git.delta.rocks / jrsonnet / refs/commits / 6bf55d21bf51

difftreelog

feat default params in function description

Yaroslav Bolyukin2024-05-19parent: #b5d51b9.patch.diff
in: master

5 files changed

modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/error.rs
1use std::{2	cmp::Ordering,3	fmt::{Debug, Display},4	path::PathBuf,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError, ObjValue};1415pub(crate) fn format_found(list: &[IStr], what: &str) -> String {16	if list.is_empty() {17		return String::new();18	}19	let mut out = String::new();20	out.push_str("\nThere is ");21	out.push_str(what);22	if list.len() > 1 {23		out.push('s');24	}25	out.push_str(" with similar name");26	if list.len() > 1 {27		out.push('s');28	}29	out.push_str(" present: ");30	for (i, v) in list.iter().enumerate() {31		if i != 0 {32			out.push_str(", ");33		}34		out.push_str(v as &str);35	}36	out37}3839fn format_signature(sig: &FunctionSignature) -> String {40	let mut out = String::new();41	out.push_str("\nFunction has the following signature: ");42	out.push('(');43	if sig.is_empty() {44		out.push_str("/*no arguments*/");45	} else {46		for (i, (name, has_default)) in sig.iter().enumerate() {47			if i != 0 {48				out.push_str(", ");49			}50			if let Some(name) = name {51				out.push_str(name);52			} else {53				out.push_str("<unnamed>");54			}55			if *has_default {56				out.push_str(" = <default>");57			}58		}59	}60	out.push(')');61	out62}6364const fn format_empty_str(str: &str) -> &str {65	if str.is_empty() {66		"\"\" (empty string)"67	} else {68		str69	}70}7172pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {73	let mut heap = Vec::new();74	for field in v.fields_ex(75		true,76		#[cfg(feature = "exp-preserve-order")]77		false,78	) {79		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());80		if conf < 0.8 {81			continue;82		}83		assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");8485		heap.push((conf, field));86	}87	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));88	heap.into_iter().map(|v| v.1).collect()89}9091type FunctionSignature = Vec<(Option<IStr>, bool)>;9293/// Possible errors94#[allow(missing_docs)]95#[derive(Error, Debug, Clone, Trace)]96#[non_exhaustive]97pub enum ErrorKind {98	#[error("intrinsic not found: {0}")]99	IntrinsicNotFound(IStr),100101	#[error("operator {0} does not operate on type {1}")]102	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),103	#[error("binary operation {1} {0} {2} is not implemented")]104	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),105106	#[error("no top level object in this context")]107	NoTopLevelObjectFound,108	#[error("self is only usable inside objects")]109	CantUseSelfOutsideOfObject,110	#[error("no super found")]111	NoSuperFound,112113	#[error("for loop can only iterate over arrays")]114	InComprehensionCanOnlyIterateOverArray,115116	#[error("array out of bounds: {0} is not within [0,{1})")]117	ArrayBoundsError(isize, usize),118	#[error("string out of bounds: {0} is not within [0,{1})")]119	StringBoundsError(usize, usize),120121	#[error("assert failed: {}", format_empty_str(.0))]122	AssertionFailed(IStr),123124	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]125	VariableIsNotDefined(IStr, Vec<IStr>),126	#[error("duplicate local var: {0}")]127	DuplicateLocalVar(IStr),128129	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]130	TypeMismatch(&'static str, Vec<ValType>, ValType),131	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]132	NoSuchField(IStr, Vec<IStr>),133134	#[error("only functions can be called, got {0}")]135	OnlyFunctionsCanBeCalledGot(ValType),136	#[error("parameter {0} is not defined")]137	UnknownFunctionParameter(String),138	#[error("argument {0} is already bound")]139	BindingParameterASecondTime(IStr),140	#[error("too many args, function has {0}{}", format_signature(.1))]141	TooManyArgsFunctionHas(usize, FunctionSignature),142	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]143	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),144145	#[error("external variable is not defined: {0}")]146	UndefinedExternalVariable(IStr),147148	#[error("field name should be string, got {0}")]149	FieldMustBeStringGot(ValType),150	#[error("duplicate field name: {}", format_empty_str(.0))]151	DuplicateFieldName(IStr),152153	#[error("attempted to index array with string {}", format_empty_str(.0))]154	AttemptedIndexAnArrayWithString(IStr),155	#[error("{0} index type should be {1}, got {2}")]156	ValueIndexMustBeTypeGot(ValType, ValType, ValType),157	#[error("cant index into {0}")]158	CantIndexInto(ValType),159	#[error("{0} is not indexable")]160	ValueIsNotIndexable(ValType),161162	#[error("super can't be used standalone")]163	StandaloneSuper,164165	#[error("can't resolve {1} from {0}")]166	ImportFileNotFound(SourcePath, String),167	#[error("can't resolve absolute {0}")]168	AbsoluteImportFileNotFound(PathBuf),169	#[error("resolved file not found: {:?}", .0)]170	ResolvedFileNotFound(SourcePath),171	#[error("can't import {0}: is a directory")]172	ImportIsADirectory(SourcePath),173	#[error("imported file is not valid utf-8: {0:?}")]174	ImportBadFileUtf8(SourcePath),175	#[error("import io error: {0}")]176	ImportIo(String),177	#[error("tried to import {1} from {0}, but imports are not supported")]178	ImportNotSupported(SourcePath, String),179	#[error("tried to import {0}, but absolute imports are not supported")]180	AbsoluteImportNotSupported(PathBuf),181	#[error("can't import from virtual file")]182	CantImportFromVirtualFile,183	#[error(184		"syntax error: {}",185		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225186		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {187			format!(188				"expected {}, got {:?}",189				.error.expected,190				.path.code().chars().nth(error.location.offset)191				.map_or_else(|| "EOF".into(), |c| c.to_string())192			)193		}, |v| v[3..].into())}194	)]195	ImportSyntaxError {196		path: Source,197		#[trace(skip)]198		error: Box<jrsonnet_parser::ParseError>,199	},200201	#[error("runtime error: {}", format_empty_str(.0))]202	RuntimeError(IStr),203	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]204	StackOverflow,205	#[error("infinite recursion detected")]206	InfiniteRecursionDetected,207	#[error("tried to index by fractional value")]208	FractionalIndex,209	#[error("attempted to divide by zero")]210	DivisionByZero,211212	#[error("string manifest output is not an string")]213	StringManifestOutputIsNotAString,214	#[error("stream manifest output is not an array")]215	StreamManifestOutputIsNotAArray,216	#[error("multi manifest output is not an object")]217	MultiManifestOutputIsNotAObject,218219	#[error("cant recurse stream manifest")]220	StreamManifestOutputCannotBeRecursed,221	#[error("stream manifest output cannot consist of raw strings")]222	StreamManifestCannotNestString,223224	#[error("{}", format_empty_str(.0))]225	ImportCallbackError(String),226	#[error("invalid unicode codepoint: {0}")]227	InvalidUnicodeCodepointGot(u32),228229	#[error("format error: {0}")]230	Format(#[from] FormatError),231	#[error("type error: {0}")]232	TypeError(TypeLocError),233234	#[cfg(feature = "anyhow-error")]235	#[error(transparent)]236	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),237}238239#[cfg(feature = "anyhow-error")]240impl From<anyhow::Error> for Error {241	fn from(e: anyhow::Error) -> Self {242		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))243	}244}245246impl From<ErrorKind> for Error {247	fn from(e: ErrorKind) -> Self {248		Self::new(e)249	}250}251252/// Single stack trace frame253#[derive(Clone, Debug, Trace)]254pub struct StackTraceElement {255	/// Source of this frame256	/// Some frames only act as description, without attached source257	pub location: Option<ExprLocation>,258	/// Frame description259	pub desc: String,260}261#[derive(Debug, Clone, Trace)]262pub struct StackTrace(pub Vec<StackTraceElement>);263264#[derive(Clone, Trace)]265pub struct Error(Box<(ErrorKind, StackTrace)>);266impl Error {267	pub fn new(e: ErrorKind) -> Self {268		Self(Box::new((e, StackTrace(vec![]))))269	}270271	pub const fn error(&self) -> &ErrorKind {272		&(self.0).0273	}274	pub fn error_mut(&mut self) -> &mut ErrorKind {275		&mut (self.0).0276	}277	pub const fn trace(&self) -> &StackTrace {278		&(self.0).1279	}280	pub fn trace_mut(&mut self) -> &mut StackTrace {281		&mut (self.0).1282	}283}284impl Display for Error {285	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {286		writeln!(f, "{}", self.0 .0)?;287		for el in &self.0 .1 .0 {288			write!(f, "\t{}", el.desc)?;289			if let Some(loc) = &el.location {290				write!(f, "at {}", loc.0 .0 .0)?;291				loc.0.map_source_locations(&[loc.1, loc.2]);292			}293			writeln!(f)?;294		}295		Ok(())296	}297}298impl Debug for Error {299	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {300		f.debug_tuple("LocError").field(&self.0).finish()301	}302}303impl std::error::Error for Error {}304305pub trait ErrorSource {306	fn to_location(self) -> Option<ExprLocation>;307}308impl ErrorSource for &LocExpr {309	fn to_location(self) -> Option<ExprLocation> {310		Some(self.1.clone())311	}312}313impl ErrorSource for &ExprLocation {314	fn to_location(self) -> Option<ExprLocation> {315		Some(self.clone())316	}317}318impl ErrorSource for CallLocation<'_> {319	fn to_location(self) -> Option<ExprLocation> {320		self.0.cloned()321	}322}323324pub type Result<V, E = Error> = std::result::Result<V, E>;325pub trait ResultExt: Sized {326	#[must_use]327	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;328	#[must_use]329	fn description(self, msg: &str) -> Self {330		self.with_description(|| msg)331	}332333	#[must_use]334	fn with_description_src<O: Into<String>>(335		self,336		src: impl ErrorSource,337		msg: impl FnOnce() -> O,338	) -> Self;339	#[must_use]340	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {341		self.with_description_src(src, || msg)342	}343}344impl<T> ResultExt for Result<T, Error> {345	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {346		if let Err(e) = &mut self {347			let trace = e.trace_mut();348			trace.0.push(StackTraceElement {349				location: None,350				desc: msg().into(),351			});352		}353		self354	}355356	fn with_description_src<O: Into<String>>(357		mut self,358		src: impl ErrorSource,359		msg: impl FnOnce() -> O,360	) -> Self {361		if let Err(e) = &mut self {362			let trace = e.trace_mut();363			trace.0.push(StackTraceElement {364				location: src.to_location(),365				desc: msg().into(),366			});367		}368		self369	}370}371372#[macro_export]373macro_rules! bail {374	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {375		return Err($w$(::$i)*$(($($tt)*))?.into())376	};377	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {378		return Err($w$(::$i)*$({$($tt)*})?.into())379	};380	($l:literal$(, $($tt:tt)*)?) => {381		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())382	};383}384385#[macro_export]386macro_rules! runtime_error {387	($l:literal$(, $($tt:tt)*)?) => {388		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))389	};390}
after · crates/jrsonnet-evaluator/src/error.rs
1use std::{2	cmp::Ordering,3	fmt::{Debug, Display},4	path::PathBuf,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	function::{builtin::ParamDefault, CallLocation},15	stdlib::format::FormatError,16	typed::TypeLocError,17	ObjValue,18};1920pub(crate) fn format_found(list: &[IStr], what: &str) -> String {21	if list.is_empty() {22		return String::new();23	}24	let mut out = String::new();25	out.push_str("\nThere is ");26	out.push_str(what);27	if list.len() > 1 {28		out.push('s');29	}30	out.push_str(" with similar name");31	if list.len() > 1 {32		out.push('s');33	}34	out.push_str(" present: ");35	for (i, v) in list.iter().enumerate() {36		if i != 0 {37			out.push_str(", ");38		}39		out.push_str(v as &str);40	}41	out42}4344fn format_signature(sig: &FunctionSignature) -> String {45	let mut out = String::new();46	out.push_str("\nFunction has the following signature: ");47	out.push('(');48	if sig.is_empty() {49		out.push_str("/*no arguments*/");50	} else {51		for (i, (name, default)) in sig.iter().enumerate() {52			if i != 0 {53				out.push_str(", ");54			}55			if let Some(name) = name {56				out.push_str(name);57			} else {58				out.push_str("<unnamed>");59			}60			match default {61				ParamDefault::None => {}62				ParamDefault::Exists => out.push_str(" = <default>"),63				ParamDefault::Literal(lit) => {64					out.push_str(" = ");65					out.push_str(lit);66				}67			}68		}69	}70	out.push(')');71	out72}7374const fn format_empty_str(str: &str) -> &str {75	if str.is_empty() {76		"\"\" (empty string)"77	} else {78		str79	}80}8182pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {83	let mut heap = Vec::new();84	for field in v.fields_ex(85		true,86		#[cfg(feature = "exp-preserve-order")]87		false,88	) {89		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());90		if conf < 0.8 {91			continue;92		}93		assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");9495		heap.push((conf, field));96	}97	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));98	heap.into_iter().map(|v| v.1).collect()99}100101type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;102103/// Possible errors104#[allow(missing_docs)]105#[derive(Error, Debug, Clone, Trace)]106#[non_exhaustive]107pub enum ErrorKind {108	#[error("intrinsic not found: {0}")]109	IntrinsicNotFound(IStr),110111	#[error("operator {0} does not operate on type {1}")]112	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),113	#[error("binary operation {1} {0} {2} is not implemented")]114	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),115116	#[error("no top level object in this context")]117	NoTopLevelObjectFound,118	#[error("self is only usable inside objects")]119	CantUseSelfOutsideOfObject,120	#[error("no super found")]121	NoSuperFound,122123	#[error("for loop can only iterate over arrays")]124	InComprehensionCanOnlyIterateOverArray,125126	#[error("array out of bounds: {0} is not within [0,{1})")]127	ArrayBoundsError(isize, usize),128	#[error("string out of bounds: {0} is not within [0,{1})")]129	StringBoundsError(usize, usize),130131	#[error("assert failed: {}", format_empty_str(.0))]132	AssertionFailed(IStr),133134	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]135	VariableIsNotDefined(IStr, Vec<IStr>),136	#[error("duplicate local var: {0}")]137	DuplicateLocalVar(IStr),138139	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]140	TypeMismatch(&'static str, Vec<ValType>, ValType),141	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]142	NoSuchField(IStr, Vec<IStr>),143144	#[error("only functions can be called, got {0}")]145	OnlyFunctionsCanBeCalledGot(ValType),146	#[error("parameter {0} is not defined")]147	UnknownFunctionParameter(String),148	#[error("argument {0} is already bound")]149	BindingParameterASecondTime(IStr),150	#[error("too many args, function has {0}{}", format_signature(.1))]151	TooManyArgsFunctionHas(usize, FunctionSignature),152	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]153	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),154155	#[error("external variable is not defined: {0}")]156	UndefinedExternalVariable(IStr),157158	#[error("field name should be string, got {0}")]159	FieldMustBeStringGot(ValType),160	#[error("duplicate field name: {}", format_empty_str(.0))]161	DuplicateFieldName(IStr),162163	#[error("attempted to index array with string {}", format_empty_str(.0))]164	AttemptedIndexAnArrayWithString(IStr),165	#[error("{0} index type should be {1}, got {2}")]166	ValueIndexMustBeTypeGot(ValType, ValType, ValType),167	#[error("cant index into {0}")]168	CantIndexInto(ValType),169	#[error("{0} is not indexable")]170	ValueIsNotIndexable(ValType),171172	#[error("super can't be used standalone")]173	StandaloneSuper,174175	#[error("can't resolve {1} from {0}")]176	ImportFileNotFound(SourcePath, String),177	#[error("can't resolve absolute {0}")]178	AbsoluteImportFileNotFound(PathBuf),179	#[error("resolved file not found: {:?}", .0)]180	ResolvedFileNotFound(SourcePath),181	#[error("can't import {0}: is a directory")]182	ImportIsADirectory(SourcePath),183	#[error("imported file is not valid utf-8: {0:?}")]184	ImportBadFileUtf8(SourcePath),185	#[error("import io error: {0}")]186	ImportIo(String),187	#[error("tried to import {1} from {0}, but imports are not supported")]188	ImportNotSupported(SourcePath, String),189	#[error("tried to import {0}, but absolute imports are not supported")]190	AbsoluteImportNotSupported(PathBuf),191	#[error("can't import from virtual file")]192	CantImportFromVirtualFile,193	#[error(194		"syntax error: {}",195		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225196		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {197			format!(198				"expected {}, got {:?}",199				.error.expected,200				.path.code().chars().nth(error.location.offset)201				.map_or_else(|| "EOF".into(), |c| c.to_string())202			)203		}, |v| v[3..].into())}204	)]205	ImportSyntaxError {206		path: Source,207		#[trace(skip)]208		error: Box<jrsonnet_parser::ParseError>,209	},210211	#[error("runtime error: {}", format_empty_str(.0))]212	RuntimeError(IStr),213	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]214	StackOverflow,215	#[error("infinite recursion detected")]216	InfiniteRecursionDetected,217	#[error("tried to index by fractional value")]218	FractionalIndex,219	#[error("attempted to divide by zero")]220	DivisionByZero,221222	#[error("string manifest output is not an string")]223	StringManifestOutputIsNotAString,224	#[error("stream manifest output is not an array")]225	StreamManifestOutputIsNotAArray,226	#[error("multi manifest output is not an object")]227	MultiManifestOutputIsNotAObject,228229	#[error("cant recurse stream manifest")]230	StreamManifestOutputCannotBeRecursed,231	#[error("stream manifest output cannot consist of raw strings")]232	StreamManifestCannotNestString,233234	#[error("{}", format_empty_str(.0))]235	ImportCallbackError(String),236	#[error("invalid unicode codepoint: {0}")]237	InvalidUnicodeCodepointGot(u32),238239	#[error("format error: {0}")]240	Format(#[from] FormatError),241	#[error("type error: {0}")]242	TypeError(TypeLocError),243244	#[cfg(feature = "anyhow-error")]245	#[error(transparent)]246	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),247}248249#[cfg(feature = "anyhow-error")]250impl From<anyhow::Error> for Error {251	fn from(e: anyhow::Error) -> Self {252		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))253	}254}255256impl From<ErrorKind> for Error {257	fn from(e: ErrorKind) -> Self {258		Self::new(e)259	}260}261262/// Single stack trace frame263#[derive(Clone, Debug, Trace)]264pub struct StackTraceElement {265	/// Source of this frame266	/// Some frames only act as description, without attached source267	pub location: Option<ExprLocation>,268	/// Frame description269	pub desc: String,270}271#[derive(Debug, Clone, Trace)]272pub struct StackTrace(pub Vec<StackTraceElement>);273274#[derive(Clone, Trace)]275pub struct Error(Box<(ErrorKind, StackTrace)>);276impl Error {277	pub fn new(e: ErrorKind) -> Self {278		Self(Box::new((e, StackTrace(vec![]))))279	}280281	pub const fn error(&self) -> &ErrorKind {282		&(self.0).0283	}284	pub fn error_mut(&mut self) -> &mut ErrorKind {285		&mut (self.0).0286	}287	pub const fn trace(&self) -> &StackTrace {288		&(self.0).1289	}290	pub fn trace_mut(&mut self) -> &mut StackTrace {291		&mut (self.0).1292	}293}294impl Display for Error {295	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {296		writeln!(f, "{}", self.0 .0)?;297		for el in &self.0 .1 .0 {298			write!(f, "\t{}", el.desc)?;299			if let Some(loc) = &el.location {300				write!(f, "at {}", loc.0 .0 .0)?;301				loc.0.map_source_locations(&[loc.1, loc.2]);302			}303			writeln!(f)?;304		}305		Ok(())306	}307}308impl Debug for Error {309	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {310		f.debug_tuple("LocError").field(&self.0).finish()311	}312}313impl std::error::Error for Error {}314315pub trait ErrorSource {316	fn to_location(self) -> Option<ExprLocation>;317}318impl ErrorSource for &LocExpr {319	fn to_location(self) -> Option<ExprLocation> {320		Some(self.1.clone())321	}322}323impl ErrorSource for &ExprLocation {324	fn to_location(self) -> Option<ExprLocation> {325		Some(self.clone())326	}327}328impl ErrorSource for CallLocation<'_> {329	fn to_location(self) -> Option<ExprLocation> {330		self.0.cloned()331	}332}333334pub type Result<V, E = Error> = std::result::Result<V, E>;335pub trait ResultExt: Sized {336	#[must_use]337	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;338	#[must_use]339	fn description(self, msg: &str) -> Self {340		self.with_description(|| msg)341	}342343	#[must_use]344	fn with_description_src<O: Into<String>>(345		self,346		src: impl ErrorSource,347		msg: impl FnOnce() -> O,348	) -> Self;349	#[must_use]350	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {351		self.with_description_src(src, || msg)352	}353}354impl<T> ResultExt for Result<T, Error> {355	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {356		if let Err(e) = &mut self {357			let trace = e.trace_mut();358			trace.0.push(StackTraceElement {359				location: None,360				desc: msg().into(),361			});362		}363		self364	}365366	fn with_description_src<O: Into<String>>(367		mut self,368		src: impl ErrorSource,369		msg: impl FnOnce() -> O,370	) -> Self {371		if let Err(e) = &mut self {372			let trace = e.trace_mut();373			trace.0.push(StackTraceElement {374				location: src.to_location(),375				desc: msg().into(),376			});377		}378		self379	}380}381382#[macro_export]383macro_rules! bail {384	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {385		return Err($w$(::$i)*$(($($tt)*))?.into())386	};387	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {388		return Err($w$(::$i)*$({$($tt)*})?.into())389	};390	($l:literal$(, $($tt:tt)*)?) => {391		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())392	};393}394395#[macro_export]396macro_rules! runtime_error {397	($l:literal$(, $($tt:tt)*)?) => {398		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))399	};400}
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -33,22 +33,40 @@
 	}
 }
 
+#[derive(Clone, Copy, Debug, Trace)]
+pub enum ParamDefault {
+	None,
+	Exists,
+	Literal(&'static str),
+}
+impl ParamDefault {
+	pub const fn exists(is_exists: bool) -> Self {
+		if is_exists {
+			Self::Exists
+		} else {
+			Self::None
+		}
+	}
+}
+
 #[derive(Clone, Trace)]
 pub struct BuiltinParam {
 	name: ParamName,
-	has_default: bool,
+	default: ParamDefault,
 }
 impl BuiltinParam {
-	pub const fn new(name: ParamName, has_default: bool) -> Self {
-		Self { name, has_default }
+	pub const fn new(name: ParamName, default: ParamDefault) -> Self {
+		Self { name, default }
 	}
 	/// Parameter name for named call parsing
 	pub fn name(&self) -> &ParamName {
 		&self.name
 	}
-	/// Is implementation allowed to return empty value
+	pub fn default(&self) -> ParamDefault {
+		self.default
+	}
 	pub fn has_default(&self) -> bool {
-		self.has_default
+		!matches!(self.default, ParamDefault::None)
 	}
 }
 
@@ -87,7 +105,7 @@
 				.into_iter()
 				.map(|n| BuiltinParam {
 					name: ParamName::new_dynamic(n),
-					has_default: false,
+					default: ParamDefault::Exists,
 				})
 				.collect(),
 			handler: tb!(handler),
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -8,7 +8,7 @@
 
 use self::{
 	arglike::OptionalContext,
-	builtin::{Builtin, BuiltinParam, ParamName, StaticBuiltin},
+	builtin::{Builtin, BuiltinParam, ParamDefault, ParamName, StaticBuiltin},
 	native::NativeDesc,
 	parse::{parse_default_function_call, parse_function_call},
 };
@@ -142,7 +142,7 @@
 							.as_ref()
 							.map(IStr::to_string)
 							.map_or(ParamName::ANONYMOUS, ParamName::new_dynamic),
-						p.1.is_some(),
+						ParamDefault::exists(p.1.is_some()),
 					)
 				})
 				.collect(),
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -10,6 +10,7 @@
 	destructure::destruct,
 	error::{ErrorKind::*, Result},
 	evaluate_named,
+	function::builtin::ParamDefault,
 	gc::GcHashMap,
 	val::ThunkValue,
 	Context, Pending, Thunk, Val,
@@ -49,7 +50,10 @@
 	if args.unnamed_len() > params.len() {
 		bail!(TooManyArgsFunctionHas(
 			params.len(),
-			params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
+			params
+				.iter()
+				.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
+				.collect()
 		))
 	}
 
@@ -127,7 +131,10 @@
 				if !found {
 					bail!(FunctionParameterNotBoundInCall(
 						param.0.clone().name(),
-						params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
+						params
+							.iter()
+							.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
+							.collect()
 					));
 				}
 			}
@@ -163,7 +170,7 @@
 			params.len(),
 			params
 				.iter()
-				.map(|p| (p.name().as_str().map(IStr::from), p.has_default()))
+				.map(|p| (p.name().as_str().map(IStr::from), p.default()))
 				.collect()
 		))
 	}
@@ -211,7 +218,7 @@
 						param.name().as_str().map(IStr::from),
 						params
 							.iter()
-							.map(|p| (p.name().as_str().map(IStr::from), p.has_default()))
+							.map(|p| (p.name().as_str().map(IStr::from), p.default()))
 							.collect()
 					));
 				}
@@ -232,7 +239,10 @@
 		fn get(self: Box<Self>) -> Result<Val> {
 			Err(FunctionParameterNotBoundInCall(
 				Some(self.0.clone()),
-				self.1.iter().map(|p| (p.0.name(), p.1.is_some())).collect(),
+				self.1
+					.iter()
+					.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
+					.collect(),
 			)
 			.into())
 		}
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -253,10 +253,14 @@
 			let name = name
 				.as_ref()
 				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});
-			let is_optional = optionality.is_optional();
+			let default = match optionality {
+				Optionality::Required => quote!(ParamDefault::None),
+				Optionality::Optional => quote!(ParamDefault::Exists),
+				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),
+			};
 			Some(quote! {
 				#(#cfg_attrs)*
-				BuiltinParam::new(#name, #is_optional),
+				BuiltinParam::new(#name, #default),
 			})
 		}
 		ArgInfo::Lazy { is_option, name } => {
@@ -264,7 +268,7 @@
 				.as_ref()
 				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});
 			Some(quote! {
-				BuiltinParam::new(#name, #is_option),
+				BuiltinParam::new(#name, ParamDefault::exists(#is_option)),
 			})
 		}
 		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,
@@ -375,7 +379,7 @@
 		const _: () = {
 			use ::jrsonnet_evaluator::{
 				State, Val,
-				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName}, CallLocation, ArgsLike, parse::parse_builtin_call},
+				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},
 				Result, Context, typed::Typed,
 				parser::ExprLocation,
 			};