git.delta.rocks / jrsonnet / refs/commits / 5e6d5ee048e2

difftreelog

refactor unify throw & throw_runtime

Yaroslav Bolyukin2022-10-17parent: #b8bef13.patch.diff
in: master

13 files changed

modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -266,14 +266,13 @@
 
 #[macro_export]
 macro_rules! throw {
-	($e: expr) => {
-		return Err($e.into())
+	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {
+		return Err($w$(::$i)*$(($($tt)*))?.into())
 	};
-}
-
-#[macro_export]
-macro_rules! throw_runtime {
-	($($tt:tt)*) => {
-		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())
+	($l:literal) => {
+		return Err($crate::error::Error::RuntimeError($l.into()).into())
+	};
+	($l:literal, $($tt:tt)*) => {
+		return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())
 	};
 }
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -32,7 +32,7 @@
 		Destruct::Array { start, rest, end } => {
 			use jrsonnet_parser::DestructRest;
 
-			use crate::{throw_runtime, val::ArrValue};
+			use crate::{throw, val::ArrValue};
 
 			#[derive(Trace)]
 			struct DataThunk {
@@ -47,14 +47,14 @@
 					let v = self.parent.evaluate(s)?;
 					let arr = match v {
 						Val::Arr(a) => a,
-						_ => throw_runtime!("expected array"),
+						_ => throw!("expected array"),
 					};
 					if !self.has_rest {
 						if arr.len() != self.min_len {
-							throw_runtime!("expected {} elements, got {}", self.min_len, arr.len())
+							throw!("expected {} elements, got {}", self.min_len, arr.len())
 						}
 					} else if arr.len() < self.min_len {
-						throw_runtime!(
+						throw!(
 							"expected at least {} elements, but array was only {}",
 							self.min_len,
 							arr.len()
@@ -163,7 +163,7 @@
 		}
 		#[cfg(feature = "exp-destruct")]
 		Destruct::Object { fields, rest } => {
-			use crate::{obj::ObjValue, throw_runtime};
+			use crate::{obj::ObjValue, throw};
 
 			#[derive(Trace)]
 			struct DataThunk {
@@ -178,17 +178,17 @@
 					let v = self.parent.evaluate(s)?;
 					let obj = match v {
 						Val::Obj(o) => o,
-						_ => throw_runtime!("expected object"),
+						_ => throw!("expected object"),
 					};
 					for field in &self.field_names {
 						if !obj.has_field_ex(field.clone(), true) {
-							throw_runtime!("missing field: {}", field);
+							throw!("missing field: {}", field);
 						}
 					}
 					if !self.has_rest {
 						let len = obj.len();
 						if len != self.field_names.len() {
-							throw_runtime!("too many fields, and rest not found");
+							throw!("too many fields, and rest not found");
 						}
 					}
 					Ok(obj)
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -150,13 +150,13 @@
 		(Num(v1), BitXor, Num(v2)) => Num(f64::from((*v1 as i32) ^ (*v2 as i32))),
 		(Num(v1), Lhs, Num(v2)) => {
 			if *v2 < 0.0 {
-				throw!(RuntimeError("shift by negative exponent".into()))
+				throw!("shift by negative exponent")
 			}
 			Num(f64::from((*v1 as i32) << (*v2 as i32)))
 		}
 		(Num(v1), Rhs, Num(v2)) => {
 			if *v2 < 0.0 {
-				throw!(RuntimeError("shift by negative exponent".into()))
+				throw!("shift by negative exponent")
 			}
 			Num(f64::from((*v1 as i32) >> (*v2 as i32)))
 		}
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -72,7 +72,7 @@
 				}
 				Self::Object(out)
 			}
-			Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+			Val::Func(_) => throw!("tried to manifest function"),
 		})
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -591,9 +591,7 @@
 			),
 			Val::Str(s) => {
 				if s.chars().count() != 1 {
-					throw!(RuntimeError(
-						format!("%c expected 1 char string, got {}", s.chars().count()).into(),
-					));
+					throw!("%c expected 1 char string, got {}", s.chars().count(),);
 				}
 				tmp_out.push_str(&s);
 			}
modifiedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -341,7 +341,7 @@
 				}
 			}
 		}
-		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+		Val::Func(_) => throw!("tried to manifest function"),
 	}
 	Ok(())
 }
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,7 +6,7 @@
 use jrsonnet_types::{ComplexValType, ValType};
 
 use crate::{
-	error::{Error::*, Result},
+	error::Result,
 	function::{FuncDesc, FuncVal},
 	throw,
 	typed::CheckType,
@@ -41,13 +41,10 @@
 					Val::Num(n) => {
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
-							throw!(RuntimeError(
-								format!(
-									"cannot convert number with fractional part to {}",
-									stringify!($ty)
-								)
-								.into()
-							))
+							throw!(
+								"cannot convert number with fractional part to {}",
+								stringify!($ty)
+							)
 						}
 						Ok(n as Self)
 					}
@@ -99,13 +96,10 @@
 					Val::Num(n) => {
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
-							throw!(RuntimeError(
-								format!(
-									"cannot convert number with fractional part to {}",
-									stringify!($ty)
-								)
-								.into()
-							))
+							throw!(
+								"cannot convert number with fractional part to {}",
+								stringify!($ty)
+							)
 						}
 						Ok(Self(n as $ty))
 					}
@@ -167,7 +161,7 @@
 
 	fn into_untyped(value: Self, _: State) -> Result<Val> {
 		if value > u32::MAX as Self {
-			throw!(RuntimeError("number is too large".into()))
+			throw!("number is too large")
 		}
 		Ok(Val::Num(value as f64))
 	}
@@ -178,9 +172,7 @@
 			Val::Num(n) => {
 				#[allow(clippy::float_cmp)]
 				if n.trunc() != n {
-					throw!(RuntimeError(
-						"cannot convert number with fractional part to usize".into()
-					))
+					throw!("cannot convert number with fractional part to usize")
 				}
 				Ok(n as Self)
 			}
@@ -440,7 +432,7 @@
 		<Self as Typed>::TYPE.check(s, &value)?;
 		match value {
 			Val::Func(FuncVal::Normal(desc)) => Ok(desc),
-			Val::Func(_) => throw!(RuntimeError("expected normal function, not builtin".into())),
+			Val::Func(_) => throw!("expected normal function, not builtin"),
 			_ => unreachable!(),
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -629,7 +629,7 @@
 		if num.is_finite() {
 			Ok(Self::Num(num))
 		} else {
-			throw!(RuntimeError("overflow".into()))
+			throw!("overflow")
 		}
 	}
 
@@ -843,14 +843,14 @@
 		(Val::Null, Val::Null) => true,
 		(Val::Str(a), Val::Str(b)) => a == b,
 		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
-		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(
-			"primitiveEquals operates on primitive types, got array".into(),
-		)),
-		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(
-			"primitiveEquals operates on primitive types, got object".into(),
-		)),
+		(Val::Arr(_), Val::Arr(_)) => {
+			throw!("primitiveEquals operates on primitive types, got array")
+		}
+		(Val::Obj(_), Val::Obj(_)) => {
+			throw!("primitiveEquals operates on primitive types, got object")
+		}
 		(a, b) if is_function_like(a) && is_function_like(b) => {
-			throw!(RuntimeError("cannot test equality of functions".into()))
+			throw!("cannot test equality of functions")
 		}
 		(_, _) => false,
 	})
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, FuncVal},
-	throw_runtime,
+	throw,
 	typed::{Any, BoundedUsize, Typed, VecVal},
 	val::{equals, ArrValue, IndexableVal},
 	IStr, State, Val,
@@ -43,7 +43,7 @@
 				match func.evaluate_simple(s.clone(), &(c.to_string(),))? {
 					Val::Str(o) => out.push_str(&o),
 					Val::Null => continue,
-					_ => throw_runtime!("in std.join all items should be strings"),
+					_ => throw!("in std.join all items should be strings"),
 				};
 			}
 			Ok(IndexableVal::Str(out.into()))
@@ -59,7 +59,7 @@
 						}
 					}
 					Val::Null => continue,
-					_ => throw_runtime!("in std.join all items should be arrays"),
+					_ => throw!("in std.join all items should be arrays"),
 				};
 			}
 			Ok(IndexableVal::Arr(out.into()))
@@ -128,7 +128,7 @@
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
-					throw_runtime!("in std.join all items should be arrays");
+					throw!("in std.join all items should be arrays");
 				}
 			}
 
@@ -149,7 +149,7 @@
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
-					throw_runtime!("in std.join all items should be strings");
+					throw!("in std.join all items should be strings");
 				}
 			}
 
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1use std::{2	cell::{Ref, RefCell, RefMut},3	collections::HashMap,4	rc::Rc,5};67use jrsonnet_evaluator::{8	error::{Error::*, Result},9	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10	gc::{GcHashMap, TraceBox},11	tb, throw_runtime,12	trace::PathResolver,13	typed::{Any, Either, Either2, Either4, VecVal, M1},14	val::{equals, ArrValue},15	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;4243pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {44	let mut builder = ObjValueBuilder::new();4546	let expr = expr::stdlib_expr();47	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)48		.expect("stdlib.jsonnet should have no errors")49		.as_obj()50		.expect("stdlib.jsonnet should evaluate to object");5152	builder.with_super(eval);5354	for (name, builtin) in [55		("length", builtin_length::INST),56		// Types57		("type", builtin_type::INST),58		("isString", builtin_is_string::INST),59		("isNumber", builtin_is_number::INST),60		("isBoolean", builtin_is_boolean::INST),61		("isObject", builtin_is_object::INST),62		("isArray", builtin_is_array::INST),63		("isFunction", builtin_is_function::INST),64		// Arrays65		("makeArray", builtin_make_array::INST),66		("slice", builtin_slice::INST),67		("map", builtin_map::INST),68		("flatMap", builtin_flatmap::INST),69		("filter", builtin_filter::INST),70		("foldl", builtin_foldl::INST),71		("foldr", builtin_foldr::INST),72		("range", builtin_range::INST),73		("join", builtin_join::INST),74		("reverse", builtin_reverse::INST),75		("any", builtin_any::INST),76		("all", builtin_all::INST),77		("member", builtin_member::INST),78		("count", builtin_count::INST),79		// Math80		("modulo", builtin_modulo::INST),81		("floor", builtin_floor::INST),82		("ceil", builtin_ceil::INST),83		("log", builtin_log::INST),84		("pow", builtin_pow::INST),85		("sqrt", builtin_sqrt::INST),86		("sin", builtin_sin::INST),87		("cos", builtin_cos::INST),88		("tan", builtin_tan::INST),89		("asin", builtin_asin::INST),90		("acos", builtin_acos::INST),91		("atan", builtin_atan::INST),92		("exp", builtin_exp::INST),93		("mantissa", builtin_mantissa::INST),94		("exponent", builtin_exponent::INST),95		// Operator96		("mod", builtin_mod::INST),97		("primitiveEquals", builtin_primitive_equals::INST),98		("equals", builtin_equals::INST),99		("format", builtin_format::INST),100		// Sort101		("sort", builtin_sort::INST),102		// Hash103		("md5", builtin_md5::INST),104		// Encoding105		("encodeUTF8", builtin_encode_utf8::INST),106		("decodeUTF8", builtin_decode_utf8::INST),107		("base64", builtin_base64::INST),108		("base64Decode", builtin_base64_decode::INST),109		("base64DecodeBytes", builtin_base64_decode_bytes::INST),110		// Objects111		("objectFieldsEx", builtin_object_fields_ex::INST),112		("objectHasEx", builtin_object_has_ex::INST),113		// Manifest114		("escapeStringJson", builtin_escape_string_json::INST),115		("manifestJsonEx", builtin_manifest_json_ex::INST),116		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),117		// Parsing118		("parseJson", builtin_parse_json::INST),119		("parseYaml", builtin_parse_yaml::INST),120		// Misc121		("codepoint", builtin_codepoint::INST),122		("substr", builtin_substr::INST),123		("char", builtin_char::INST),124		("strReplace", builtin_str_replace::INST),125		("splitLimit", builtin_splitlimit::INST),126		("asciiUpper", builtin_ascii_upper::INST),127		("asciiLower", builtin_ascii_lower::INST),128		("findSubstr", builtin_find_substr::INST),129		("startsWith", builtin_starts_with::INST),130		("endsWith", builtin_ends_with::INST),131	]132	.iter()133	.cloned()134	{135		builder136			.member(name.into())137			.hide()138			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))139			.expect("no conflict");140	}141142	builder143		.member("extVar".into())144		.hide()145		.value(146			s.clone(),147			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {148				settings: settings.clone()149			})))),150		)151		.expect("no conflict");152	builder153		.member("native".into())154		.hide()155		.value(156			s.clone(),157			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {158				settings: settings.clone()159			})))),160		)161		.expect("no conflict");162	builder163		.member("trace".into())164		.hide()165		.value(166			s.clone(),167			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),168		)169		.expect("no conflict");170171	builder172		.member("id".into())173		.hide()174		.value(s, Val::Func(FuncVal::Id))175		.expect("no conflict");176177	builder.build()178}179180pub trait TracePrinter {181	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);182}183184pub struct StdTracePrinter {185	resolver: PathResolver,186}187impl StdTracePrinter {188	pub fn new(resolver: PathResolver) -> Self {189		Self { resolver }190	}191}192impl TracePrinter for StdTracePrinter {193	fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {194		eprint!("TRACE:");195		if let Some(loc) = loc.0 {196			let locs = loc.0.map_source_locations(&[loc.1]);197			eprint!(198				" {}:{}",199				match loc.0.source_path().path() {200					Some(p) => self.resolver.resolve(p),201					None => loc.0.source_path().to_string(),202				},203				locs[0].line204			);205		}206		eprintln!(" {}", value);207	}208}209210pub struct Settings {211	/// Used for `std.extVar`212	pub ext_vars: HashMap<IStr, TlaArg>,213	/// Used for `std.native`214	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,215	/// Helper to add globals without implementing custom ContextInitializer216	pub globals: GcHashMap<IStr, Thunk<Val>>,217	/// Used for `std.trace`218	pub trace_printer: Box<dyn TracePrinter>,219	/// Used for `std.thisFile`220	pub path_resolver: PathResolver,221}222223pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {224	let source_name = format!("<extvar:{}>", name);225	Source::new_virtual(source_name.into(), code.into())226}227228pub struct ContextInitializer {229	// When we don't need to support legacy-this-file, we can reuse same context for all files230	#[cfg(not(feature = "legacy-this-file"))]231	context: Context,232	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it233	#[cfg(feature = "legacy-this-file")]234	stdlib_obj: ObjValue,235	settings: Rc<RefCell<Settings>>,236}237impl ContextInitializer {238	pub fn new(s: State, resolver: PathResolver) -> Self {239		let settings = Settings {240			ext_vars: Default::default(),241			ext_natives: Default::default(),242			globals: Default::default(),243			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),244			path_resolver: resolver,245		};246		let settings = Rc::new(RefCell::new(settings));247		Self {248			#[cfg(not(feature = "legacy-this-file"))]249			context: {250				let mut context = ContextBuilder::with_capacity(1);251				context.bind(252					"std".into(),253					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),254				);255				context.build()256			},257			#[cfg(feature = "legacy-this-file")]258			stdlib_obj: stdlib_uncached(s, settings.clone()),259			settings,260		}261	}262	pub fn settings(&self) -> Ref<Settings> {263		self.settings.borrow()264	}265	pub fn settings_mut(&self) -> RefMut<Settings> {266		self.settings.borrow_mut()267	}268	pub fn add_ext_var(&self, name: IStr, value: Val) {269		self.settings_mut()270			.ext_vars271			.insert(name, TlaArg::Val(value));272	}273	pub fn add_ext_str(&self, name: IStr, value: IStr) {274		self.settings_mut()275			.ext_vars276			.insert(name, TlaArg::String(value));277	}278	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {279		let code = code.into();280		let source = extvar_source(name, code.clone());281		let parsed = jrsonnet_parser::parse(282			&code,283			&jrsonnet_parser::ParserSettings {284				file_name: source.clone(),285			},286		)287		.map_err(|e| ImportSyntaxError {288			path: source,289			error: Box::new(e),290		})?;291		// self.data_mut().volatile_files.insert(source_name, code);292		self.settings_mut()293			.ext_vars294			.insert(name.into(), TlaArg::Code(parsed));295		Ok(())296	}297	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {298		self.settings_mut().ext_natives.insert(name, cb);299	}300}301impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {302	#[cfg(not(feature = "legacy-this-file"))]303	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {304		let out = self.context.clone();305		let globals = &self.settings().globals;306		if globals.is_empty() {307			return out;308		}309310		let mut out = ContextBuilder::extend(out);311		for (k, v) in globals.iter() {312			out.bind(k.clone(), v.clone());313		}314		out.build()315	}316	#[cfg(feature = "legacy-this-file")]317	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {318		let mut builder = ObjValueBuilder::new();319		builder.with_super(self.stdlib_obj.clone());320		builder321			.member("thisFile".into())322			.hide()323			.value(324				s,325				Val::Str(match source.source_path().path() {326					Some(p) => self.settings().path_resolver.resolve(p).into(),327					None => source.source_path().to_string().into(),328				}),329			)330			.expect("this object builder is empty");331		let stdlib_with_this_file = builder.build();332333		let mut context = ContextBuilder::with_capacity(1);334		context.bind(335			"std".into(),336			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),337		);338		for (k, v) in self.settings().globals.iter() {339			context.bind(k.clone(), v.clone());340		}341		context.build()342	}343	fn as_any(&self) -> &dyn std::any::Any {344		self345	}346}347348#[builtin]349fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {350	use Either4::*;351	Ok(match x {352		A(x) => x.chars().count(),353		B(x) => x.len(),354		C(x) => x.len(),355		D(f) => f.params_len(),356	})357}358359#[builtin]360const fn builtin_codepoint(str: char) -> Result<u32> {361	Ok(str as u32)362}363364#[builtin]365fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {366	Ok(str.chars().skip(from).take(len).collect())367}368369#[builtin(fields(370	settings: Rc<RefCell<Settings>>,371))]372fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {373	let ctx = s.create_default_context(extvar_source(&x, ""));374	Ok(Any(this375		.settings376		.borrow()377		.ext_vars378		.get(&x)379		.cloned()380		.ok_or_else(|| UndefinedExternalVariable(x))?381		.evaluate_arg(s.clone(), ctx, true)?382		.evaluate(s)?))383}384385#[builtin(fields(386	settings: Rc<RefCell<Settings>>,387))]388fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {389	Ok(Any(this390		.settings391		.borrow()392		.ext_natives393		.get(&name)394		.cloned()395		.map_or(Val::Null, |v| {396			Val::Func(FuncVal::Builtin(v.clone()))397		})))398}399400#[builtin]401fn builtin_char(n: u32) -> Result<char> {402	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)403}404405#[builtin(fields(406	settings: Rc<RefCell<Settings>>,407))]408fn builtin_trace(409	this: &builtin_trace,410	s: State,411	loc: CallLocation,412	str: IStr,413	rest: Thunk<Val>,414) -> Result<Any> {415	this.settings416		.borrow()417		.trace_printer418		.print_trace(s.clone(), loc, str);419	Ok(Any(rest.evaluate(s)?))420}421422#[builtin]423fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {424	Ok(str.replace(&from as &str, &to as &str))425}426427#[builtin]428fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {429	use Either2::*;430	Ok(VecVal(Cc::new(match maxsplits {431		A(n) => str432			.splitn(n + 1, &c as &str)433			.map(|s| Val::Str(s.into()))434			.collect(),435		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),436	})))437}438439#[builtin]440fn builtin_ascii_upper(str: IStr) -> Result<String> {441	Ok(str.to_ascii_uppercase())442}443444#[builtin]445fn builtin_ascii_lower(str: IStr) -> Result<String> {446	Ok(str.to_ascii_lowercase())447}448449#[builtin]450fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {451	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {452		return Ok(ArrValue::empty());453	}454455	let str = str.as_str();456	let pat = pat.as_bytes();457	let strb = str.as_bytes();458459	let max_pos = str.len() - pat.len();460461	let mut out: Vec<Val> = Vec::new();462	for (ch_idx, (i, _)) in str463		.char_indices()464		.take_while(|(i, _)| i <= &max_pos)465		.enumerate()466	{467		if &strb[i..i + pat.len()] == pat {468			out.push(Val::Num(ch_idx as f64))469		}470	}471	Ok(out.into())472}473474#[allow(clippy::comparison_chain)]475#[builtin]476fn builtin_starts_with(477	s: State,478	a: Either![IStr, ArrValue],479	b: Either![IStr, ArrValue],480) -> Result<bool> {481	Ok(match (a, b) {482		(Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),483		(Either2::B(a), Either2::B(b)) => {484			if b.len() > a.len() {485				return Ok(false);486			} else if b.len() == a.len() {487				return equals(s, &Val::Arr(a), &Val::Arr(b));488			} else {489				for (a, b) in a490					.slice(None, Some(b.len()), None)491					.iter(s.clone())492					.zip(b.iter(s.clone()))493				{494					let a = a?;495					let b = b?;496					if !equals(s.clone(), &a, &b)? {497						return Ok(false);498					}499				}500				true501			}502		}503		_ => throw_runtime!("both arguments should be of the same type"),504	})505}506507#[allow(clippy::comparison_chain)]508#[builtin]509fn builtin_ends_with(510	s: State,511	a: Either![IStr, ArrValue],512	b: Either![IStr, ArrValue],513) -> Result<bool> {514	Ok(match (a, b) {515		(Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),516		(Either2::B(a), Either2::B(b)) => {517			if b.len() > a.len() {518				return Ok(false);519			} else if b.len() == a.len() {520				return equals(s, &Val::Arr(a), &Val::Arr(b));521			} else {522				let a_len = a.len();523				for (a, b) in a524					.slice(Some(a_len - b.len()), None, None)525					.iter(s.clone())526					.zip(b.iter(s.clone()))527				{528					let a = a?;529					let b = b?;530					if !equals(s.clone(), &a, &b)? {531						return Ok(false);532					}533				}534				true535			}536		}537		_ => throw_runtime!("both arguments should be of the same type"),538	})539}540541pub trait StateExt {542	/// This method was previously implemented in jrsonnet-evaluator itself543	fn with_stdlib(&self);544	fn add_global(&self, name: IStr, value: Thunk<Val>);545}546547impl StateExt for State {548	fn with_stdlib(&self) {549		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());550		self.settings_mut().context_initializer = Box::new(initializer)551	}552	fn add_global(&self, name: IStr, value: Thunk<Val>) {553		self.settings()554			.context_initializer555			.as_any()556			.downcast_ref::<ContextInitializer>()557			.expect("not standard context initializer")558			.settings_mut()559			.globals560			.insert(name, value);561	}562}
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, FuncVal},
-	throw_runtime,
+	throw,
 	typed::Any,
 	val::ArrValue,
 	State, Val,
@@ -41,9 +41,9 @@
 			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
 			(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
 			(Val::Str(_) | Val::Num(_), _) => {
-				throw_runtime!("sort elements should have the same types")
+				throw!("sort elements should have the same types")
 			}
-			_ => throw_runtime!("sort key should either be a string or a number"),
+			_ => throw!("sort key should either be a string or a number"),
 		}
 	}
 	Ok(sort_type)
modifiedtests/tests/common.rsdiffbeforeafterboth
--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, FuncVal},
-	throw_runtime, ObjValueBuilder, State, Thunk, Val,
+	throw, ObjValueBuilder, State, Thunk, Val,
 };
 use jrsonnet_stdlib::StateExt;
 
@@ -11,7 +11,7 @@
 		let a = &$a;
 		let b = &$b;
 		if a != b {
-			::jrsonnet_evaluator::throw_runtime!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+			::jrsonnet_evaluator::throw!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
 		}
 	}};
 }
@@ -20,7 +20,7 @@
 macro_rules! ensure {
 	($v:expr $(,)?) => {
 		if !$v {
-			::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+			::jrsonnet_evaluator::throw!("assertion failed: {}", stringify!($v))
 		}
 	};
 }
@@ -29,7 +29,7 @@
 macro_rules! ensure_val_eq {
 	($s:expr, $a:expr, $b:expr) => {{
 		if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
-			::jrsonnet_evaluator::throw_runtime!(
+			::jrsonnet_evaluator::throw!(
 				"assertion failed: a != b\na={:#?}\nb={:#?}",
 				$a.to_json(
 					$s.clone(),
@@ -52,7 +52,7 @@
 fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
 	match lazy.evaluate(s) {
 		Ok(_) => {
-			throw_runtime!("expected argument to throw on evaluation, but it returned instead")
+			throw!("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,4 +1,4 @@
-use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+use jrsonnet_evaluator::{error::Result, throw, State, Val};
 use jrsonnet_stdlib::StateExt;
 
 mod common;
@@ -23,7 +23,7 @@
 
 	{
 		let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") {
-			Ok(_) => throw_runtime!("assertion should fail"),
+			Ok(_) => throw!("assertion should fail"),
 			Err(e) => e,
 		};
 		let e = s.stringify_err(&e);
@@ -31,7 +31,7 @@
 	}
 	{
 		let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") {
-			Ok(_) => throw_runtime!("assertion should fail"),
+			Ok(_) => throw!("assertion should fail"),
 			Err(e) => e,
 		};
 		let e = s.stringify_err(&e);