git.delta.rocks / jrsonnet / refs/commits / dad6c32364f5

difftreelog

refactor error helpers

Yaroslav Bolyukin2023-08-13parent: #81c4597.patch.diff
in: master

38 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -13,8 +13,9 @@
 };
 
 use jrsonnet_evaluator::{
+	bail,
 	error::{ErrorKind::*, Result},
-	throw, FileImportResolver, ImportResolver,
+	FileImportResolver, ImportResolver,
 };
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
@@ -80,7 +81,7 @@
 		assert!(success == 0 || success == 1);
 		if success == 0 {
 			let result = String::from_utf8(buf_intern).expect("error should be valid string");
-			throw!(ImportCallbackError(result));
+			bail!(ImportCallbackError(result));
 		}
 
 		let found_here_raw = unsafe { CStr::from_ptr(found_here) };
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -19,12 +19,12 @@
 };
 
 use jrsonnet_evaluator::{
-	apply_tla,
+	apply_tla, bail,
 	function::TlaArg,
 	gc::GcHashMap,
 	manifest::{JsonFormat, ManifestFormat, ToStringFormat},
 	stack::set_stack_depth_limit,
-	tb, throw,
+	tb,
 	trace::{CompactFormat, PathResolver, TraceFormat},
 	FileImportResolver, IStr, Result, State, Val,
 };
@@ -249,7 +249,7 @@
 
 fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {
 	let Val::Obj(val) = val else {
-		throw!("expected object as multi output")
+		bail!("expected object as multi output")
 	};
 	let mut out = Vec::new();
 	for (k, v) in val.iter(
@@ -336,7 +336,7 @@
 
 fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {
 	let Val::Arr(val) = val else {
-		throw!("expected array as stream output")
+		bail!("expected array as stream output")
 	};
 	let mut out = Vec::new();
 	for item in val.iter() {
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -7,9 +7,9 @@
 use clap_complete::Shell;
 use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};
 use jrsonnet_evaluator::{
-	apply_tla,
+	apply_tla, bail,
 	error::{Error as JrError, ErrorKind},
-	throw, ResultExt, State, Val,
+	ResultExt, State, Val,
 };
 
 #[cfg(feature = "mimalloc")]
@@ -208,7 +208,7 @@
 			create_dir_all(dir)?;
 		}
 		let Val::Obj(obj) = val else {
-			throw!(
+			bail!(
 				"value should be object for --multi manifest, got {}",
 				val.value_type()
 			)
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -54,7 +54,7 @@
 	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
 		use std::cmp::Ordering;
 
-		use crate::throw;
+		use crate::bail;
 
 		if let Some(val) = self.0.bindings.get(&name).cloned() {
 			return Ok(val);
@@ -70,7 +70,7 @@
 		});
 		heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
 
-		throw!(VariableIsNotDefined(
+		bail!(VariableIsNotDefined(
 			name,
 			heap.into_iter().map(|(_, k)| k).collect()
 		))
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -2,7 +2,7 @@
 
 use jrsonnet_gcmodule::{Cc, Trace};
 
-use crate::{error::ErrorKind::InfiniteRecursionDetected, throw, val::ThunkValue, Result, Thunk};
+use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};
 
 // TODO: Replace with OnceCell once in std
 #[derive(Clone, Trace)]
@@ -41,7 +41,7 @@
 
 	fn get(self: Box<Self>) -> Result<Self::Output> {
 		let Some(value) = self.0.get() else {
-			throw!(InfiniteRecursionDetected);
+			bail!(InfiniteRecursionDetected);
 		};
 		Ok(value.clone())
 	}
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -370,17 +370,21 @@
 }
 
 #[macro_export]
-macro_rules! throw {
+macro_rules! bail {
 	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {
 		return Err($w$(::$i)*$(($($tt)*))?.into())
 	};
 	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {
 		return Err($w$(::$i)*$({$($tt)*})?.into())
 	};
-	($l:literal) => {
-		return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())
+	($l:literal$(, $($tt:tt)*)?) => {
+		return Err($crate::error::ErrorKind::RuntimeError(format!($l$(, $($tt)*)?).into()).into())
 	};
-	($l:literal, $($tt:tt)*) => {
-		return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())
+}
+
+#[macro_export]
+macro_rules! runtime_error {
+	($l:literal$(, $($tt:tt)*)?) => {
+		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError(format!($l$(, $($tt)*)?).into()))
 	};
 }
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,10 +3,10 @@
 use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
 
 use crate::{
+	bail,
 	error::{ErrorKind::*, Result},
 	evaluate, evaluate_method, evaluate_named,
 	gc::GcHashMap,
-	throw,
 	val::ThunkValue,
 	Context, Pending, Thunk, Val,
 };
@@ -23,7 +23,7 @@
 		Destruct::Full(v) => {
 			let old = new_bindings.insert(v.clone(), parent);
 			if old.is_some() {
-				throw!(DuplicateLocalVar(v.clone()))
+				bail!(DuplicateLocalVar(v.clone()))
 			}
 		}
 		#[cfg(feature = "exp-destruct")]
@@ -46,14 +46,14 @@
 				fn get(self: Box<Self>) -> Result<Self::Output> {
 					let v = self.parent.evaluate()?;
 					let Val::Arr(arr) = v else {
-						throw!("expected array");
+						bail!("expected array");
 					};
 					if !self.has_rest {
 						if arr.len() != self.min_len {
-							throw!("expected {} elements, got {}", self.min_len, arr.len())
+							bail!("expected {} elements, got {}", self.min_len, arr.len())
 						}
 					} else if arr.len() < self.min_len {
-						throw!(
+						bail!(
 							"expected at least {} elements, but array was only {}",
 							self.min_len,
 							arr.len()
@@ -178,17 +178,17 @@
 				fn get(self: Box<Self>) -> Result<Self::Output> {
 					let v = self.parent.evaluate()?;
 					let Val::Obj(obj) = v else {
-						throw!("expected object");
+						bail!("expected object");
 					};
 					for field in &self.field_names {
 						if !obj.has_field_ex(field.clone(), true) {
-							throw!("missing field: {}", field);
+							bail!("missing field: {field}");
 						}
 					}
 					if !self.has_rest {
 						let len = obj.len();
 						if len != self.field_names.len() {
-							throw!("too many fields, and rest not found");
+							bail!("too many fields, and rest not found");
 						}
 					}
 					Ok(obj)
@@ -310,7 +310,7 @@
 				}),
 			);
 			if old.is_some() {
-				throw!(DuplicateLocalVar(name.clone()))
+				bail!(DuplicateLocalVar(name.clone()))
 			}
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,11 +11,11 @@
 use self::destructure::destruct;
 use crate::{
 	arr::ArrValue,
+	bail,
 	destructure::evaluate_dest,
 	error::{suggest_object_fields, ErrorKind::*},
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
 	function::{CallLocation, FuncDesc, FuncVal},
-	throw,
 	typed::Typed,
 	val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},
 	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
@@ -150,7 +150,7 @@
 					evaluate_comp(ctx, &specs[1..], callback)?;
 				}
 			}
-			_ => throw!(InComprehensionCanOnlyIterateOverArray),
+			_ => bail!(InComprehensionCanOnlyIterateOverArray),
 		},
 	}
 	Ok(())
@@ -375,7 +375,7 @@
 				State::push(loc, || format!("function <{}> call", f.name()), body)?
 			}
 		}
-		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
+		v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),
 	})
 }
 
@@ -393,9 +393,9 @@
 			|| "assertion failure".to_owned(),
 			|| {
 				if let Some(msg) = msg {
-					throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));
+					bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));
 				}
-				throw!(AssertionFailed(Val::Null.to_string()?));
+				bail!(AssertionFailed(Val::Null.to_string()?));
 			},
 		)?;
 	}
@@ -457,12 +457,12 @@
 						if part.null_coaelse {
 							return Ok(Val::Null);
 						}
-						throw!(NoSuperFound)
+						bail!(NoSuperFound)
 					};
 					let name = evaluate(ctx.clone(), &part.value)?;
 
 					let Val::Str(name) = name else {
-						throw!(ValueIndexMustBeTypeGot(
+						bail!(ValueIndexMustBeTypeGot(
 							ValType::Obj,
 							ValType::Str,
 							name.value_type(),
@@ -483,7 +483,7 @@
 						None => {
 							let suggestions = suggest_object_fields(super_obj, name.clone());
 
-							throw!(NoSuchField(name, suggestions))
+							bail!(NoSuchField(name, suggestions))
 						}
 					}
 				}
@@ -502,25 +502,25 @@
 						None => {
 							let suggestions = suggest_object_fields(&v, key.clone().into_flat());
 
-							throw!(NoSuchField(key.clone().into_flat(), suggestions))
+							bail!(NoSuchField(key.clone().into_flat(), suggestions))
 						}
 					},
-					(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
+					(Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(
 						ValType::Obj,
 						ValType::Str,
 						n.value_type(),
 					)),
 					(Val::Arr(v), Val::Num(n)) => {
 						if n.fract() > f64::EPSILON {
-							throw!(FractionalIndex)
+							bail!(FractionalIndex)
 						}
 						v.get(n as usize)?
 							.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
 					}
 					(Val::Arr(_), Val::Str(n)) => {
-						throw!(AttemptedIndexAnArrayWithString(n.into_flat()))
+						bail!(AttemptedIndexAnArrayWithString(n.into_flat()))
 					}
-					(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
+					(Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(
 						ValType::Arr,
 						ValType::Num,
 						n.value_type(),
@@ -537,18 +537,18 @@
 							.into();
 						if v.is_empty() {
 							let size = s.into_flat().chars().count();
-							throw!(StringBoundsError(n as usize, size))
+							bail!(StringBoundsError(n as usize, size))
 						}
 						StrValue::Flat(v)
 					}),
-					(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
+					(Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(
 						ValType::Str,
 						ValType::Num,
 						n.value_type(),
 					)),
 					#[cfg(feature = "exp-null-coaelse")]
 					(Val::Null, _) if part.null_coaelse => return Ok(Val::Null),
-					(v, _) => throw!(CantIndexInto(v.value_type())),
+					(v, _) => bail!(CantIndexInto(v.value_type())),
 				};
 			}
 			indexable
@@ -612,7 +612,7 @@
 		ErrorStmt(e) => State::push(
 			CallLocation::new(loc),
 			|| "error statement".to_owned(),
-			|| throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
+			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
 		)?,
 		IfElse {
 			cond,
@@ -661,7 +661,7 @@
 		}
 		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
 			let Expr::Str(path) = &*path.0 else {
-				throw!("computed imports are not supported")
+				bail!("computed imports are not supported")
 			};
 			let tmp = loc.clone().0;
 			let s = ctx.state();
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -4,10 +4,10 @@
 
 use crate::{
 	arr::ArrValue,
+	bail,
 	error::ErrorKind::*,
 	evaluate,
 	stdlib::std_format,
-	throw,
 	typed::Typed,
 	val::{equals, StrValue},
 	Context, Result, Val,
@@ -21,7 +21,7 @@
 		(Minus, Num(n)) => Num(-*n),
 		(Not, Bool(v)) => Bool(!v),
 		(BitNot, Num(n)) => Num(!(*n as i64) as f64),
-		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
+		(op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
 	})
 }
 
@@ -49,7 +49,7 @@
 		(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
 		#[cfg(feature = "exp-bigint")]
 		(BigInt(a), BigInt(b)) => BigInt(Box::new((&**a).clone() + (&**b).clone())),
-		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
+		_ => bail!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Add,
 			a.value_type(),
 			b.value_type(),
@@ -62,14 +62,14 @@
 	match (a, b) {
 		(Num(a), Num(b)) => {
 			if *b == 0.0 {
-				throw!(DivisionByZero)
+				bail!(DivisionByZero)
 			}
 			Ok(Num(a % b))
 		}
 		(Str(str), vals) => {
 			String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)
 		}
-		(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
+		(a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Mod,
 			a.value_type(),
 			b.value_type()
@@ -124,7 +124,7 @@
 			}
 			a.len().cmp(&b.len())
 		}
-		(_, _) => throw!(BinaryOperatorDoesNotOperateOnValues(
+		(_, _) => bail!(BinaryOperatorDoesNotOperateOnValues(
 			op,
 			a.value_type(),
 			b.value_type()
@@ -159,7 +159,7 @@
 		(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
 		(Num(v1), Div, Num(v2)) => {
 			if *v2 == 0.0 {
-				throw!(DivisionByZero)
+				bail!(DivisionByZero)
 			}
 			Val::new_checked_num(v1 / v2)?
 		}
@@ -171,14 +171,14 @@
 		(Num(v1), BitXor, Num(v2)) => Num((*v1 as i64 ^ *v2 as i64) as f64),
 		(Num(v1), Lhs, Num(v2)) => {
 			if *v2 < 0.0 {
-				throw!("shift by negative exponent")
+				bail!("shift by negative exponent")
 			}
 			let exp = ((*v2 as i64) & 63) as u32;
 			Num((*v1 as i64).wrapping_shl(exp) as f64)
 		}
 		(Num(v1), Rhs, Num(v2)) => {
 			if *v2 < 0.0 {
-				throw!("shift by negative exponent")
+				bail!("shift by negative exponent")
 			}
 			let exp = ((*v2 as i64) & 63) as u32;
 			Num((*v1 as i64).wrapping_shr(exp) as f64)
@@ -190,7 +190,7 @@
 		#[cfg(feature = "exp-bigint")]
 		(BigInt(a), Sub, BigInt(b)) => BigInt(Box::new((&**a).clone() - (&**b).clone())),
 
-		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
+		_ => bail!(BinaryOperatorDoesNotOperateOnValues(
 			op,
 			a.value_type(),
 			b.value_type(),
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -3,14 +3,7 @@
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{ArgsDesc, LocExpr};
 
-use crate::{
-	error::Result,
-	evaluate,
-	gc::GcHashMap,
-	typed::Typed,
-	val::{StrValue, ThunkValue},
-	Context, Thunk, Val,
-};
+use crate::{evaluate, gc::GcHashMap, typed::Typed, val::ThunkValue, Context, Result, Thunk, Val};
 
 /// Marker for arguments, which can be evaluated with context set to None
 pub trait OptionalContext {}
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -4,7 +4,7 @@
 use jrsonnet_interner::IStr;
 
 use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
-use crate::{error::Result, gc::TraceBox, tb, Context, Val};
+use crate::{gc::TraceBox, tb, Context, Result, Val};
 
 /// Can't have str | IStr, because constant BuiltinParam causes
 /// E0492: constant functions cannot refer to interior mutable data
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -6,11 +6,11 @@
 
 use super::{arglike::ArgsLike, builtin::BuiltinParam};
 use crate::{
+	bail,
 	destructure::destruct,
 	error::{ErrorKind::*, Result},
 	evaluate_named,
 	gc::GcHashMap,
-	throw,
 	val::ThunkValue,
 	Context, Pending, Thunk, Val,
 };
@@ -47,7 +47,7 @@
 	let mut passed_args =
 		GcHashMap::with_capacity(params.iter().map(|p| p.0.capacity_hint()).sum());
 	if args.unnamed_len() > params.len() {
-		throw!(TooManyArgsFunctionHas(
+		bail!(TooManyArgsFunctionHas(
 			params.len(),
 			params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
 		))
@@ -71,10 +71,10 @@
 	args.named_iter(ctx, tailstrict, &mut |name, value| {
 		// FIXME: O(n) for arg existence check
 		if !params.iter().any(|p| p.0.name().as_ref() == Some(name)) {
-			throw!(UnknownFunctionParameter((name as &str).to_owned()));
+			bail!(UnknownFunctionParameter((name as &str).to_owned()));
 		}
 		if passed_args.insert(name.clone(), value).is_some() {
-			throw!(BindingParameterASecondTime(name.clone()));
+			bail!(BindingParameterASecondTime(name.clone()));
 		}
 		filled_named += 1;
 		Ok(())
@@ -125,7 +125,7 @@
 					}
 				});
 				if !found {
-					throw!(FunctionParameterNotBoundInCall(
+					bail!(FunctionParameterNotBoundInCall(
 						param.0.clone().name(),
 						params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
 					));
@@ -159,7 +159,7 @@
 ) -> Result<Vec<Option<Thunk<Val>>>> {
 	let mut passed_args: Vec<Option<Thunk<Val>>> = vec![None; params.len()];
 	if args.unnamed_len() > params.len() {
-		throw!(TooManyArgsFunctionHas(
+		bail!(TooManyArgsFunctionHas(
 			params.len(),
 			params
 				.iter()
@@ -183,7 +183,7 @@
 			.position(|p| p.name() == name)
 			.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
 		if replace(&mut passed_args[id], Some(arg)).is_some() {
-			throw!(BindingParameterASecondTime(name.clone()));
+			bail!(BindingParameterASecondTime(name.clone()));
 		}
 		filled_args += 1;
 		Ok(())
@@ -207,7 +207,7 @@
 					}
 				});
 				if !found {
-					throw!(FunctionParameterNotBoundInCall(
+					bail!(FunctionParameterNotBoundInCall(
 						param.name().as_str().map(IStr::from),
 						params
 							.iter()
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -12,8 +12,8 @@
 use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
 
 use crate::{
+	bail,
 	error::{ErrorKind::*, Result},
-	throw,
 };
 
 /// Implements file resolution logic for `import` and `importStr`
@@ -25,14 +25,14 @@
 	/// `from` should only be returned from [`ImportResolver::resolve`], or from other defined file, any other value
 	/// may result in panic
 	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
-		throw!(ImportNotSupported(from.clone(), path.into()))
+		bail!(ImportNotSupported(from.clone(), path.into()))
 	}
 	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
 		self.resolve_from(&SourcePath::default(), path)
 	}
 	/// Resolves absolute path, doesn't supports jpath and other fancy things
 	fn resolve(&self, path: &Path) -> Result<SourcePath> {
-		throw!(AbsoluteImportNotSupported(path.to_owned()))
+		bail!(AbsoluteImportNotSupported(path.to_owned()))
 	}
 
 	/// Load resolved file
@@ -110,16 +110,16 @@
 					)));
 				}
 			}
-			throw!(ImportFileNotFound(from.clone(), path.to_owned()))
+			bail!(ImportFileNotFound(from.clone(), path.to_owned()))
 		}
 	}
 	fn resolve(&self, path: &Path) -> Result<SourcePath> {
 		let meta = match fs::metadata(path) {
 			Ok(v) => v,
 			Err(e) if e.kind() == ErrorKind::NotFound => {
-				throw!(AbsoluteImportFileNotFound(path.to_owned()))
+				bail!(AbsoluteImportFileNotFound(path.to_owned()))
 			}
-			Err(e) => throw!(ImportIo(e.to_string())),
+			Err(e) => bail!(ImportIo(e.to_string())),
 		};
 		if meta.is_file() {
 			Ok(SourcePath::new(SourceFile::new(
@@ -138,7 +138,7 @@
 		let path = if let Some(f) = id.downcast_ref::<SourceFile>() {
 			f.path()
 		} else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {
-			throw!(ImportIsADirectory(id.clone()))
+			bail!(ImportIsADirectory(id.clone()))
 		} else {
 			unreachable!("other types are not supported in resolve");
 		};
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -620,6 +620,6 @@
 	where
 		T: std::fmt::Display,
 	{
-		JrError::new(ErrorKind::RuntimeError(format!("serde: {msg}").into()))
+		runtime_error!("serde: {msg}")
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -354,7 +354,7 @@
 		}
 		let parsed = file.parsed.as_ref().expect("just set").clone();
 		if file.evaluating {
-			throw!(InfiniteRecursionDetected)
+			bail!(InfiniteRecursionDetected)
 		}
 		file.evaluating = true;
 		// Dropping file cache guard here, as evaluation may use this map too
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,9 +1,6 @@
 use std::{borrow::Cow, fmt::Write};
 
-use crate::{
-	error::{ErrorKind::*, Result},
-	throw, State, Val,
-};
+use crate::{bail, Result, State, Val};
 
 pub trait ManifestFormat {
 	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -268,7 +265,7 @@
 			}
 			buf.push('}');
 		}
-		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+		Val::Func(_) => bail!("tried to manifest function"),
 	};
 	Ok(())
 }
@@ -292,7 +289,7 @@
 impl ManifestFormat for StringFormat {
 	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
 		let Val::Str(s) = val else {
-			throw!(
+			bail!(
 				"output should be string for string manifest format, got {}",
 				val.value_type()
 			)
@@ -309,7 +306,7 @@
 impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {
 	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
 		let Val::Arr(arr) = val else {
-			throw!(
+			bail!(
 				"output should be array for yaml stream format, got {}",
 				val.value_type()
 			)
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{ExprLocation, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	error::{suggest_object_fields, Error, ErrorKind::*},17	function::CallLocation,18	gc::{GcHashMap, GcHashSet, TraceBox},19	operator::evaluate_add_op,20	tb, throw,21	val::{ArrValue, ThunkValue},22	MaybeUnbound, Result, State, Thunk, Unbound, Val,23};2425#[cfg(not(feature = "exp-preserve-order"))]26mod ordering {27	#![allow(28		// This module works as stub for preserve-order feature29		clippy::unused_self,30	)]3132	use jrsonnet_gcmodule::Trace;3334	#[derive(Clone, Copy, Default, Debug, Trace)]35	pub struct FieldIndex(());36	impl FieldIndex {37		pub const fn next(self) -> Self {38			Self(())39		}40	}4142	#[derive(Clone, Copy, Default, Debug, Trace)]43	pub struct SuperDepth(());44	impl SuperDepth {45		pub const fn deeper(self) -> Self {46			Self(())47		}48	}4950	#[derive(Clone, Copy)]51	pub struct FieldSortKey(());52	impl FieldSortKey {53		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {54			Self(())55		}56	}57}5859#[cfg(feature = "exp-preserve-order")]60mod ordering {61	use std::cmp::Reverse;6263	use jrsonnet_gcmodule::Trace;6465	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]66	pub struct FieldIndex(u32);67	impl FieldIndex {68		pub fn next(self) -> Self {69			Self(self.0 + 1)70		}71	}7273	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]74	pub struct SuperDepth(u32);75	impl SuperDepth {76		pub fn deeper(self) -> Self {77			Self(self.0 + 1)78		}79	}8081	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]82	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);83	impl FieldSortKey {84		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {85			Self(Reverse(depth), index)86		}87	}88}8990use ordering::*;9192// 0 - add93//  12 - visibility94#[derive(Clone, Copy)]95pub struct ObjFieldFlags(u8);96impl ObjFieldFlags {97	fn new(add: bool, visibility: Visibility) -> Self {98		let mut v = 0;99		if add {100			v |= 1;101		}102		v |= match visibility {103			Visibility::Normal => 0b000,104			Visibility::Hidden => 0b010,105			Visibility::Unhide => 0b100,106		};107		Self(v)108	}109	pub fn add(&self) -> bool {110		self.0 & 1 != 0111	}112	pub fn visibility(&self) -> Visibility {113		match (self.0 & 0b110) >> 1 {114			0b00 => Visibility::Normal,115			0b01 => Visibility::Hidden,116			0b10 => Visibility::Unhide,117			_ => unreachable!(),118		}119	}120}121impl Debug for ObjFieldFlags {122	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {123		f.debug_struct("ObjFieldFlags")124			.field("add", &self.add())125			.field("visibility", &self.visibility())126			.finish()127	}128}129130#[allow(clippy::module_name_repetitions)]131#[derive(Debug, Trace)]132pub struct ObjMember {133	#[trace(skip)]134	flags: ObjFieldFlags,135	original_index: FieldIndex,136	pub invoke: MaybeUnbound,137	pub location: Option<ExprLocation>,138}139140pub trait ObjectAssertion: Trace {141	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;142}143144// Field => This145146#[derive(Trace)]147enum CacheValue {148	Cached(Val),149	NotFound,150	Pending,151	Errored(Error),152}153154#[allow(clippy::module_name_repetitions)]155#[derive(Trace)]156#[trace(tracking(force))]157pub struct OopObject {158	sup: Option<ObjValue>,159	// this: Option<ObjValue>,160	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,161	assertions_ran: RefCell<GcHashSet<ObjValue>>,162	this_entries: Cc<GcHashMap<IStr, ObjMember>>,163	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,164}165impl Debug for OopObject {166	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {167		f.debug_struct("OopObject")168			.field("sup", &self.sup)169			// .field("assertions", &self.assertions)170			// .field("assertions_ran", &self.assertions_ran)171			.field("this_entries", &self.this_entries)172			// .field("value_cache", &self.value_cache)173			.finish()174	}175}176177type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;178179pub trait ObjectLike: Trace + Any + Debug {180	fn extend_from(&self, sup: ObjValue) -> ObjValue;181	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed182	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {183		ObjValue::new(ThisOverride { inner: me, this })184	}185	fn this(&self) -> Option<ObjValue> {186		None187	}188	fn len(&self) -> usize;189	fn is_empty(&self) -> bool;190	// If callback returns false, iteration stops191	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;192193	fn has_field_include_hidden(&self, name: IStr) -> bool;194	fn has_field(&self, name: IStr) -> bool;195196	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;197	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198	fn field_visibility(&self, field: IStr) -> Option<Visibility>;199200	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;201}202203#[derive(Clone, Trace)]204pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);205206impl PartialEq for WeakObjValue {207	fn eq(&self, other: &Self) -> bool {208		Weak::ptr_eq(&self.0, &other.0)209	}210}211212impl Eq for WeakObjValue {}213impl Hash for WeakObjValue {214	fn hash<H: Hasher>(&self, hasher: &mut H) {215		// Safety: usize is POD216		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };217		hasher.write_usize(addr);218	}219}220221#[allow(clippy::module_name_repetitions)]222#[derive(Clone, Trace, Debug)]223pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);224225#[derive(Debug, Trace)]226struct EmptyObject;227impl ObjectLike for EmptyObject {228	fn extend_from(&self, sup: ObjValue) -> ObjValue {229		// obj + {} == obj230		sup231	}232233	fn this(&self) -> Option<ObjValue> {234		None235	}236237	fn len(&self) -> usize {238		0239	}240241	fn is_empty(&self) -> bool {242		true243	}244245	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {246		false247	}248249	fn has_field_include_hidden(&self, _name: IStr) -> bool {250		false251	}252253	fn has_field(&self, _name: IStr) -> bool {254		false255	}256257	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {258		Ok(None)259	}260	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {261		Ok(None)262	}263264	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {265		Ok(())266	}267268	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {269		None270	}271}272273#[derive(Trace, Debug)]274struct ThisOverride {275	inner: ObjValue,276	this: ObjValue,277}278impl ObjectLike for ThisOverride {279	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {280		ObjValue::new(ThisOverride {281			inner: self.inner.clone(),282			this,283		})284	}285286	fn extend_from(&self, sup: ObjValue) -> ObjValue {287		self.inner.extend_from(sup).with_this(self.this.clone())288	}289290	fn this(&self) -> Option<ObjValue> {291		Some(self.this.clone())292	}293294	fn len(&self) -> usize {295		self.inner.len()296	}297298	fn is_empty(&self) -> bool {299		self.inner.is_empty()300	}301302	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {303		self.inner.enum_fields(depth, handler)304	}305306	fn has_field_include_hidden(&self, name: IStr) -> bool {307		self.inner.has_field_include_hidden(name)308	}309310	fn has_field(&self, name: IStr) -> bool {311		self.inner.has_field(name)312	}313314	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {315		self.inner.get_for(key, this)316	}317318	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {319		self.inner.get_raw(key, this)320	}321322	fn field_visibility(&self, field: IStr) -> Option<Visibility> {323		self.inner.field_visibility(field)324	}325326	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {327		self.inner.run_assertions_raw(this)328	}329}330331impl ObjValue {332	pub fn new(v: impl ObjectLike) -> Self {333		Self(Cc::new(tb!(v)))334	}335	pub fn new_empty() -> Self {336		Self::new(EmptyObject)337	}338	pub fn builder() -> ObjValueBuilder {339		ObjValueBuilder::new()340	}341	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {342		ObjValueBuilder::with_capacity(capacity)343	}344	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {345		let mut out = ObjValueBuilder::with_capacity(1);346		out.with_super(self);347		let mut member = out.member(key);348		if value.flags.add() {349			member = member.add()350		}351		if let Some(loc) = value.location {352			member = member.with_location(loc);353		}354		let _ = member355			.with_visibility(value.flags.visibility())356			.binding(value.invoke);357		out.build()358	}359	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {360		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())361	}362363	#[must_use]364	pub fn extend_from(&self, sup: Self) -> Self {365		self.0.extend_from(sup)366	}367	#[must_use]368	pub fn with_this(&self, this: Self) -> Self {369		self.0.with_this(self.clone(), this)370	}371	pub fn len(&self) -> usize {372		self.0.len()373	}374	pub fn is_empty(&self) -> bool {375		self.0.is_empty()376	}377	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {378		self.0.enum_fields(depth, handler)379	}380381	pub fn has_field_include_hidden(&self, name: IStr) -> bool {382		self.0.has_field_include_hidden(name)383	}384	pub fn has_field(&self, name: IStr) -> bool {385		self.0.has_field(name)386	}387	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {388		if include_hidden {389			self.has_field_include_hidden(name)390		} else {391			self.has_field(name)392		}393	}394395	pub fn get(&self, key: IStr) -> Result<Option<Val>> {396		self.run_assertions()?;397		self.get_for(key, self.0.this().unwrap_or(self.clone()))398	}399400	pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {401		self.0.get_for(key, this)402	}403404	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {405		let Some(value) = self.get(key.clone())? else {406			let suggestions = suggest_object_fields(self, key.clone());407			throw!(NoSuchField(key, suggestions))408		};409		Ok(value)410	}411412	fn get_raw(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {413		self.0.get_for_uncached(key, this)414	}415416	fn field_visibility(&self, field: IStr) -> Option<Visibility> {417		self.0.field_visibility(field)418	}419420	pub fn run_assertions(&self) -> Result<()> {421		// FIXME: Should it use `self.0.this()` in case of standalone super?422		self.run_assertions_raw(self.clone())423	}424	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {425		self.0.run_assertions_raw(this)426	}427428	pub fn iter(429		&self,430		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,431	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {432		let fields = self.fields(433			#[cfg(feature = "exp-preserve-order")]434			preserve_order,435		);436		fields.into_iter().map(|field| {437			(438				field.clone(),439				self.get(field)440					.map(|opt| opt.expect("iterating over keys, field exists")),441			)442		})443	}444	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {445		#[derive(Trace)]446		struct ThunkGet {447			obj: ObjValue,448			key: IStr,449		}450		impl ThunkValue for ThunkGet {451			type Output = Val;452453			fn get(self: Box<Self>) -> Result<Self::Output> {454				Ok(self.obj.get(self.key)?.expect("field exists"))455			}456		}457458		if !self.has_field_ex(key.clone(), true) {459			return None;460		}461		Some(Thunk::new(ThunkGet {462			obj: self.clone(),463			key,464		}))465	}466	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {467		#[derive(Trace)]468		struct ThunkGet {469			obj: ObjValue,470			key: IStr,471		}472		impl ThunkValue for ThunkGet {473			type Output = Val;474475			fn get(self: Box<Self>) -> Result<Self::Output> {476				Ok(self.obj.get_or_bail(self.key)?)477			}478		}479480		Thunk::new(ThunkGet {481			obj: self.clone(),482			key,483		})484	}485	pub fn ptr_eq(a: &Self, b: &Self) -> bool {486		Cc::ptr_eq(&a.0, &b.0)487	}488	pub fn downgrade(self) -> WeakObjValue {489		WeakObjValue(self.0.downgrade())490	}491	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {492		let mut out = FxHashMap::default();493		self.enum_fields(494			SuperDepth::default(),495			&mut |depth, index, name, visibility| {496				let new_sort_key = FieldSortKey::new(depth, index);497				let entry = out.entry(name.clone());498				let (visible, _) = entry.or_insert((true, new_sort_key));499				match visibility {500					Visibility::Normal => {}501					Visibility::Hidden => {502						*visible = false;503					}504					Visibility::Unhide => {505						*visible = true;506					}507				};508				false509			},510		);511		out512	}513	pub fn fields_ex(514		&self,515		include_hidden: bool,516		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,517	) -> Vec<IStr> {518		#[cfg(feature = "exp-preserve-order")]519		if preserve_order {520			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self521				.fields_visibility()522				.into_iter()523				.filter(|(_, (visible, _))| include_hidden || *visible)524				.enumerate()525				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))526				.unzip();527			keys.sort_unstable_by_key(|v| v.0);528			// Reorder in-place by resulting indexes529			for i in 0..fields.len() {530				let x = fields[i].clone();531				let mut j = i;532				loop {533					let k = keys[j].1;534					keys[j].1 = j;535					if k == i {536						break;537					}538					fields[j] = fields[k].clone();539					j = k;540				}541				fields[j] = x;542			}543			return fields;544		}545546		let mut fields: Vec<_> = self547			.fields_visibility()548			.into_iter()549			.filter(|(_, (visible, _))| include_hidden || *visible)550			.map(|(k, _)| k)551			.collect();552		fields.sort_unstable();553		fields554	}555	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {556		self.fields_ex(557			false,558			#[cfg(feature = "exp-preserve-order")]559			preserve_order,560		)561	}562	pub fn values_ex(563		&self,564		include_hidden: bool,565		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,566	) -> ArrValue {567		ArrValue::new(PickObjectValues::new(568			self.clone(),569			self.fields_ex(570				include_hidden,571				#[cfg(feature = "exp-preserve-order")]572				preserve_order,573			),574		))575	}576	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {577		self.values_ex(578			false,579			#[cfg(feature = "exp-preserve-order")]580			preserve_order,581		)582	}583	pub fn key_values_ex(584		&self,585		include_hidden: bool,586		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,587	) -> ArrValue {588		ArrValue::new(PickObjectKeyValues::new(589			self.clone(),590			self.fields_ex(591				include_hidden,592				#[cfg(feature = "exp-preserve-order")]593				preserve_order,594			),595		))596	}597	pub fn key_values(598		&self,599		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,600	) -> ArrValue {601		self.key_values_ex(602			false,603			#[cfg(feature = "exp-preserve-order")]604			preserve_order,605		)606	}607}608609impl OopObject {610	pub fn new(611		sup: Option<ObjValue>,612		this_entries: Cc<GcHashMap<IStr, ObjMember>>,613		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,614	) -> Self {615		Self {616			sup,617			// this: None,618			assertions,619			assertions_ran: RefCell::new(GcHashSet::new()),620			this_entries,621			value_cache: RefCell::new(GcHashMap::new()),622		}623	}624625	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {626		v.invoke.evaluate(self.sup.clone(), Some(real_this))627	}628629	// FIXME: Duplication between ObjValue and OopObject630	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {631		let mut out = FxHashMap::default();632		self.enum_fields(633			SuperDepth::default(),634			&mut |depth, index, name, visibility| {635				let new_sort_key = FieldSortKey::new(depth, index);636				let entry = out.entry(name.clone());637				let (visible, _) = entry.or_insert((true, new_sort_key));638				match visibility {639					Visibility::Normal => {}640					Visibility::Hidden => {641						*visible = false;642					}643					Visibility::Unhide => {644						*visible = true;645					}646				};647				false648			},649		);650		out651	}652}653654impl ObjectLike for OopObject {655	fn extend_from(&self, sup: ObjValue) -> ObjValue {656		ObjValue::new(match &self.sup {657			None => Self::new(658				Some(sup),659				self.this_entries.clone(),660				self.assertions.clone(),661			),662			Some(v) => Self::new(663				Some(v.extend_from(sup)),664				self.this_entries.clone(),665				self.assertions.clone(),666			),667		})668	}669670	fn len(&self) -> usize {671		self.fields_visibility()672			.into_iter()673			.filter(|(_, (visible, _))| *visible)674			.count()675	}676677	fn is_empty(&self) -> bool {678		if !self.this_entries.is_empty() {679			return false;680		}681		self.sup.as_ref().map_or(true, ObjValue::is_empty)682	}683684	/// Run callback for every field found in object685	///686	/// Returns true if ended prematurely687	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {688		if let Some(s) = &self.sup {689			if s.enum_fields(depth.deeper(), handler) {690				return true;691			}692		}693		for (name, member) in self.this_entries.iter() {694			if handler(695				depth,696				member.original_index,697				name.clone(),698				member.flags.visibility(),699			) {700				return true;701			}702		}703		false704	}705706	fn has_field_include_hidden(&self, name: IStr) -> bool {707		if self.this_entries.contains_key(&name) {708			true709		} else if let Some(super_obj) = &self.sup {710			super_obj.has_field_include_hidden(name)711		} else {712			false713		}714	}715	fn has_field(&self, name: IStr) -> bool {716		self.field_visibility(name)717			.map_or(false, |v| v.is_visible())718	}719720	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {721		let cache_key = (key.clone(), Some(this.clone().downgrade()));722		if let Some(v) = self.value_cache.borrow().get(&cache_key) {723			return Ok(match v {724				CacheValue::Cached(v) => Some(v.clone()),725				CacheValue::NotFound => None,726				CacheValue::Pending => throw!(InfiniteRecursionDetected),727				CacheValue::Errored(e) => return Err(e.clone()),728			});729		}730		self.value_cache731			.borrow_mut()732			.insert(cache_key.clone(), CacheValue::Pending);733		let value = self.get_for_uncached(key, this).map_err(|e| {734			self.value_cache735				.borrow_mut()736				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));737			e738		})?;739		self.value_cache.borrow_mut().insert(740			cache_key,741			value742				.as_ref()743				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),744		);745		Ok(value)746	}747	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {748		match (self.this_entries.get(&key), &self.sup) {749			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),750			(Some(k), Some(super_obj)) => {751				let our = self.evaluate_this(k, real_this.clone())?;752				if k.flags.add() {753					super_obj754						.get_raw(key, real_this)?755						.map_or(Ok(Some(our.clone())), |v| {756							Ok(Some(evaluate_add_op(&v, &our)?))757						})758				} else {759					Ok(Some(our))760				}761			}762			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),763			(None, None) => Ok(None),764		}765	}766	fn field_visibility(&self, name: IStr) -> Option<Visibility> {767		if let Some(m) = self.this_entries.get(&name) {768			Some(match &m.flags.visibility() {769				Visibility::Normal => self770					.sup771					.as_ref()772					.and_then(|super_obj| super_obj.field_visibility(name))773					.unwrap_or(Visibility::Normal),774				v => *v,775			})776		} else if let Some(super_obj) = &self.sup {777			super_obj.field_visibility(name)778		} else {779			None780		}781	}782783	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {784		if self.assertions.is_empty() {785			if let Some(super_obj) = &self.sup {786				super_obj.run_assertions_raw(real_this)?;787			}788			return Ok(());789		}790		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {791			for assertion in self.assertions.iter() {792				if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {793					self.assertions_ran.borrow_mut().remove(&real_this);794					return Err(e);795				}796			}797			if let Some(super_obj) = &self.sup {798				super_obj.run_assertions_raw(real_this)?;799			}800		}801		Ok(())802	}803}804805impl PartialEq for ObjValue {806	fn eq(&self, other: &Self) -> bool {807		Cc::ptr_eq(&self.0, &other.0)808	}809}810811impl Eq for ObjValue {}812impl Hash for ObjValue {813	fn hash<H: Hasher>(&self, hasher: &mut H) {814		hasher.write_usize(addr_of!(*self.0) as usize);815	}816}817818#[allow(clippy::module_name_repetitions)]819pub struct ObjValueBuilder {820	sup: Option<ObjValue>,821	map: GcHashMap<IStr, ObjMember>,822	assertions: Vec<TraceBox<dyn ObjectAssertion>>,823	next_field_index: FieldIndex,824}825impl ObjValueBuilder {826	pub fn new() -> Self {827		Self::with_capacity(0)828	}829	pub fn with_capacity(capacity: usize) -> Self {830		Self {831			sup: None,832			map: GcHashMap::with_capacity(capacity),833			assertions: Vec::new(),834			next_field_index: FieldIndex::default(),835		}836	}837	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {838		self.assertions.reserve_exact(capacity);839		self840	}841	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {842		self.sup = Some(super_obj);843		self844	}845846	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {847		self.assertions.push(tb!(assertion));848		self849	}850	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {851		let field_index = self.next_field_index;852		self.next_field_index = self.next_field_index.next();853		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)854	}855856	pub fn build(self) -> ObjValue {857		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {858			return ObjValue::new_empty();859		}860		ObjValue::new(OopObject::new(861			self.sup,862			Cc::new(self.map),863			Cc::new(self.assertions),864		))865	}866}867impl Default for ObjValueBuilder {868	fn default() -> Self {869		Self::with_capacity(0)870	}871}872873#[allow(clippy::module_name_repetitions)]874#[must_use = "value not added unless binding() was called"]875pub struct ObjMemberBuilder<Kind> {876	kind: Kind,877	name: IStr,878	add: bool,879	visibility: Visibility,880	original_index: FieldIndex,881	location: Option<ExprLocation>,882}883884#[allow(clippy::missing_const_for_fn)]885impl<Kind> ObjMemberBuilder<Kind> {886	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {887		Self {888			kind,889			name,890			original_index,891			add: false,892			visibility: Visibility::Normal,893			location: None,894		}895	}896897	pub const fn with_add(mut self, add: bool) -> Self {898		self.add = add;899		self900	}901	pub fn add(self) -> Self {902		self.with_add(true)903	}904	pub fn with_visibility(mut self, visibility: Visibility) -> Self {905		self.visibility = visibility;906		self907	}908	pub fn hide(self) -> Self {909		self.with_visibility(Visibility::Hidden)910	}911	pub fn with_location(mut self, location: ExprLocation) -> Self {912		self.location = Some(location);913		self914	}915	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {916		(917			self.kind,918			self.name,919			ObjMember {920				flags: ObjFieldFlags::new(self.add, self.visibility),921				original_index: self.original_index,922				invoke: binding,923				location: self.location,924			},925		)926	}927}928929pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);930impl ObjMemberBuilder<ValueBuilder<'_>> {931	/// Inserts value, replacing if it is already defined932	pub fn value_unchecked(self, value: Val) {933		let (receiver, name, member) =934			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));935		let entry = receiver.0.map.entry(name);936		entry.insert(member);937	}938939	pub fn value(self, value: Val) -> Result<()> {940		self.thunk(Thunk::evaluated(value))941	}942	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {943		self.binding(MaybeUnbound::Bound(value))944	}945	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {946		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))947	}948	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {949		let (receiver, name, member) = self.build_member(binding);950		let location = member.location.clone();951		let old = receiver.0.map.insert(name.clone(), member);952		if old.is_some() {953			State::push(954				CallLocation(location.as_ref()),955				|| format!("field <{}> initializtion", name.clone()),956				|| throw!(DuplicateFieldName(name.clone())),957			)?;958		}959		Ok(())960	}961}962963pub struct ExtendBuilder<'v>(&'v mut ObjValue);964impl ObjMemberBuilder<ExtendBuilder<'_>> {965	pub fn value(self, value: Val) {966		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));967	}968	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {969		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));970	}971	pub fn binding(self, binding: MaybeUnbound) {972		let (receiver, name, member) = self.build_member(binding);973		let new = receiver.0.clone();974		*receiver.0 = new.extend_with_raw_member(name, member);975	}976}
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -7,8 +7,8 @@
 use thiserror::Error;
 
 use crate::{
+	bail,
 	error::{format_found, suggest_object_fields, ErrorKind::*},
-	throw,
 	typed::Typed,
 	Error, ObjValue, Result, Val,
 };
@@ -611,12 +611,12 @@
 			Val::Str(s) => {
 				let s = s.into_flat();
 				if s.chars().count() != 1 {
-					throw!("%c expected 1 char string, got {}", s.chars().count(),);
+					bail!("%c expected 1 char string, got {}", s.chars().count());
 				}
 				tmp_out.push_str(&s);
 			}
 			_ => {
-				throw!(TypeMismatch(
+				bail!(TypeMismatch(
 					"%c requires number/string",
 					vec![ValType::Num, ValType::Str],
 					value.value_type(),
@@ -657,7 +657,7 @@
 				let width = match c.width {
 					Width::Star => {
 						if values.is_empty() {
-							throw!(NotEnoughValues);
+							bail!(NotEnoughValues);
 						}
 						let value = &values[0];
 						values = &values[1..];
@@ -668,7 +668,7 @@
 				let precision = match c.precision {
 					Some(Width::Star) => {
 						if values.is_empty() {
-							throw!(NotEnoughValues);
+							bail!(NotEnoughValues);
 						}
 						let value = &values[0];
 						values = &values[1..];
@@ -683,7 +683,7 @@
 					&Val::Null
 				} else {
 					if values.is_empty() {
-						throw!(NotEnoughValues);
+						bail!(NotEnoughValues);
 					}
 					let value = &values[0];
 					values = &values[1..];
@@ -696,7 +696,7 @@
 	}
 
 	if !values.is_empty() {
-		throw!(
+		bail!(
 			"too many values to format, expected {value_count}, got {}",
 			value_count + values.len()
 		)
@@ -717,7 +717,7 @@
 				let current = &field[name_offset..end_offset];
 				let full = &field[..name_offset];
 				let found = Box::new(suggest_object_fields(&obj, current.into()));
-				throw!(SubfieldNotFound {
+				bail!(SubfieldNotFound {
 					current: current.into(),
 					full: full.into(),
 					found,
@@ -726,7 +726,7 @@
 		} else {
 			// No underflow may happen, initially we always start with an object
 			let subfield = &field[..name_offset - 1];
-			throw!(SubfieldDidntYieldAnObject(
+			bail!(SubfieldDidntYieldAnObject(
 				subfield.into(),
 				current.value_type()
 			));
@@ -750,13 +750,13 @@
 				let f: IStr = c.mkey.into();
 				let width = match c.width {
 					Width::Star => {
-						throw!(CannotUseStarWidthWithObject);
+						bail!(CannotUseStarWidthWithObject);
 					}
 					Width::Fixed(n) => n,
 				};
 				let precision = match c.precision {
 					Some(Width::Star) => {
-						throw!(CannotUseStarWidthWithObject);
+						bail!(CannotUseStarWidthWithObject);
 					}
 					Some(Width::Fixed(n)) => Some(n),
 					None => None,
@@ -766,7 +766,7 @@
 					Val::Null
 				} else {
 					if f.is_empty() {
-						throw!(MappingKeysRequired);
+						bail!(MappingKeysRequired);
 					}
 					if let Some(v) = values.get(f.clone())? {
 						v
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,7 +3,7 @@
 
 use format::{format_arr, format_obj};
 
-use crate::{error::Result, function::CallLocation, State, Val};
+use crate::{function::CallLocation, Result, State, Val};
 
 pub mod format;
 
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -7,12 +7,11 @@
 
 use crate::{
 	arr::{ArrValue, BytesArray},
-	error::Result,
+	bail,
 	function::{native::NativeDesc, FuncDesc, FuncVal},
-	throw,
 	typed::CheckType,
-	val::{IndexableVal, StrValue, ThunkMapper},
-	ObjValue, ObjValueBuilder, Thunk, Val,
+	val::{IndexableVal, ThunkMapper},
+	ObjValue, ObjValueBuilder, Result, Thunk, Val,
 };
 
 #[derive(Trace)]
@@ -134,7 +133,7 @@
 					Val::Num(n) => {
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
-							throw!(
+							bail!(
 								"cannot convert number with fractional part to {}",
 								stringify!($ty)
 							)
@@ -189,7 +188,7 @@
 					Val::Num(n) => {
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
-							throw!(
+							bail!(
 								"cannot convert number with fractional part to {}",
 								stringify!($ty)
 							)
@@ -253,7 +252,7 @@
 
 	fn into_untyped(value: Self) -> Result<Val> {
 		if value > MAX_SAFE_INTEGER as Self {
-			throw!("number is too large")
+			bail!("number is too large")
 		}
 		Ok(Val::Num(value as f64))
 	}
@@ -264,7 +263,7 @@
 			Val::Num(n) => {
 				#[allow(clippy::float_cmp)]
 				if n.trunc() != n {
-					throw!("cannot convert number with fractional part to usize")
+					bail!("cannot convert number with fractional part to usize")
 				}
 				Ok(n as Self)
 			}
@@ -354,7 +353,7 @@
 		let mut out = ObjValueBuilder::with_capacity(typed.len());
 		for (k, v) in typed {
 			let Some(key) = K::into_untyped(k)?.as_str() else {
-				throw!("map key should serialize to string");
+				bail!("map key should serialize to string");
 			};
 			let value = V::into_untyped(v)?;
 			out.member(key).value_unchecked(value);
@@ -567,7 +566,7 @@
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
 			Val::Func(FuncVal::Normal(desc)) => Ok(desc),
-			Val::Func(_) => throw!("expected normal function, not builtin"),
+			Val::Func(_) => bail!("expected normal function, not builtin"),
 			_ => unreachable!(),
 		}
 	}
@@ -649,7 +648,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
 
 	fn into_untyped(_typed: Self) -> Result<Val> {
-		throw!("can only convert functions from jsonnet to native")
+		bail!("can only convert functions from jsonnet to native")
 	}
 
 	fn from_untyped(untyped: Val) -> Result<Self> {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -11,11 +11,12 @@
 
 pub use crate::arr::{ArrValue, ArrayLike};
 use crate::{
+	bail,
 	error::{Error, ErrorKind::*},
 	function::FuncVal,
 	gc::{GcHashMap, TraceBox},
 	manifest::{ManifestFormat, ToStringFormat},
-	tb, throw,
+	tb,
 	typed::BoundedUsize,
 	ObjValue, Result, Unbound, WeakObjValue,
 };
@@ -456,7 +457,7 @@
 		if num.is_finite() {
 			Ok(Self::Num(num))
 		} else {
-			throw!("overflow")
+			bail!("overflow")
 		}
 	}
 
@@ -495,7 +496,7 @@
 		Ok(match self {
 			Val::Str(s) => IndexableVal::Str(s.into_flat()),
 			Val::Arr(arr) => IndexableVal::Arr(arr),
-			_ => throw!(ValueIsNotIndexable(self.value_type())),
+			_ => bail!(ValueIsNotIndexable(self.value_type())),
 		})
 	}
 }
@@ -514,13 +515,13 @@
 		#[cfg(feature = "exp-bigint")]
 		(Val::BigInt(a), Val::BigInt(b)) => a == b,
 		(Val::Arr(_), Val::Arr(_)) => {
-			throw!("primitiveEquals operates on primitive types, got array")
+			bail!("primitiveEquals operates on primitive types, got array")
 		}
 		(Val::Obj(_), Val::Obj(_)) => {
-			throw!("primitiveEquals operates on primitive types, got object")
+			bail!("primitiveEquals operates on primitive types, got object")
 		}
 		(a, b) if is_function_like(a) && is_function_like(b) => {
-			throw!("cannot test equality of functions")
+			bail!("cannot test equality of functions")
 		}
 		(_, _) => false,
 	})
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -356,7 +356,7 @@
 			use ::jrsonnet_evaluator::{
 				State, Val,
 				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName}, CallLocation, ArgsLike, parse::parse_builtin_call},
-				error::Result, Context, typed::Typed,
+				Result, Context, typed::Typed,
 				parser::ExprLocation,
 			};
 			const PARAMS: &'static [BuiltinParam] = &[
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,19 +1,19 @@
 #![allow(non_snake_case)]
 
 use jrsonnet_evaluator::{
-	error::{ErrorKind::RuntimeError, Result},
+	bail,
 	function::{builtin, FuncVal},
-	throw,
+	runtime_error,
 	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
-	val::{equals, ArrValue, IndexableVal, StrValue},
-	Either, IStr, Thunk, Val,
+	val::{equals, ArrValue, IndexableVal},
+	Either, IStr, Result, Thunk, Val,
 };
 
 pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
 	if let Some(on_empty) = on_empty {
 		on_empty.evaluate()
 	} else {
-		throw!("expected non-empty array")
+		bail!("expected non-empty array")
 	}
 }
 
@@ -39,7 +39,7 @@
 		Either2::A(s) => Val::Str(StrValue::Flat(s.repeat(count).into())),
 		Either2::B(arr) => Val::Arr(
 			ArrValue::repeated(arr, count)
-				.ok_or_else(|| RuntimeError("repeated length overflow".into()))?,
+				.ok_or_else(|| runtime_error!("repeated length overflow"))?,
 		),
 	})
 }
@@ -73,7 +73,7 @@
 				match func(Either2::A(c.to_string()))? {
 					Val::Str(o) => write!(out, "{o}").unwrap(),
 					Val::Null => continue,
-					_ => throw!("in std.join all items should be strings"),
+					_ => bail!("in std.join all items should be strings"),
 				};
 			}
 			Ok(IndexableVal::Str(out.into()))
@@ -89,7 +89,7 @@
 						}
 					}
 					Val::Null => continue,
-					_ => throw!("in std.join all items should be arrays"),
+					_ => bail!("in std.join all items should be arrays"),
 				};
 			}
 			Ok(IndexableVal::Arr(out.into()))
@@ -154,7 +154,7 @@
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
-					throw!("in std.join all items should be arrays");
+					bail!("in std.join all items should be arrays");
 				}
 			}
 
@@ -175,7 +175,7 @@
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
-					throw!("in std.join all items should be strings");
+					bail!("in std.join all items should be strings");
 				}
 			}
 
modifiedcrates/jrsonnet-stdlib/src/compat.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/compat.rs
+++ b/crates/jrsonnet-stdlib/src/compat.rs
@@ -1,6 +1,6 @@
 use std::cmp::Ordering;
 
-use jrsonnet_evaluator::{error::Result, function::builtin, operator::evaluate_compare_op, Val};
+use jrsonnet_evaluator::{function::builtin, operator::evaluate_compare_op, Result, Val};
 
 #[builtin]
 #[allow(non_snake_case)]
modifiedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -1,9 +1,9 @@
 use base64::{engine::general_purpose::STANDARD, Engine};
 use jrsonnet_evaluator::{
-	error::{ErrorKind::RuntimeError, Result},
 	function::builtin,
+	runtime_error,
 	typed::{Either, Either2},
-	IBytes, IStr,
+	IBytes, IStr, Result,
 };
 
 #[builtin]
@@ -13,9 +13,7 @@
 
 #[builtin]
 pub fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {
-	Ok(arr
-		.cast_str()
-		.ok_or_else(|| RuntimeError("bad utf8".into()))?)
+	arr.cast_str().ok_or_else(|| runtime_error!("bad utf8"))
 }
 
 #[builtin]
@@ -31,7 +29,7 @@
 pub fn builtin_base64_decode_bytes(str: IStr) -> Result<IBytes> {
 	Ok(STANDARD
 		.decode(str.as_bytes())
-		.map_err(|e| RuntimeError(format!("invalid base64: {e}").into()))?
+		.map_err(|e| runtime_error!("invalid base64: {e}"))?
 		.as_slice()
 		.into())
 }
@@ -40,6 +38,6 @@
 pub fn builtin_base64_decode(str: IStr) -> Result<String> {
 	let bytes = STANDARD
 		.decode(str.as_bytes())
-		.map_err(|e| RuntimeError(format!("invalid base64: {e}").into()))?;
-	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
+		.map_err(|e| runtime_error!("invalid base64: {e}"))?;
+	Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
 }
modifiedcrates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/mod.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -2,10 +2,9 @@
 mod yaml;
 
 use jrsonnet_evaluator::{
-	error::Result,
 	function::builtin,
 	manifest::{escape_string_json, JsonFormat},
-	IStr, ObjValue, Val,
+	IStr, ObjValue, Result, Val,
 };
 pub use toml::TomlFormat;
 pub use yaml::YamlFormat;
modifiedcrates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,8 +1,8 @@
 use std::borrow::Cow;
 
 use jrsonnet_evaluator::{
+	bail,
 	manifest::{escape_string_json_buf, ManifestFormat},
-	throw,
 	val::ArrValue,
 	IStr, ObjValue, Result, Val,
 };
@@ -157,10 +157,10 @@
 			buf.push_str(" }");
 		}
 		Val::Null => {
-			throw!("tried to manifest null")
+			bail!("tried to manifest null")
 		}
 		Val::Func(_) => {
-			throw!("tried to manifest function")
+			bail!("tried to manifest function")
 		}
 	}
 	Ok(())
@@ -290,7 +290,7 @@
 			Val::Obj(obj) => {
 				manifest_table_internal(&obj, &mut Vec::new(), buf, &mut String::new(), self)
 			}
-			_ => throw!("toml body should be object"),
+			_ => bail!("toml body should be object"),
 		}
 	}
 }
modifiedcrates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -1,8 +1,9 @@
 use std::{borrow::Cow, fmt::Write};
 
 use jrsonnet_evaluator::{
+	bail,
 	manifest::{escape_string_json_buf, ManifestFormat},
-	throw, Result, Val,
+	Result, Val,
 };
 
 pub struct YamlFormat<'s> {
@@ -219,7 +220,7 @@
 				}
 			}
 		}
-		Val::Func(_) => throw!("tried to manifest function"),
+		Val::Func(_) => bail!("tried to manifest function"),
 	}
 	Ok(())
 }
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,10 +1,10 @@
 use std::{cell::RefCell, rc::Rc};
 
 use jrsonnet_evaluator::{
+	bail,
 	error::{ErrorKind::*, Result},
 	function::{builtin, ArgLike, CallLocation, FuncVal},
 	manifest::JsonFormat,
-	throw,
 	typed::{Either2, Either4},
 	val::{equals, ArrValue},
 	Context, Either, IStr, ObjValue, Thunk, Val,
@@ -103,7 +103,7 @@
 				true
 			}
 		}
-		_ => throw!("both arguments should be of the same type"),
+		_ => bail!("both arguments should be of the same type"),
 	})
 }
 
@@ -129,6 +129,6 @@
 				true
 			}
 		}
-		_ => throw!("both arguments should be of the same type"),
+		_ => bail!("both arguments should be of the same type"),
 	})
 }
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,13 +2,12 @@
 //! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
 
 use jrsonnet_evaluator::{
-	error::Result,
 	function::builtin,
 	operator::evaluate_mod_op,
 	stdlib::std_format,
 	typed::{Either, Either2},
-	val::{equals, primitive_equals, StrValue},
-	IStr, Val,
+	val::{equals, primitive_equals},
+	IStr, Result, Val,
 };
 
 #[builtin]
modifiedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -1,14 +1,10 @@
-use jrsonnet_evaluator::{
-	error::{ErrorKind::RuntimeError, Result},
-	function::builtin,
-	IStr, Val,
-};
+use jrsonnet_evaluator::{function::builtin, runtime_error, IStr, Result, Val};
 use serde::Deserialize;
 
 #[builtin]
 pub fn builtin_parse_json(str: IStr) -> Result<Val> {
-	let value: Val = serde_json::from_str(&str)
-		.map_err(|e| RuntimeError(format!("failed to parse json: {e}").into()))?;
+	let value: Val =
+		serde_json::from_str(&str).map_err(|e| runtime_error!("failed to parse json: {e}"))?;
 	Ok(value)
 }
 
@@ -21,8 +17,8 @@
 	);
 	let mut out = vec![];
 	for item in value {
-		let val = Val::deserialize(item)
-			.map_err(|e| RuntimeError(format!("failed to parse yaml: {e}").into()))?;
+		let val =
+			Val::deserialize(item).map_err(|e| runtime_error!("failed to parse yaml: {e}"))?;
 		out.push(val);
 	}
 	Ok(if out.is_empty() {
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -3,12 +3,11 @@
 use std::cmp::Ordering;
 
 use jrsonnet_evaluator::{
-	error::Result,
+	bail,
 	function::{builtin, FuncVal},
 	operator::evaluate_compare_op,
-	throw,
 	val::{equals, ArrValue},
-	Thunk, Val,
+	Result, Thunk, Val,
 };
 use jrsonnet_parser::BinaryOpType;
 
@@ -44,7 +43,7 @@
 			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
 			(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
 			(Val::Str(_) | Val::Num(_), _) => {
-				throw!("sort elements should have the same types")
+				bail!("sort elements should have the same types")
 			}
 			_ => {}
 		}
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
+	bail,
 	error::{ErrorKind::*, Result},
 	function::builtin,
-	throw,
 	typed::{Either2, M1},
 	val::{ArrValue, StrValue},
 	Either, IStr, Val,
@@ -91,13 +91,13 @@
 pub fn builtin_parse_int(str: IStr) -> Result<f64> {
 	if let Some(raw) = str.strip_prefix('-') {
 		if raw.is_empty() {
-			throw!("integer only consists of a minus")
+			bail!("integer only consists of a minus")
 		}
 
 		parse_nat::<10>(raw).map(|value| -value)
 	} else {
 		if str.is_empty() {
-			throw!("empty integer")
+			bail!("empty integer")
 		}
 
 		parse_nat::<10>(str.as_str())
@@ -107,7 +107,7 @@
 #[builtin]
 pub fn builtin_parse_octal(str: IStr) -> Result<f64> {
 	if str.is_empty() {
-		throw!("empty octal integer");
+		bail!("empty octal integer");
 	}
 
 	parse_nat::<8>(str.as_str())
@@ -116,7 +116,7 @@
 #[builtin]
 pub fn builtin_parse_hex(str: IStr) -> Result<f64> {
 	if str.is_empty() {
-		throw!("empty hexadecimal integer");
+		bail!("empty hexadecimal integer");
 	}
 
 	parse_nat::<16>(str.as_str())
@@ -156,7 +156,7 @@
 		if digit < BASE {
 			Ok(base * aggregate + digit as f64)
 		} else {
-			throw!("{raw:?} is not a base {BASE} integer",);
+			bail!("{raw:?} is not a base {BASE} integer");
 		}
 	})
 }
@@ -164,13 +164,14 @@
 #[cfg(feature = "exp-bigint")]
 #[builtin]
 pub fn builtin_bigint(v: Either![f64, IStr]) -> Result<Val> {
+	use jrsonnet_evaluator::runtime_error;
 	use Either2::*;
 	Ok(match v {
 		A(a) => Val::BigInt(Box::new((a as i64).into())),
 		B(b) => Val::BigInt(Box::new(
 			b.as_str()
 				.parse()
-				.map_err(|e| RuntimeError(format!("bad bigint: {e}").into()))?,
+				.map_err(|e| runtime_error!("bad bigint: {e}"))?,
 		)),
 	})
 }
modifiedtests/tests/as_native.rsdiffbeforeafterboth
--- a/tests/tests/as_native.rs
+++ b/tests/tests/as_native.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_evaluator::{Result, State};
 use jrsonnet_stdlib::StateExt;
 
 mod common;
modifiedtests/tests/builtin.rsdiffbeforeafterboth
--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -1,10 +1,9 @@
 mod common;
 
 use jrsonnet_evaluator::{
-	error::Result,
 	function::{builtin, builtin::Builtin, CallLocation, FuncVal},
 	typed::Typed,
-	ContextBuilder, State, Thunk, Val,
+	ContextBuilder, Result, State, Thunk, Val,
 };
 use jrsonnet_stdlib::StateExt;
 
modifiedtests/tests/common.rsdiffbeforeafterboth
--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
-	error::Result,
+	bail,
 	function::{builtin, FuncVal},
-	throw, ObjValueBuilder, State, Thunk, Val,
+	ObjValueBuilder, Result, State, Thunk, Val,
 };
 
 #[macro_export]
@@ -10,7 +10,7 @@
 		let a = &$a;
 		let b = &$b;
 		if a != b {
-			::jrsonnet_evaluator::throw!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+			::jrsonnet_evaluator::bail!("assertion failed: a != b\na={a:#?}\nb={b:#?}")
 		}
 	}};
 }
@@ -19,7 +19,7 @@
 macro_rules! ensure {
 	($v:expr $(,)?) => {
 		if !$v {
-			::jrsonnet_evaluator::throw!("assertion failed: {}", stringify!($v))
+			::jrsonnet_evaluator::bail!("assertion failed: {}", stringify!($v))
 		}
 	};
 }
@@ -29,7 +29,7 @@
 	($a:expr, $b:expr) => {{
 		if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {
 			use ::jrsonnet_evaluator::manifest::JsonFormat;
-			::jrsonnet_evaluator::throw!(
+			::jrsonnet_evaluator::bail!(
 				"assertion failed: a != b\na={:#?}\nb={:#?}",
 				$a.manifest(JsonFormat::default())?,
 				$b.manifest(JsonFormat::default())?,
@@ -42,7 +42,7 @@
 fn assert_throw(lazy: Thunk<Val>, message: String) -> Result<bool> {
 	match lazy.evaluate() {
 		Ok(_) => {
-			throw!("expected argument to throw on evaluation, but it returned instead")
+			bail!("expected argument to throw on evaluation, but it returned instead")
 		}
 		Err(e) => {
 			let error = format!("{}", e.error());
modifiedtests/tests/sanity.rsdiffbeforeafterboth
--- a/tests/tests/sanity.rs
+++ b/tests/tests/sanity.rs
@@ -1,8 +1,7 @@
 use jrsonnet_evaluator::{
-	error::Result,
-	throw,
+	bail,
 	trace::{CompactFormat, TraceFormat},
-	State, Val,
+	Result, State, Val,
 };
 use jrsonnet_stdlib::StateExt;
 
@@ -29,14 +28,14 @@
 
 	{
 		let Err(e) = s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") else {
-			throw!("assertion should fail");
+			bail!("assertion should fail");
 		};
 		let e = trace_format.format(&e).unwrap();
 		ensure!(e.starts_with("assert failed: fail\n"));
 	}
 	{
 		let Err(e) = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") else {
-			throw!("assertion should fail")
+			bail!("assertion should fail")
 		};
 		let e = trace_format.format(&e).unwrap();
 		ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
modifiedtests/tests/typed_obj.rsdiffbeforeafterboth
--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -2,7 +2,7 @@
 
 use std::fmt::Debug;
 
-use jrsonnet_evaluator::{error::Result, typed::Typed, State};
+use jrsonnet_evaluator::{typed::Typed, Result, State};
 use jrsonnet_stdlib::StateExt;
 
 #[derive(Clone, Typed, PartialEq, Debug)]