git.delta.rocks / jrsonnet / refs/commits / 4c3faa0f088c

difftreelog

refactor reduce callsite boilerplate

Yaroslav Bolyukin2022-12-08parent: #ccafbf7.patch.diff
in: master

38 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -116,12 +116,11 @@
 	cb: JsonnetImportCallback,
 	ctx: *mut c_void,
 ) {
-	vm.state
-		.set_import_resolver(Box::new(CallbackImportResolver {
-			cb,
-			ctx,
-			out: RefCell::new(HashMap::new()),
-		}))
+	vm.state.set_import_resolver(CallbackImportResolver {
+		cb,
+		ctx,
+		out: RefCell::new(HashMap::new()),
+	})
 }
 
 /// # Safety
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -7,11 +7,9 @@
 use jrsonnet_evaluator::{
 	error::{Error, ErrorKind},
 	function::builtin::{NativeCallback, NativeCallbackHandler},
-	tb,
 	typed::Typed,
 	IStr, Val,
 };
-use jrsonnet_gcmodule::Cc;
 
 use crate::VM;
 
@@ -102,9 +100,6 @@
 		.add_native(
 			name,
 			#[allow(deprecated)]
-			Cc::new(tb!(NativeCallback::new(
-				params,
-				tb!(JsonnetNativeCallbackHandler { ctx, cb }),
-			))),
+			NativeCallback::new(params, JsonnetNativeCallbackHandler { ctx, cb }),
 		)
 }
modifiedbindings/jsonnet/src/val_extract.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -13,7 +13,10 @@
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_string(_vm: &VM, v: &Val) -> *mut c_char {
 	match v {
-		Val::Str(s) => CString::new(s as &str).unwrap().into_raw(),
+		Val::Str(s) => {
+			let s = s.clone().into_flat();
+			CString::new(s.as_str()).unwrap().into_raw()
+		}
 		_ => std::ptr::null_mut(),
 	}
 }
modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,8 +5,10 @@
 	os::raw::{c_char, c_double, c_int},
 };
 
-use jrsonnet_evaluator::{val::ArrValue, ObjValue, Val};
-use jrsonnet_gcmodule::Cc;
+use jrsonnet_evaluator::{
+	val::{ArrValue, StrValue},
+	ObjValue, Val,
+};
 
 use crate::VM;
 
@@ -19,7 +21,7 @@
 pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &VM, val: *const c_char) -> *mut Val {
 	let val = CStr::from_ptr(val);
 	let val = val.to_str().expect("string is not utf-8");
-	Box::into_raw(Box::new(Val::Str(val.into())))
+	Box::into_raw(Box::new(Val::Str(StrValue::Flat(val.into()))))
 }
 
 /// Convert the given double to a `JsonnetJsonValue`.
@@ -46,7 +48,7 @@
 /// Assign elements with [`jsonnet_json_array_append`].
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_array(_vm: &VM) -> *mut Val {
-	Box::into_raw(Box::new(Val::Arr(ArrValue::eager(Cc::new(Vec::new())))))
+	Box::into_raw(Box::new(Val::Arr(ArrValue::eager(Vec::new()))))
 }
 
 /// Make a `JsonnetJsonValue` representing an object.
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -54,7 +54,7 @@
 			library_paths.extend(env::split_paths(path.as_os_str()));
 		}
 
-		s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));
+		s.set_import_resolver(FileImportResolver::new(library_paths));
 
 		set_stack_depth_limit(self.max_stack);
 		Ok(())
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -55,8 +55,8 @@
 		Self::Lazy(LazyArray(thunks))
 	}
 
-	pub fn eager(values: Cc<Vec<Val>>) -> Self {
-		Self::Eager(EagerArray(values))
+	pub fn eager(values: Vec<Val>) -> Self {
+		Self::Eager(EagerArray(Cc::new(values)))
 	}
 
 	pub fn repeated(data: ArrValue, repeats: usize) -> Option<Self> {
@@ -81,7 +81,7 @@
 				out.push(i);
 			};
 		}
-		Ok(Self::eager(Cc::new(out)))
+		Ok(Self::eager(out))
 	}
 
 	pub fn extended(a: ArrValue, b: ArrValue) -> Self {
@@ -98,7 +98,7 @@
 			let mut out = Vec::with_capacity(a.len() + b.len());
 			out.extend(a);
 			out.extend(b);
-			Self::eager(Cc::new(out))
+			Self::eager(out)
 		} else {
 			let mut out = Vec::with_capacity(a.len() + b.len());
 			out.extend(a.iter_lazy());
@@ -235,7 +235,7 @@
 }
 impl From<Vec<Val>> for ArrValue {
 	fn from(value: Vec<Val>) -> Self {
-		Self::eager(Cc::new(value))
+		Self::eager(value)
 	}
 }
 impl From<Vec<Thunk<Val>>> for ArrValue {
@@ -243,6 +243,11 @@
 		Self::lazy(Cc::new(value))
 	}
 }
+impl FromIterator<Val> for ArrValue {
+	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {
+		Self::eager(iter.into_iter().collect())
+	}
+}
 
 #[cfg(target_pointer_width = "64")]
 static_assertions::assert_eq_size!(ArrValue, [u8; 16]);
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -7,10 +7,10 @@
 use jrsonnet_interner::IBytes;
 use jrsonnet_parser::LocExpr;
 
-use super::{ArrValue, ArrayLikeIter};
+use super::ArrValue;
 use crate::{
-	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, tb, typed::Any,
-	val::ThunkValue, Context, Error, Result, Thunk, Val,
+	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, val::ThunkValue,
+	Context, Error, Result, Thunk, Val,
 };
 
 pub trait ArrayLike: Sized + Into<ArrValue> {
@@ -75,7 +75,7 @@
 	}
 
 	#[cfg(not(feature = "nightly"))]
-	fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {
+	fn iter_cheap(&self) -> Option<impl crate::arr::ArrayLikeIter<Val> + '_> {
 		Some(
 			self.inner
 				.iter_cheap()?
@@ -300,10 +300,10 @@
 			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
 		};
 
-		Some(Thunk::new(tb!(ArrayElement {
+		Some(Thunk::new(ArrayElement {
 			arr_thunk: self.clone(),
 			index,
-		})))
+		}))
 	}
 	fn get_cheap(&self, _index: usize) -> Option<Val> {
 		None
@@ -748,7 +748,7 @@
 			.get(index)
 			.transpose()
 			.expect("index checked")
-			.and_then(|r| self.0.mapper.evaluate_simple(&(Any(r),)));
+			.and_then(|r| self.0.mapper.evaluate_simple(&(r,)));
 
 		let new_value = match val {
 			Ok(v) => v,
@@ -787,10 +787,10 @@
 			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
 		};
 
-		Some(Thunk::new(tb!(ArrayElement {
+		Some(Thunk::new(ArrayElement {
 			arr_thunk: self.clone(),
 			index,
-		})))
+		}))
 	}
 
 	fn get_cheap(&self, _index: usize) -> Option<Val> {
modifiedcrates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -294,7 +294,6 @@
 		path: handler.resolve(path.as_ref()).await?,
 		parse: true,
 	}];
-	// let mut resolved = HashMap::<(SourcePath, IStr), (SourcePath, bool)>::new();
 	while let Some(job) = queue.pop() {
 		match job {
 			Job::LoadFile { path, parse } => {
@@ -349,8 +348,8 @@
 			}
 		}
 	}
-	s.set_import_resolver(Box::new(ResolvedImportResolver {
+	s.set_import_resolver(ResolvedImportResolver {
 		resolved: RefCell::new(resolved),
-	}));
+	});
 	Ok(())
 }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -39,16 +39,16 @@
 			.expect("used state from dummy context")
 	}
 
-	pub fn dollar(&self) -> &Option<ObjValue> {
-		&self.0.dollar
+	pub fn dollar(&self) -> Option<&ObjValue> {
+		self.0.dollar.as_ref()
 	}
 
-	pub fn this(&self) -> &Option<ObjValue> {
-		&self.0.this
+	pub fn this(&self) -> Option<&ObjValue> {
+		self.0.this.as_ref()
 	}
 
-	pub fn super_obj(&self) -> &Option<ObjValue> {
-		&self.0.sup
+	pub fn super_obj(&self) -> Option<&ObjValue> {
+		self.0.sup.as_ref()
 	}
 
 	#[cfg(not(feature = "friendly-errors"))]
@@ -130,12 +130,6 @@
 		}))
 	}
 }
-
-// impl Default for Context {
-// 	fn default() -> Self {
-// 		Self::new()
-// 	}
-// }
 
 impl PartialEq for Context {
 	fn eq(&self, other: &Self) -> bool {
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -6,7 +6,7 @@
 	error::{ErrorKind::*, Result},
 	evaluate, evaluate_method, evaluate_named,
 	gc::GcHashMap,
-	tb, throw,
+	throw,
 	val::ThunkValue,
 	Context, Pending, Thunk, Val,
 };
@@ -63,11 +63,11 @@
 				}
 			}
 
-			let full = Thunk::new(tb!(DataThunk {
+			let full = Thunk::new(DataThunk {
 				min_len: start.len() + end.len(),
 				has_rest: rest.is_some(),
 				parent,
-			}));
+			});
 
 			{
 				#[derive(Trace)]
@@ -86,10 +86,10 @@
 				for (i, d) in start.iter().enumerate() {
 					destruct(
 						d,
-						Thunk::new(tb!(BaseThunk {
+						Thunk::new(BaseThunk {
 							full: full.clone(),
 							index: i,
-						})),
+						}),
 						fctx.clone(),
 						new_bindings,
 					)?;
@@ -119,11 +119,11 @@
 
 					destruct(
 						&Destruct::Full(v.clone()),
-						Thunk::new(tb!(RestThunk {
+						Thunk::new(RestThunk {
 							full: full.clone(),
 							start: start.len(),
 							end: end.len(),
-						})),
+						}),
 						fctx.clone(),
 						new_bindings,
 					)?;
@@ -151,11 +151,11 @@
 				for (i, d) in end.iter().enumerate() {
 					destruct(
 						d,
-						Thunk::new(tb!(EndThunk {
+						Thunk::new(EndThunk {
 							full: full.clone(),
 							index: i,
 							end: end.len(),
-						})),
+						}),
 						fctx.clone(),
 						new_bindings,
 					)?;
@@ -199,11 +199,11 @@
 				.filter(|f| f.2.is_none())
 				.map(|f| f.0.clone())
 				.collect();
-			let full = Thunk::new(tb!(DataThunk {
+			let full = Thunk::new(DataThunk {
 				parent,
 				field_names,
-				has_rest: rest.is_some()
-			}));
+				has_rest: rest.is_some(),
+			});
 
 			for (field, d, default) in fields {
 				#[derive(Trace)]
@@ -225,11 +225,11 @@
 						}
 					}
 				}
-				let value = Thunk::new(tb!(FieldThunk {
+				let value = Thunk::new(FieldThunk {
 					full: full.clone(),
 					field: field.clone(),
 					default: default.clone().map(|e| (fctx.clone(), e)),
-				}));
+				});
 				if let Some(d) = d {
 					destruct(d, value, fctx.clone(), new_bindings)?;
 				} else {
@@ -268,11 +268,11 @@
 					)
 				}
 			}
-			let data = Thunk::new(tb!(EvaluateThunkValue {
+			let data = Thunk::new(EvaluateThunkValue {
 				name: into.name(),
 				fctx: fctx.clone(),
 				expr: value.clone(),
-			}));
+			});
 			destruct(into, data, fctx, new_bindings)?;
 		}
 		BindSpec::Function {
@@ -302,12 +302,12 @@
 
 			let old = new_bindings.insert(
 				name.clone(),
-				Thunk::new(tb!(MethodThunk {
+				Thunk::new(MethodThunk {
 					fctx,
 					name: name.clone(),
 					params: params.clone(),
-					value: value.clone()
-				})),
+					value: value.clone(),
+				}),
 			);
 			if old.is_some() {
 				throw!(DuplicateLocalVar(name.clone()))
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use self::destructure::destruct;12use crate::{13	arr::ArrValue,14	destructure::evaluate_dest,15	error::ErrorKind::*,16	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},17	function::{CallLocation, FuncDesc, FuncVal},18	tb, throw,19	typed::Typed,20	val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},21	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,22	Unbound, Val,23};24pub mod destructure;25pub mod operator;2627pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {28	fn is_trivial(expr: &LocExpr) -> bool {29		match &*expr.0 {30			Expr::Str(_)31			| Expr::Num(_)32			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,33			Expr::Arr(a) => a.iter().all(is_trivial),34			Expr::Parened(e) => is_trivial(e),35			_ => false,36		}37	}38	Some(match &*expr.0 {39		Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),40		Expr::Num(n) => Val::Num(*n),41		Expr::Literal(LiteralType::False) => Val::Bool(false),42		Expr::Literal(LiteralType::True) => Val::Bool(true),43		Expr::Literal(LiteralType::Null) => Val::Null,44		Expr::Arr(n) => {45			if n.iter().any(|e| !is_trivial(e)) {46				return None;47			}48			Val::Arr(ArrValue::eager(Cc::new(49				n.iter()50					.map(evaluate_trivial)51					.map(|e| e.expect("checked trivial"))52					.collect(),53			)))54		}55		Expr::Parened(e) => evaluate_trivial(e)?,56		_ => return None,57	})58}5960pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {61	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {62		name,63		ctx,64		params,65		body,66	})))67}6869pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {70	Ok(match field_name {71		FieldName::Fixed(n) => Some(n.clone()),72		FieldName::Dyn(expr) => State::push(73			CallLocation::new(&expr.1),74			|| "evaluating field name".to_string(),75			|| {76				let value = evaluate(ctx, expr)?;77				if matches!(value, Val::Null) {78					Ok(None)79				} else {80					Ok(Some(IStr::from_untyped(value)?))81				}82			},83		)?,84	})85}8687pub fn evaluate_comp(88	ctx: Context,89	specs: &[CompSpec],90	callback: &mut impl FnMut(Context) -> Result<()>,91) -> Result<()> {92	match specs.get(0) {93		None => callback(ctx)?,94		Some(CompSpec::IfSpec(IfSpecData(cond))) => {95			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {96				evaluate_comp(ctx, &specs[1..], callback)?;97			}98		}99		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {100			Val::Arr(list) => {101				for item in list.iter_lazy() {102					let fctx = Pending::new();103					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());104					destruct(var, item, fctx.clone(), &mut new_bindings)?;105					let ctx = ctx106						.clone()107						.extend(new_bindings, None, None, None)108						.into_future(fctx);109110					evaluate_comp(ctx, &specs[1..], callback)?;111				}112			}113			#[cfg(feature = "exp-object-iteration")]114			Val::Obj(obj) => {115				for field in obj.fields(116					// TODO: Should there be ability to preserve iteration order?117					#[cfg(feature = "exp-preserve-order")]118					false,119				) {120					#[derive(Trace)]121					struct ObjectFieldThunk {122						obj: ObjValue,123						field: IStr,124					}125					impl ThunkValue for ObjectFieldThunk {126						type Output = Val;127128						fn get(self: Box<Self>) -> Result<Self::Output> {129							self.obj.get(self.field).transpose().expect(130								"field exists, as field name was obtained from object.fields()",131							)132						}133					}134135					let fctx = Pending::new();136					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());137					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(Cc::new(vec![138						Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),139						Thunk::new(tb!(ObjectFieldThunk {140							field: field.clone(),141							obj: obj.clone(),142						})),143					]))));144					destruct(var, value, fctx.clone(), &mut new_bindings)?;145					let ctx = ctx146						.clone()147						.extend(new_bindings, None, None, None)148						.into_future(fctx);149150					evaluate_comp(ctx, &specs[1..], callback)?;151				}152			}153			_ => throw!(InComprehensionCanOnlyIterateOverArray),154		},155	}156	Ok(())157}158159trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}160impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}161162fn evaluate_object_locals(163	fctx: Pending<Context>,164	locals: Rc<Vec<BindSpec>>,165) -> impl CloneableUnbound<Context> {166	#[derive(Trace, Clone)]167	struct UnboundLocals {168		fctx: Pending<Context>,169		locals: Rc<Vec<BindSpec>>,170	}171	impl Unbound for UnboundLocals {172		type Bound = Context;173174		fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {175			let fctx = Context::new_future();176			let mut new_bindings =177				GcHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());178			for b in self.locals.iter() {179				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;180			}181182			let ctx = self.fctx.unwrap();183			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());184185			let ctx = ctx186				.extend(new_bindings, new_dollar, sup, this)187				.into_future(fctx);188189			Ok(ctx)190		}191	}192193	UnboundLocals { fctx, locals }194}195196pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(197	builder: &mut ObjValueBuilder,198	ctx: Context,199	uctx: B,200	field: &FieldMember,201) -> Result<()> {202	let name = evaluate_field_name(ctx, &field.name)?;203	let Some(name) = name else {204		return Ok(());205	};206207	match field {208		FieldMember {209			plus,210			params: None,211			visibility,212			value,213			..214		} => {215			#[derive(Trace)]216			struct UnboundValue<B: Trace> {217				uctx: B,218				value: LocExpr,219				name: IStr,220			}221			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {222				type Bound = Val;223				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {224					evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())225				}226			}227228			builder229				.member(name.clone())230				.with_add(*plus)231				.with_visibility(*visibility)232				.with_location(value.1.clone())233				.bindable(tb!(UnboundValue {234					uctx,235					value: value.clone(),236					name,237				}))?;238		}239		FieldMember {240			params: Some(params),241			visibility,242			value,243			..244		} => {245			#[derive(Trace)]246			struct UnboundMethod<B: Trace> {247				uctx: B,248				value: LocExpr,249				params: ParamsDesc,250				name: IStr,251			}252			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {253				type Bound = Val;254				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {255					Ok(evaluate_method(256						self.uctx.bind(sup, this)?,257						self.name.clone(),258						self.params.clone(),259						self.value.clone(),260					))261				}262			}263264			builder265				.member(name.clone())266				.with_visibility(*visibility)267				.with_location(value.1.clone())268				.bindable(tb!(UnboundMethod {269					uctx,270					value: value.clone(),271					params: params.clone(),272					name,273				}))?;274		}275	}276	Ok(())277}278279#[allow(clippy::too_many_lines)]280pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {281	let mut builder = ObjValueBuilder::new();282	let locals = Rc::new(283		members284			.iter()285			.filter_map(|m| match m {286				Member::BindStmt(bind) => Some(bind.clone()),287				_ => None,288			})289			.collect::<Vec<_>>(),290	);291292	let fctx = Context::new_future();293294	// We have single context for all fields, so we can cache binds295	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));296297	for member in members.iter() {298		match member {299			Member::Field(field) => {300				evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;301			}302			Member::AssertStmt(stmt) => {303				#[derive(Trace)]304				struct ObjectAssert<B: Trace> {305					uctx: B,306					assert: AssertStmt,307				}308				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {309					fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {310						let ctx = self.uctx.bind(sup, this)?;311						evaluate_assert(ctx, &self.assert)312					}313				}314				builder.assert(tb!(ObjectAssert {315					uctx: uctx.clone(),316					assert: stmt.clone(),317				}));318			}319			Member::BindStmt(_) => {320				// Already handled321			}322		}323	}324	let this = builder.build();325	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));326	Ok(this)327}328329pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {330	Ok(match object {331		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,332		ObjBody::ObjComp(obj) => {333			let mut builder = ObjValueBuilder::new();334			let locals = Rc::new(335				obj.pre_locals336					.iter()337					.chain(obj.post_locals.iter())338					.cloned()339					.collect::<Vec<_>>(),340			);341			let mut ctxs = vec![];342			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {343				let fctx = Context::new_future();344				ctxs.push((ctx.clone(), fctx.clone()));345				let uctx = evaluate_object_locals(fctx, locals.clone());346347				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)348			})?;349350			let this = builder.build();351			for (ctx, fctx) in ctxs {352				let _ctx = ctx353					.extend(GcHashMap::new(), None, None, Some(this.clone()))354					.into_future(fctx);355			}356			this357		}358	})359}360361pub fn evaluate_apply(362	ctx: Context,363	value: &LocExpr,364	args: &ArgsDesc,365	loc: CallLocation<'_>,366	tailstrict: bool,367) -> Result<Val> {368	let value = evaluate(ctx.clone(), value)?;369	Ok(match value {370		Val::Func(f) => {371			let body = || f.evaluate(ctx, loc, args, tailstrict);372			if tailstrict {373				body()?374			} else {375				State::push(loc, || format!("function <{}> call", f.name()), body)?376			}377		}378		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),379	})380}381382pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {383	let value = &assertion.0;384	let msg = &assertion.1;385	let assertion_result = State::push(386		CallLocation::new(&value.1),387		|| "assertion condition".to_owned(),388		|| bool::from_untyped(evaluate(ctx.clone(), value)?),389	)?;390	if !assertion_result {391		State::push(392			CallLocation::new(&value.1),393			|| "assertion failure".to_owned(),394			|| {395				if let Some(msg) = msg {396					throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));397				}398				throw!(AssertionFailed(Val::Null.to_string()?));399			},400		)?;401	}402	Ok(())403}404405pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {406	use Expr::*;407	let LocExpr(raw_expr, _loc) = expr;408	Ok(match &**raw_expr {409		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),410		_ => evaluate(ctx, expr)?,411	})412}413414#[allow(clippy::too_many_lines)]415pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {416	use Expr::*;417	if let Some(trivial) = evaluate_trivial(expr) {418		return Ok(trivial);419	}420	let LocExpr(expr, loc) = expr;421	Ok(match &**expr {422		Literal(LiteralType::This) => {423			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)424		}425		Literal(LiteralType::Super) => Val::Obj(426			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(427				ctx.this()428					.clone()429					.expect("if super exists - then this should too"),430			),431		),432		Literal(LiteralType::Dollar) => {433			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)434		}435		Literal(LiteralType::True) => Val::Bool(true),436		Literal(LiteralType::False) => Val::Bool(false),437		Literal(LiteralType::Null) => Val::Null,438		Parened(e) => evaluate(ctx, e)?,439		Str(v) => Val::Str(StrValue::Flat(v.clone())),440		Num(v) => Val::new_checked_num(*v)?,441		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,442		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,443		Var(name) => State::push(444			CallLocation::new(loc),445			|| format!("variable <{name}> access"),446			|| ctx.binding(name.clone())?.evaluate(),447		)?,448		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {449			let name = evaluate(ctx.clone(), index)?;450			let Val::Str(name) = name else {451				throw!(ValueIndexMustBeTypeGot(452					ValType::Obj,453					ValType::Str,454					name.value_type(),455				))456			};457			ctx.super_obj()458				.clone()459				.expect("no super found")460				.get_for(name.into_flat(), ctx.this().clone().expect("no this found"))?461				.expect("value not found")462		}463		Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {464			(Val::Obj(v), Val::Str(key)) => State::push(465				CallLocation::new(loc),466				|| format!("field <{key}> access"),467				|| match v.get(key.clone().into_flat()) {468					Ok(Some(v)) => Ok(v),469					#[cfg(not(feature = "friendly-errors"))]470					Ok(None) => throw!(NoSuchField(key.clone(), vec![])),471					#[cfg(feature = "friendly-errors")]472					Ok(None) => {473						let mut heap = Vec::new();474						for field in v.fields_ex(475							true,476							#[cfg(feature = "exp-preserve-order")]477							false,478						) {479							let conf = strsim::jaro_winkler(480								&field as &str,481								&key.clone().into_flat() as &str,482							);483							if conf < 0.8 {484								continue;485							}486							heap.push((conf, field));487						}488						heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));489490						throw!(NoSuchField(491							key.clone().into_flat(),492							heap.into_iter().map(|(_, v)| v).collect()493						))494					}495					Err(e) => Err(e),496				},497			)?,498			(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(499				ValType::Obj,500				ValType::Str,501				n.value_type(),502			)),503504			(Val::Arr(v), Val::Num(n)) => {505				if n.fract() > f64::EPSILON {506					throw!(FractionalIndex)507				}508				v.get(n as usize)?509					.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?510			}511			(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n.into_flat())),512			(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(513				ValType::Arr,514				ValType::Num,515				n.value_type(),516			)),517518			(Val::Str(s), Val::Num(n)) => Val::Str({519				let v: IStr = s520					.clone()521					.into_flat()522					.chars()523					.skip(n as usize)524					.take(1)525					.collect::<String>()526					.into();527				if v.is_empty() {528					let size = s.into_flat().chars().count();529					throw!(StringBoundsError(n as usize, size))530				}531				StrValue::Flat(v)532			}),533			(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(534				ValType::Str,535				ValType::Num,536				n.value_type(),537			)),538539			(v, _) => throw!(CantIndexInto(v.value_type())),540		},541		LocalExpr(bindings, returned) => {542			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =543				GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());544			let fctx = Context::new_future();545			for b in bindings {546				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;547			}548			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);549			evaluate(ctx, &returned.clone())?550		}551		Arr(items) => {552			if items.is_empty() {553				Val::Arr(ArrValue::empty())554			} else if items.len() == 1 {555				#[derive(Trace)]556				struct ArrayElement {557					ctx: Context,558					item: LocExpr,559				}560				impl ThunkValue for ArrayElement {561					type Output = Val;562					fn get(self: Box<Self>) -> Result<Val> {563						evaluate(self.ctx, &self.item)564					}565				}566				Val::Arr(ArrValue::lazy(Cc::new(vec![Thunk::new(tb!(567					ArrayElement {568						ctx,569						item: items[0].clone(),570					}571				))])))572			} else {573				Val::Arr(ArrValue::expr(ctx, items.iter().cloned()))574			}575		}576		ArrComp(expr, comp_specs) => {577			let mut out = Vec::new();578			evaluate_comp(ctx, comp_specs, &mut |ctx| {579				out.push(evaluate(ctx, expr)?);580				Ok(())581			})?;582			Val::Arr(ArrValue::eager(Cc::new(out)))583		}584		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),585		ObjExtend(a, b) => evaluate_add_op(586			&evaluate(ctx.clone(), a)?,587			&Val::Obj(evaluate_object(ctx, b)?),588		)?,589		Apply(value, args, tailstrict) => {590			evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?591		}592		Function(params, body) => {593			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())594		}595		AssertExpr(assert, returned) => {596			evaluate_assert(ctx.clone(), assert)?;597			evaluate(ctx, returned)?598		}599		ErrorStmt(e) => State::push(600			CallLocation::new(loc),601			|| "error statement".to_owned(),602			|| throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),603		)?,604		IfElse {605			cond,606			cond_then,607			cond_else,608		} => {609			if State::push(610				CallLocation::new(loc),611				|| "if condition".to_owned(),612				|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),613			)? {614				evaluate(ctx, cond_then)?615			} else {616				match cond_else {617					Some(v) => evaluate(ctx, v)?,618					None => Val::Null,619				}620			}621		}622		Slice(value, desc) => {623			fn parse_idx<T: Typed>(624				loc: CallLocation<'_>,625				ctx: &Context,626				expr: &Option<LocExpr>,627				desc: &'static str,628			) -> Result<Option<T>> {629				if let Some(value) = expr {630					Ok(Some(State::push(631						loc,632						|| format!("slice {desc}"),633						|| T::from_untyped(evaluate(ctx.clone(), value)?),634					)?))635				} else {636					Ok(None)637				}638			}639640			let indexable = evaluate(ctx.clone(), value)?;641			let loc = CallLocation::new(loc);642643			let start = parse_idx(loc, &ctx, &desc.start, "start")?;644			let end = parse_idx(loc, &ctx, &desc.end, "end")?;645			let step = parse_idx(loc, &ctx, &desc.step, "step")?;646647			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?648		}649		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {650			let Expr::Str(path) = &*path.0 else {651				throw!("computed imports are not supported")652			};653			let tmp = loc.clone().0;654			let s = ctx.state();655			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;656			match i {657				Import(_) => State::push(658					CallLocation::new(loc),659					|| format!("import {:?}", path.clone()),660					|| s.import_resolved(resolved_path),661				)?,662				ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),663				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),664				_ => unreachable!(),665			}666		}667	})668}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use self::destructure::destruct;12use crate::{13	arr::ArrValue,14	destructure::evaluate_dest,15	error::ErrorKind::*,16	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},17	function::{CallLocation, FuncDesc, FuncVal},18	throw,19	typed::Typed,20	val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},21	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,22	Unbound, Val,23};24pub mod destructure;25pub mod operator;2627pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {28	fn is_trivial(expr: &LocExpr) -> bool {29		match &*expr.0 {30			Expr::Str(_)31			| Expr::Num(_)32			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,33			Expr::Arr(a) => a.iter().all(is_trivial),34			Expr::Parened(e) => is_trivial(e),35			_ => false,36		}37	}38	Some(match &*expr.0 {39		Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),40		Expr::Num(n) => Val::Num(*n),41		Expr::Literal(LiteralType::False) => Val::Bool(false),42		Expr::Literal(LiteralType::True) => Val::Bool(true),43		Expr::Literal(LiteralType::Null) => Val::Null,44		Expr::Arr(n) => {45			if n.iter().any(|e| !is_trivial(e)) {46				return None;47			}48			Val::Arr(ArrValue::eager(49				n.iter()50					.map(evaluate_trivial)51					.map(|e| e.expect("checked trivial"))52					.collect(),53			))54		}55		Expr::Parened(e) => evaluate_trivial(e)?,56		_ => return None,57	})58}5960pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {61	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {62		name,63		ctx,64		params,65		body,66	})))67}6869pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {70	Ok(match field_name {71		FieldName::Fixed(n) => Some(n.clone()),72		FieldName::Dyn(expr) => State::push(73			CallLocation::new(&expr.1),74			|| "evaluating field name".to_string(),75			|| {76				let value = evaluate(ctx, expr)?;77				if matches!(value, Val::Null) {78					Ok(None)79				} else {80					Ok(Some(IStr::from_untyped(value)?))81				}82			},83		)?,84	})85}8687pub fn evaluate_comp(88	ctx: Context,89	specs: &[CompSpec],90	callback: &mut impl FnMut(Context) -> Result<()>,91) -> Result<()> {92	match specs.get(0) {93		None => callback(ctx)?,94		Some(CompSpec::IfSpec(IfSpecData(cond))) => {95			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {96				evaluate_comp(ctx, &specs[1..], callback)?;97			}98		}99		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {100			Val::Arr(list) => {101				for item in list.iter_lazy() {102					let fctx = Pending::new();103					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());104					destruct(var, item, fctx.clone(), &mut new_bindings)?;105					let ctx = ctx106						.clone()107						.extend(new_bindings, None, None, None)108						.into_future(fctx);109110					evaluate_comp(ctx, &specs[1..], callback)?;111				}112			}113			#[cfg(feature = "exp-object-iteration")]114			Val::Obj(obj) => {115				for field in obj.fields(116					// TODO: Should there be ability to preserve iteration order?117					#[cfg(feature = "exp-preserve-order")]118					false,119				) {120					#[derive(Trace)]121					struct ObjectFieldThunk {122						obj: ObjValue,123						field: IStr,124					}125					impl ThunkValue for ObjectFieldThunk {126						type Output = Val;127128						fn get(self: Box<Self>) -> Result<Self::Output> {129							self.obj.get(self.field).transpose().expect(130								"field exists, as field name was obtained from object.fields()",131							)132						}133					}134135					let fctx = Pending::new();136					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());137					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(Cc::new(vec![138						Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),139						Thunk::new(ObjectFieldThunk {140							field: field.clone(),141							obj: obj.clone(),142						}),143					]))));144					destruct(var, value, fctx.clone(), &mut new_bindings)?;145					let ctx = ctx146						.clone()147						.extend(new_bindings, None, None, None)148						.into_future(fctx);149150					evaluate_comp(ctx, &specs[1..], callback)?;151				}152			}153			_ => throw!(InComprehensionCanOnlyIterateOverArray),154		},155	}156	Ok(())157}158159trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}160impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}161162fn evaluate_object_locals(163	fctx: Pending<Context>,164	locals: Rc<Vec<BindSpec>>,165) -> impl CloneableUnbound<Context> {166	#[derive(Trace, Clone)]167	struct UnboundLocals {168		fctx: Pending<Context>,169		locals: Rc<Vec<BindSpec>>,170	}171	impl Unbound for UnboundLocals {172		type Bound = Context;173174		fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {175			let fctx = Context::new_future();176			let mut new_bindings =177				GcHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());178			for b in self.locals.iter() {179				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;180			}181182			let ctx = self.fctx.unwrap();183			let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());184185			let ctx = ctx186				.extend(new_bindings, new_dollar, sup, this)187				.into_future(fctx);188189			Ok(ctx)190		}191	}192193	UnboundLocals { fctx, locals }194}195196pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(197	builder: &mut ObjValueBuilder,198	ctx: Context,199	uctx: B,200	field: &FieldMember,201) -> Result<()> {202	let name = evaluate_field_name(ctx, &field.name)?;203	let Some(name) = name else {204		return Ok(());205	};206207	match field {208		FieldMember {209			plus,210			params: None,211			visibility,212			value,213			..214		} => {215			#[derive(Trace)]216			struct UnboundValue<B: Trace> {217				uctx: B,218				value: LocExpr,219				name: IStr,220			}221			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {222				type Bound = Val;223				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {224					evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())225				}226			}227228			builder229				.member(name.clone())230				.with_add(*plus)231				.with_visibility(*visibility)232				.with_location(value.1.clone())233				.bindable(UnboundValue {234					uctx,235					value: value.clone(),236					name,237				})?;238		}239		FieldMember {240			params: Some(params),241			visibility,242			value,243			..244		} => {245			#[derive(Trace)]246			struct UnboundMethod<B: Trace> {247				uctx: B,248				value: LocExpr,249				params: ParamsDesc,250				name: IStr,251			}252			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {253				type Bound = Val;254				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {255					Ok(evaluate_method(256						self.uctx.bind(sup, this)?,257						self.name.clone(),258						self.params.clone(),259						self.value.clone(),260					))261				}262			}263264			builder265				.member(name.clone())266				.with_visibility(*visibility)267				.with_location(value.1.clone())268				.bindable(UnboundMethod {269					uctx,270					value: value.clone(),271					params: params.clone(),272					name,273				})?;274		}275	}276	Ok(())277}278279#[allow(clippy::too_many_lines)]280pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {281	let mut builder = ObjValueBuilder::new();282	let locals = Rc::new(283		members284			.iter()285			.filter_map(|m| match m {286				Member::BindStmt(bind) => Some(bind.clone()),287				_ => None,288			})289			.collect::<Vec<_>>(),290	);291292	let fctx = Context::new_future();293294	// We have single context for all fields, so we can cache binds295	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));296297	for member in members.iter() {298		match member {299			Member::Field(field) => {300				evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;301			}302			Member::AssertStmt(stmt) => {303				#[derive(Trace)]304				struct ObjectAssert<B: Trace> {305					uctx: B,306					assert: AssertStmt,307				}308				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {309					fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {310						let ctx = self.uctx.bind(sup, this)?;311						evaluate_assert(ctx, &self.assert)312					}313				}314				builder.assert(ObjectAssert {315					uctx: uctx.clone(),316					assert: stmt.clone(),317				});318			}319			Member::BindStmt(_) => {320				// Already handled321			}322		}323	}324	let this = builder.build();325	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));326	Ok(this)327}328329pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {330	Ok(match object {331		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,332		ObjBody::ObjComp(obj) => {333			let mut builder = ObjValueBuilder::new();334			let locals = Rc::new(335				obj.pre_locals336					.iter()337					.chain(obj.post_locals.iter())338					.cloned()339					.collect::<Vec<_>>(),340			);341			let mut ctxs = vec![];342			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {343				let fctx = Context::new_future();344				ctxs.push((ctx.clone(), fctx.clone()));345				let uctx = evaluate_object_locals(fctx, locals.clone());346347				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)348			})?;349350			let this = builder.build();351			for (ctx, fctx) in ctxs {352				let _ctx = ctx353					.extend(GcHashMap::new(), None, None, Some(this.clone()))354					.into_future(fctx);355			}356			this357		}358	})359}360361pub fn evaluate_apply(362	ctx: Context,363	value: &LocExpr,364	args: &ArgsDesc,365	loc: CallLocation<'_>,366	tailstrict: bool,367) -> Result<Val> {368	let value = evaluate(ctx.clone(), value)?;369	Ok(match value {370		Val::Func(f) => {371			let body = || f.evaluate(ctx, loc, args, tailstrict);372			if tailstrict {373				body()?374			} else {375				State::push(loc, || format!("function <{}> call", f.name()), body)?376			}377		}378		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),379	})380}381382pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {383	let value = &assertion.0;384	let msg = &assertion.1;385	let assertion_result = State::push(386		CallLocation::new(&value.1),387		|| "assertion condition".to_owned(),388		|| bool::from_untyped(evaluate(ctx.clone(), value)?),389	)?;390	if !assertion_result {391		State::push(392			CallLocation::new(&value.1),393			|| "assertion failure".to_owned(),394			|| {395				if let Some(msg) = msg {396					throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));397				}398				throw!(AssertionFailed(Val::Null.to_string()?));399			},400		)?;401	}402	Ok(())403}404405pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {406	use Expr::*;407	let LocExpr(raw_expr, _loc) = expr;408	Ok(match &**raw_expr {409		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),410		_ => evaluate(ctx, expr)?,411	})412}413414#[allow(clippy::too_many_lines)]415pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {416	use Expr::*;417	if let Some(trivial) = evaluate_trivial(expr) {418		return Ok(trivial);419	}420	let LocExpr(expr, loc) = expr;421	Ok(match &**expr {422		Literal(LiteralType::This) => {423			Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())424		}425		Literal(LiteralType::Super) => Val::Obj(426			ctx.super_obj().ok_or(NoSuperFound)?.with_this(427				ctx.this()428					.expect("if super exists - then this should too")429					.clone(),430			),431		),432		Literal(LiteralType::Dollar) => {433			Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())434		}435		Literal(LiteralType::True) => Val::Bool(true),436		Literal(LiteralType::False) => Val::Bool(false),437		Literal(LiteralType::Null) => Val::Null,438		Parened(e) => evaluate(ctx, e)?,439		Str(v) => Val::Str(StrValue::Flat(v.clone())),440		Num(v) => Val::new_checked_num(*v)?,441		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,442		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,443		Var(name) => State::push(444			CallLocation::new(loc),445			|| format!("variable <{name}> access"),446			|| ctx.binding(name.clone())?.evaluate(),447		)?,448		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {449			let name = evaluate(ctx.clone(), index)?;450			let Val::Str(name) = name else {451				throw!(ValueIndexMustBeTypeGot(452					ValType::Obj,453					ValType::Str,454					name.value_type(),455				))456			};457			ctx.super_obj()458				.expect("no super found")459				.get_for(name.into_flat(), ctx.this().expect("no this found").clone())?460				.expect("value not found")461		}462		Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {463			(Val::Obj(v), Val::Str(key)) => State::push(464				CallLocation::new(loc),465				|| format!("field <{key}> access"),466				|| match v.get(key.clone().into_flat()) {467					Ok(Some(v)) => Ok(v),468					#[cfg(not(feature = "friendly-errors"))]469					Ok(None) => throw!(NoSuchField(key.clone(), vec![])),470					#[cfg(feature = "friendly-errors")]471					Ok(None) => {472						let mut heap = Vec::new();473						for field in v.fields_ex(474							true,475							#[cfg(feature = "exp-preserve-order")]476							false,477						) {478							let conf = strsim::jaro_winkler(479								&field as &str,480								&key.clone().into_flat() as &str,481							);482							if conf < 0.8 {483								continue;484							}485							heap.push((conf, field));486						}487						heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));488489						throw!(NoSuchField(490							key.clone().into_flat(),491							heap.into_iter().map(|(_, v)| v).collect()492						))493					}494					Err(e) => Err(e),495				},496			)?,497			(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(498				ValType::Obj,499				ValType::Str,500				n.value_type(),501			)),502503			(Val::Arr(v), Val::Num(n)) => {504				if n.fract() > f64::EPSILON {505					throw!(FractionalIndex)506				}507				v.get(n as usize)?508					.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?509			}510			(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n.into_flat())),511			(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(512				ValType::Arr,513				ValType::Num,514				n.value_type(),515			)),516517			(Val::Str(s), Val::Num(n)) => Val::Str({518				let v: IStr = s519					.clone()520					.into_flat()521					.chars()522					.skip(n as usize)523					.take(1)524					.collect::<String>()525					.into();526				if v.is_empty() {527					let size = s.into_flat().chars().count();528					throw!(StringBoundsError(n as usize, size))529				}530				StrValue::Flat(v)531			}),532			(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(533				ValType::Str,534				ValType::Num,535				n.value_type(),536			)),537538			(v, _) => throw!(CantIndexInto(v.value_type())),539		},540		LocalExpr(bindings, returned) => {541			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =542				GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());543			let fctx = Context::new_future();544			for b in bindings {545				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;546			}547			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);548			evaluate(ctx, &returned.clone())?549		}550		Arr(items) => {551			if items.is_empty() {552				Val::Arr(ArrValue::empty())553			} else if items.len() == 1 {554				#[derive(Trace)]555				struct ArrayElement {556					ctx: Context,557					item: LocExpr,558				}559				impl ThunkValue for ArrayElement {560					type Output = Val;561					fn get(self: Box<Self>) -> Result<Val> {562						evaluate(self.ctx, &self.item)563					}564				}565				Val::Arr(ArrValue::lazy(Cc::new(vec![Thunk::new(ArrayElement {566					ctx,567					item: items[0].clone(),568				})])))569			} else {570				Val::Arr(ArrValue::expr(ctx, items.iter().cloned()))571			}572		}573		ArrComp(expr, comp_specs) => {574			let mut out = Vec::new();575			evaluate_comp(ctx, comp_specs, &mut |ctx| {576				out.push(evaluate(ctx, expr)?);577				Ok(())578			})?;579			Val::Arr(ArrValue::eager(out))580		}581		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),582		ObjExtend(a, b) => evaluate_add_op(583			&evaluate(ctx.clone(), a)?,584			&Val::Obj(evaluate_object(ctx, b)?),585		)?,586		Apply(value, args, tailstrict) => {587			evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?588		}589		Function(params, body) => {590			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())591		}592		AssertExpr(assert, returned) => {593			evaluate_assert(ctx.clone(), assert)?;594			evaluate(ctx, returned)?595		}596		ErrorStmt(e) => State::push(597			CallLocation::new(loc),598			|| "error statement".to_owned(),599			|| throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),600		)?,601		IfElse {602			cond,603			cond_then,604			cond_else,605		} => {606			if State::push(607				CallLocation::new(loc),608				|| "if condition".to_owned(),609				|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),610			)? {611				evaluate(ctx, cond_then)?612			} else {613				match cond_else {614					Some(v) => evaluate(ctx, v)?,615					None => Val::Null,616				}617			}618		}619		Slice(value, desc) => {620			fn parse_idx<T: Typed>(621				loc: CallLocation<'_>,622				ctx: &Context,623				expr: Option<&LocExpr>,624				desc: &'static str,625			) -> Result<Option<T>> {626				if let Some(value) = expr {627					Ok(Some(State::push(628						loc,629						|| format!("slice {desc}"),630						|| T::from_untyped(evaluate(ctx.clone(), value)?),631					)?))632				} else {633					Ok(None)634				}635			}636637			let indexable = evaluate(ctx.clone(), value)?;638			let loc = CallLocation::new(loc);639640			let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;641			let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;642			let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;643644			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?645		}646		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {647			let Expr::Str(path) = &*path.0 else {648				throw!("computed imports are not supported")649			};650			let tmp = loc.clone().0;651			let s = ctx.state();652			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;653			match i {654				Import(_) => State::push(655					CallLocation::new(loc),656					|| format!("import {:?}", path.clone()),657					|| s.import_resolved(resolved_path),658				)?,659				ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),660				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),661				_ => unreachable!(),662			}663		}664	})665}
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -7,7 +7,6 @@
 	error::Result,
 	evaluate,
 	gc::GcHashMap,
-	tb,
 	typed::Typed,
 	val::{StrValue, ThunkValue},
 	Context, Thunk, Val,
@@ -37,10 +36,10 @@
 		Ok(if tailstrict {
 			Thunk::evaluated(evaluate(ctx, self)?)
 		} else {
-			Thunk::new(tb!(EvaluateThunk {
+			Thunk::new(EvaluateThunk {
 				ctx,
 				expr: (*self).clone(),
-			}))
+			})
 		})
 	}
 }
@@ -69,10 +68,10 @@
 			TlaArg::Code(code) => Ok(if tailstrict {
 				Thunk::evaluated(evaluate(ctx, code)?)
 			} else {
-				Thunk::new(tb!(EvaluateThunk {
+				Thunk::new(EvaluateThunk {
 					ctx,
 					expr: code.clone(),
-				}))
+				})
 			}),
 			TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),
 		}
@@ -128,7 +127,6 @@
 	}
 	fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
 }
-impl OptionalContext for Vec<Val> {}
 
 impl ArgsLike for ArgsDesc {
 	fn unnamed_len(&self) -> usize {
@@ -147,10 +145,10 @@
 				if tailstrict {
 					Thunk::evaluated(evaluate(ctx.clone(), arg)?)
 				} else {
-					Thunk::new(tb!(EvaluateThunk {
+					Thunk::new(EvaluateThunk {
 						ctx: ctx.clone(),
 						expr: arg.clone(),
-					}))
+					})
 				},
 			)?;
 		}
@@ -169,10 +167,10 @@
 				if tailstrict {
 					Thunk::evaluated(evaluate(ctx.clone(), arg)?)
 				} else {
-					Thunk::new(tb!(EvaluateThunk {
+					Thunk::new(EvaluateThunk {
 						ctx: ctx.clone(),
 						expr: arg.clone(),
-					}))
+					})
 				},
 			)?;
 		}
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -3,7 +3,7 @@
 use jrsonnet_gcmodule::Trace;
 
 use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
-use crate::{error::Result, gc::TraceBox, Context, Val};
+use crate::{error::Result, gc::TraceBox, tb, Context, Val};
 
 pub type BuiltinParamName = Cow<'static, str>;
 
@@ -42,10 +42,7 @@
 }
 impl NativeCallback {
 	#[deprecated = "prefer using builtins directly, use this interface only for bindings"]
-	pub fn new(
-		params: Vec<Cow<'static, str>>,
-		handler: TraceBox<dyn NativeCallbackHandler>,
-	) -> Self {
+	pub fn new(params: Vec<Cow<'static, str>>, handler: impl NativeCallbackHandler) -> Self {
 		Self {
 			params: params
 				.into_iter()
@@ -54,7 +51,7 @@
 					has_default: false,
 				})
 				.collect(),
-			handler,
+			handler: tb!(handler),
 		}
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -12,9 +12,7 @@
 	native::NativeDesc,
 	parse::{parse_default_function_call, parse_function_call},
 };
-use crate::{
-	evaluate, evaluate_trivial, gc::TraceBox, typed::Any, Context, ContextBuilder, Result, Val,
-};
+use crate::{evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result, Val};
 
 pub mod arglike;
 pub mod builtin;
@@ -116,6 +114,9 @@
 }
 
 impl FuncVal {
+	pub fn builtin(builtin: impl Builtin) -> Self {
+		Self::Builtin(Cc::new(tb!(builtin)))
+	}
 	/// Amount of non-default required arguments
 	pub fn params_len(&self) -> usize {
 		match self {
@@ -148,8 +149,8 @@
 			Self::Id => {
 				#[allow(clippy::unnecessary_wraps)]
 				#[builtin]
-				const fn builtin_id(v: Any) -> Result<Any> {
-					Ok(v)
+				const fn builtin_id(x: Val) -> Val {
+					x
 				}
 				static ID: &builtin_id = &builtin_id {};
 
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -10,7 +10,7 @@
 	error::{ErrorKind::*, Result},
 	evaluate_named,
 	gc::GcHashMap,
-	tb, throw,
+	throw,
 	val::ThunkValue,
 	Context, Pending, Thunk, Val,
 };
@@ -100,11 +100,11 @@
 
 			destruct(
 				&param.0,
-				Thunk::new(tb!(EvaluateNamedThunk {
+				Thunk::new(EvaluateNamedThunk {
 					ctx: fctx.clone(),
 					name: param.0.name().unwrap_or_else(|| "<destruct>".into()),
 					value: param.1.clone().expect("default exists"),
-				})),
+				}),
 				fctx.clone(),
 				&mut defaults,
 			)?;
@@ -250,21 +250,21 @@
 		if let Some(v) = &param.1 {
 			destruct(
 				&param.0.clone(),
-				Thunk::new(tb!(EvaluateNamedThunk {
+				Thunk::new(EvaluateNamedThunk {
 					ctx: fctx.clone(),
 					name: param.0.name().unwrap_or_else(|| "<destruct>".into()),
 					value: v.clone(),
-				})),
+				}),
 				fctx.clone(),
 				&mut bindings,
 			)?;
 		} else {
 			destruct(
 				&param.0,
-				Thunk::new(tb!(DependsOnUnbound(
+				Thunk::new(DependsOnUnbound(
 					param.0.name().unwrap_or_else(|| "<destruct>".into()),
-					params.clone()
-				))),
+					params.clone(),
+				)),
 				fctx.clone(),
 				&mut bindings,
 			)?;
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,5 @@
 use std::borrow::Cow;
 
-use jrsonnet_gcmodule::Cc;
 use serde::{
 	de::Visitor,
 	ser::{Error, SerializeMap, SerializeSeq},
@@ -117,7 +116,7 @@
 					out.push(val);
 				}
 
-				Ok(Val::Arr(ArrValue::eager(Cc::new(out))))
+				Ok(Val::Arr(ArrValue::eager(out)))
 			}
 
 			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -433,10 +433,13 @@
 	pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {
 		Ref::map(self.settings(), |s| &*s.import_resolver)
 	}
-	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {
-		self.settings_mut().import_resolver = TraceBox(resolver);
+	pub fn set_import_resolver(&self, resolver: impl ImportResolver) {
+		self.settings_mut().import_resolver = tb!(resolver);
 	}
 	pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {
 		Ref::map(self.settings(), |s| &*s.context_initializer)
 	}
+	pub fn set_context_initializer(&self, initializer: impl ContextInitializer) {
+		self.settings_mut().context_initializer = tb!(initializer);
+	}
 }
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
 	function::CallLocation,
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
-	throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,
+	tb, throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,
 };
 
 #[cfg(not(feature = "exp-preserve-order"))]
@@ -538,8 +538,8 @@
 		self
 	}
 
-	pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {
-		self.assertions.push(assertion);
+	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {
+		self.assertions.push(tb!(assertion));
 		self
 	}
 	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
@@ -631,8 +631,8 @@
 	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
 		self.binding(MaybeUnbound::Bound(value))
 	}
-	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) -> Result<()> {
-		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)))
+	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
+		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))
 	}
 	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
 		let (receiver, name, member) = self.build_member(binding);
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -29,6 +29,14 @@
 	const TYPE: &'static ComplexValType;
 	fn into_untyped(typed: Self) -> Result<Val>;
 	fn from_untyped(untyped: Val) -> Result<Self>;
+
+	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
+	/// This method returns identity in impl Typed for Result, and should not be overriden
+	#[doc(hidden)]
+	fn into_result(typed: Self) -> Result<Val> {
+		let value = Self::into_untyped(typed)?;
+		Ok(value)
+	}
 }
 
 const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
@@ -238,61 +246,54 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		let mut o = Vec::with_capacity(value.len());
-		for i in value {
-			o.push(T::into_untyped(i)?);
-		}
-		Ok(Val::Arr(o.into()))
+		Ok(Val::Arr(
+			value
+				.into_iter()
+				.map(T::into_untyped)
+				.collect::<Result<ArrValue>>()?,
+		))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
-		<Self as Typed>::TYPE.check(&value)?;
-		match value {
-			Val::Arr(a) => {
-				let mut o = Self::with_capacity(a.len());
-				for i in a.iter() {
-					o.push(T::from_untyped(i?)?);
-				}
-				Ok(o)
-			}
-			_ => unreachable!(),
-		}
+		let Val::Arr(a) = value else {
+			<Self as Typed>::TYPE.check(&value)?;
+			unreachable!("typecheck should fail")
+		};
+		a.iter()
+			.map(|r| r.and_then(T::from_untyped))
+			.collect::<Result<Vec<T>>>()
 	}
 }
 
-/// To be used in Vec<Any>
-/// Regular Val can't be used here, because it has wrong `TryFrom::Error` type
-#[derive(Clone)]
-pub struct Any(pub Val);
-
-impl Typed for Any {
+impl Typed for Val {
 	const TYPE: &'static ComplexValType = &ComplexValType::Any;
 
-	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(value.0)
+	fn into_untyped(typed: Self) -> Result<Val> {
+		Ok(typed)
 	}
-
-	fn from_untyped(value: Val) -> Result<Self> {
-		Ok(Self(value))
+	fn from_untyped(untyped: Val) -> Result<Self> {
+		Ok(untyped)
 	}
 }
 
-/// Specialization, provides faster `TryFrom<VecVal>` for Val
-pub struct VecVal(pub Vec<Val>);
+// Hack
+#[doc(hidden)]
+impl<T> Typed for Result<T>
+where
+	T: Typed,
+{
+	const TYPE: &'static ComplexValType = &ComplexValType::Any;
 
-impl Typed for VecVal {
-	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+	fn into_untyped(_typed: Self) -> Result<Val> {
+		panic!("do not use this conversion")
+	}
 
-	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Arr(ArrValue::eager(Cc::new(value.0))))
+	fn from_untyped(_untyped: Val) -> Result<Self> {
+		panic!("do not use this conversion")
 	}
 
-	fn from_untyped(value: Val) -> Result<Self> {
-		<Self as Typed>::TYPE.check(&value)?;
-		match value {
-			Val::Arr(a) => Ok(Self(a.iter().collect::<Result<Vec<_>>>()?)),
-			_ => unreachable!(),
-		}
+	fn into_result(typed: Self) -> Result<Val> {
+		typed.map(T::into_untyped)?
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -15,7 +15,7 @@
 	function::FuncVal,
 	gc::{GcHashMap, TraceBox},
 	manifest::{ManifestFormat, ToStringFormat},
-	throw,
+	tb, throw,
 	typed::BoundedUsize,
 	ObjValue, Result, Unbound, WeakObjValue,
 };
@@ -41,8 +41,8 @@
 	pub fn evaluated(val: T) -> Self {
 		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))
 	}
-	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))
+	pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))
 	}
 	pub fn errored(e: Error) -> Self {
 		Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -192,38 +192,27 @@
 	item: proc_macro::TokenStream,
 ) -> proc_macro::TokenStream {
 	let attr = parse_macro_input!(attr as BuiltinAttrs);
-	let item: ItemFn = parse_macro_input!(item);
+	let item_fn = item.clone();
+	let item_fn: ItemFn = parse_macro_input!(item_fn);
 
-	match builtin_inner(attr, item) {
+	match builtin_inner(attr, item_fn, item.into()) {
 		Ok(v) => v.into(),
 		Err(e) => e.into_compile_error().into(),
 	}
 }
 
-fn builtin_inner(attr: BuiltinAttrs, fun: ItemFn) -> syn::Result<TokenStream> {
+fn builtin_inner(
+	attr: BuiltinAttrs,
+	fun: ItemFn,
+	item: proc_macro2::TokenStream,
+) -> syn::Result<TokenStream> {
 	let ReturnType::Type(_, result) = &fun.sig.output else {
 		return Err(Error::new(
 			fun.sig.span(),
 			"builtin should return something",
 		))
 	};
-
-	let Some(args) = type_is_path(result, "Result") else {
-		return Err(Error::new(result.span(), "return value should be result"));
 
-	};
-	let PathArguments::AngleBracketed(params) = args else {
-		return Err(Error::new(args.span(), "missing result generic"));
-	};
-	let generic_arg = params.args.iter().next().unwrap();
-	// This argument must be a type:
-	let GenericArgument::Type(result_inner) = generic_arg else {
-		return Err(Error::new(
-			generic_arg.span(),
-			"option generic should be a type",
-		))
-	};
-
 	let name = fun.sig.ident.to_string();
 	let args = fun
 		.sig
@@ -355,7 +344,8 @@
 	};
 
 	Ok(quote! {
-		#fun
+		#item
+
 		#[doc(hidden)]
 		#[allow(non_camel_case_types)]
 		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]
@@ -388,8 +378,7 @@
 					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;
 
 					let result: #result = #name(#(#pass)*);
-					let result = result?;
-					<#result_inner>::into_untyped(result)
+					<_ as Typed>::into_result(result)
 				}
 			}
 		};
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -2,11 +2,10 @@
 	error::{ErrorKind::RuntimeError, Result},
 	function::{builtin, FuncVal},
 	throw,
-	typed::{Any, BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
+	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
 	val::{equals, ArrValue, IndexableVal, StrValue},
 	Either, IStr, Val,
 };
-use jrsonnet_gcmodule::Cc;
 
 #[builtin]
 pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {
@@ -18,21 +17,21 @@
 		for _ in 0..*sz {
 			out.push(trivial.clone())
 		}
-		Ok(ArrValue::eager(Cc::new(out)))
+		Ok(ArrValue::eager(out))
 	} else {
 		Ok(ArrValue::range_exclusive(0, *sz).map(func))
 	}
 }
 
 #[builtin]
-pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Any> {
-	Ok(Any(match what {
+pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {
+	Ok(match what {
 		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()))?,
 		),
-	}))
+	})
 }
 
 #[builtin]
@@ -41,8 +40,8 @@
 	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,
 	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,
 	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,
-) -> Result<Any> {
-	indexable.slice(index, end, step).map(Val::from).map(Any)
+) -> Result<Val> {
+	indexable.slice(index, end, step).map(Val::from)
 }
 
 #[builtin]
@@ -52,7 +51,7 @@
 
 #[builtin]
 pub fn builtin_flatmap(
-	func: NativeFn<((Either![String, Any],), Any)>,
+	func: NativeFn<((Either![String, Val],), Val)>,
 	arr: IndexableVal,
 ) -> Result<IndexableVal> {
 	use std::fmt::Write;
@@ -60,7 +59,7 @@
 		IndexableVal::Str(str) => {
 			let mut out = String::new();
 			for c in str.chars() {
-				match func(Either2::A(c.to_string()))?.0 {
+				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"),
@@ -72,7 +71,7 @@
 			let mut out = Vec::new();
 			for el in a.iter() {
 				let el = el?;
-				match func(Either2::B(Any(el)))?.0 {
+				match func(Either2::B(el))? {
 					Val::Arr(o) => {
 						for oe in o.iter() {
 							out.push(oe?);
@@ -89,25 +88,25 @@
 
 #[builtin]
 pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
-	arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(Any(val.clone()),))?))
+	arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),))?))
 }
 
 #[builtin]
-pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
-	let mut acc = init.0;
+pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {
+	let mut acc = init;
 	for i in arr.iter() {
-		acc = func.evaluate_simple(&(Any(acc), Any(i?)))?;
+		acc = func.evaluate_simple(&(acc, i?))?;
 	}
-	Ok(Any(acc))
+	Ok(acc)
 }
 
 #[builtin]
-pub fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
-	let mut acc = init.0;
+pub fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {
+	let mut acc = init;
 	for i in arr.iter().rev() {
-		acc = func.evaluate_simple(&(Any(i?), Any(acc)))?;
+		acc = func.evaluate_simple(&(i?, acc))?;
 	}
-	Ok(Any(acc))
+	Ok(acc)
 }
 
 #[builtin]
@@ -175,8 +174,8 @@
 }
 
 #[builtin]
-pub fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {
-	Ok(value.reversed())
+pub fn builtin_reverse(arr: ArrValue) -> ArrValue {
+	arr.reversed()
 }
 
 #[builtin]
@@ -202,16 +201,16 @@
 }
 
 #[builtin]
-pub fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {
+pub fn builtin_member(arr: IndexableVal, x: Val) -> Result<bool> {
 	match arr {
 		IndexableVal::Str(str) => {
-			let x: IStr = IStr::from_untyped(x.0)?;
+			let x: IStr = IStr::from_untyped(x)?;
 			Ok(!x.is_empty() && str.contains(&*x))
 		}
 		IndexableVal::Arr(a) => {
 			for item in a.iter() {
 				let item = item?;
-				if equals(&item, &x.0)? {
+				if equals(&item, &x)? {
 					return Ok(true);
 				}
 			}
@@ -221,10 +220,10 @@
 }
 
 #[builtin]
-pub fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {
+pub fn builtin_count(arr: ArrValue, x: Val) -> Result<usize> {
 	let mut count = 0;
-	for item in &arr {
-		if equals(&item.0, &v.0)? {
+	for item in arr.iter() {
+		if equals(&item?, &x)? {
 			count += 1;
 		}
 	}
modifiedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -6,8 +6,8 @@
 };
 
 #[builtin]
-pub fn builtin_encode_utf8(str: IStr) -> Result<IBytes> {
-	Ok(str.cast_bytes())
+pub fn builtin_encode_utf8(str: IStr) -> IBytes {
+	str.cast_bytes()
 }
 
 #[builtin]
@@ -18,24 +18,24 @@
 }
 
 #[builtin]
-pub fn builtin_base64(input: Either![IStr, IBytes]) -> Result<String> {
+pub fn builtin_base64(input: Either![IStr, IBytes]) -> String {
 	use Either2::*;
-	Ok(match input {
+	match input {
 		A(l) => base64::encode(l.as_bytes()),
 		B(a) => base64::encode(a.as_slice()),
-	})
+	}
 }
 
 #[builtin]
-pub fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
-	Ok(base64::decode(input.as_bytes())
+pub fn builtin_base64_decode_bytes(str: IStr) -> Result<IBytes> {
+	Ok(base64::decode(str.as_bytes())
 		.map_err(|_| RuntimeError("bad base64".into()))?
 		.as_slice()
 		.into())
 }
 
 #[builtin]
-pub fn builtin_base64_decode(input: IStr) -> Result<String> {
-	let bytes = base64::decode(input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+pub fn builtin_base64_decode(str: IStr) -> Result<String> {
+	let bytes = base64::decode(str.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
 	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
 }
modifiedcrates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -1,13 +1,13 @@
-use jrsonnet_evaluator::{error::Result, function::builtin, IStr};
+use jrsonnet_evaluator::{function::builtin, IStr};
 
 #[builtin]
-pub fn builtin_md5(str: IStr) -> Result<String> {
-	Ok(format!("{:x}", md5::compute(str.as_bytes())))
+pub fn builtin_md5(s: IStr) -> String {
+	format!("{:x}", md5::compute(s.as_bytes()))
 }
 
 #[cfg(feature = "exp-more-hashes")]
 #[builtin]
-pub fn builtin_sha256(str: IStr) -> Result<String> {
+pub fn builtin_sha256(s: IStr) -> String {
 	use sha2::digest::Digest;
-	Ok(format!("{:?}", sha2::Sha256::digest(str.as_bytes())))
+	format!("{:?}", sha2::Sha256::digest(s.as_bytes()))
 }
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -155,23 +155,21 @@
 	builder
 		.member("extVar".into())
 		.hide()
-		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
-			settings: settings.clone()
-		})))))
+		.value(Val::Func(FuncVal::builtin(builtin_ext_var {
+			settings: settings.clone(),
+		})))
 		.expect("no conflict");
 	builder
 		.member("native".into())
 		.hide()
-		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
-			settings: settings.clone()
-		})))))
+		.value(Val::Func(FuncVal::builtin(builtin_native {
+			settings: settings.clone(),
+		})))
 		.expect("no conflict");
 	builder
 		.member("trace".into())
 		.hide()
-		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace {
-			settings
-		})))))
+		.value(Val::Func(FuncVal::builtin(builtin_trace { settings })))
 		.expect("no conflict");
 
 	builder
@@ -301,8 +299,10 @@
 			.insert(name.into(), TlaArg::Code(parsed));
 		Ok(())
 	}
-	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {
-		self.settings_mut().ext_natives.insert(name, cb);
+	pub fn add_native(&self, name: IStr, cb: impl Builtin) {
+		self.settings_mut()
+			.ext_natives
+			.insert(name, Cc::new(tb!(cb)));
 	}
 }
 impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
modifiedcrates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/mod.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -5,7 +5,6 @@
 	error::Result,
 	function::builtin,
 	manifest::{escape_string_json, JsonFormat},
-	typed::Any,
 	IStr, ObjValue, Val,
 };
 pub use toml::TomlFormat;
@@ -18,7 +17,7 @@
 
 #[builtin]
 pub fn builtin_manifest_json_ex(
-	value: Any,
+	value: Val,
 	indent: IStr,
 	newline: Option<IStr>,
 	key_val_sep: Option<IStr>,
@@ -26,7 +25,7 @@
 ) -> Result<String> {
 	let newline = newline.as_deref().unwrap_or("\n");
 	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
-	value.0.manifest(JsonFormat::std_to_json(
+	value.manifest(JsonFormat::std_to_json(
 		indent.to_string(),
 		newline,
 		key_val_sep,
@@ -37,12 +36,12 @@
 
 #[builtin]
 pub fn builtin_manifest_yaml_doc(
-	value: Any,
+	value: Val,
 	indent_array_in_object: Option<bool>,
 	quote_keys: Option<bool>,
 	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
 ) -> Result<String> {
-	value.0.manifest(YamlFormat::std_to_yaml(
+	value.manifest(YamlFormat::std_to_yaml(
 		indent_array_in_object.unwrap_or(false),
 		quote_keys.unwrap_or(true),
 		#[cfg(feature = "exp-preserve-order")]
modifiedcrates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/math.rs
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -1,88 +1,92 @@
-use jrsonnet_evaluator::{error::Result, function::builtin, typed::PositiveF64};
+use jrsonnet_evaluator::{function::builtin, typed::PositiveF64};
 
 #[builtin]
-pub fn builtin_abs(n: f64) -> Result<f64> {
-	Ok(n.abs())
+pub fn builtin_abs(n: f64) -> f64 {
+	n.abs()
 }
 
 #[builtin]
-pub fn builtin_sign(n: f64) -> Result<f64> {
-	Ok(if n == 0. { 0. } else { n.signum() })
+pub fn builtin_sign(n: f64) -> f64 {
+	if n == 0. {
+		0.
+	} else {
+		n.signum()
+	}
 }
 
 #[builtin]
-pub fn builtin_max(a: f64, b: f64) -> Result<f64> {
-	Ok(a.max(b))
+pub fn builtin_max(a: f64, b: f64) -> f64 {
+	a.max(b)
 }
 
 #[builtin]
-pub fn builtin_min(a: f64, b: f64) -> Result<f64> {
-	Ok(a.min(b))
+pub fn builtin_min(a: f64, b: f64) -> f64 {
+	a.min(b)
 }
 
 #[builtin]
-pub fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
-	Ok(a % b)
+pub fn builtin_modulo(x: f64, y: f64) -> f64 {
+	x % y
 }
 
 #[builtin]
-pub fn builtin_floor(x: f64) -> Result<f64> {
-	Ok(x.floor())
+pub fn builtin_floor(x: f64) -> f64 {
+	x.floor()
 }
 
 #[builtin]
-pub fn builtin_ceil(x: f64) -> Result<f64> {
-	Ok(x.ceil())
+pub fn builtin_ceil(x: f64) -> f64 {
+	x.ceil()
 }
 
 #[builtin]
-pub fn builtin_log(n: f64) -> Result<f64> {
-	Ok(n.ln())
+pub fn builtin_log(x: f64) -> f64 {
+	x.ln()
 }
 
 #[builtin]
-pub fn builtin_pow(x: f64, n: f64) -> Result<f64> {
-	Ok(x.powf(n))
+pub fn builtin_pow(x: f64, n: f64) -> f64 {
+	x.powf(n)
 }
 
 #[builtin]
-pub fn builtin_sqrt(x: PositiveF64) -> Result<f64> {
-	Ok(x.0.sqrt())
+pub fn builtin_sqrt(x: PositiveF64) -> f64 {
+	x.0.sqrt()
 }
 
 #[builtin]
-pub fn builtin_sin(x: f64) -> Result<f64> {
-	Ok(x.sin())
+pub fn builtin_sin(x: f64) -> f64 {
+	x.sin()
 }
 
 #[builtin]
-pub fn builtin_cos(x: f64) -> Result<f64> {
-	Ok(x.cos())
+pub fn builtin_cos(x: f64) -> f64 {
+	x.cos()
 }
 
 #[builtin]
-pub fn builtin_tan(x: f64) -> Result<f64> {
-	Ok(x.tan())
+pub fn builtin_tan(x: f64) -> f64 {
+	x.tan()
 }
 
 #[builtin]
-pub fn builtin_asin(x: f64) -> Result<f64> {
-	Ok(x.asin())
+pub fn builtin_asin(x: f64) -> f64 {
+	x.asin()
 }
 
 #[builtin]
-pub fn builtin_acos(x: f64) -> Result<f64> {
-	Ok(x.acos())
+pub fn builtin_acos(x: f64) -> f64 {
+	x.acos()
 }
 
 #[builtin]
-pub fn builtin_atan(x: f64) -> Result<f64> {
-	Ok(x.atan())
+pub fn builtin_atan(x: f64) -> f64 {
+	x.atan()
 }
 
 #[builtin]
-pub fn builtin_exp(x: f64) -> Result<f64> {
-	Ok(x.exp())
+pub fn builtin_exp(x: f64) -> f64 {
+	x.exp()
 }
 
 fn frexp(s: f64) -> (f64, i16) {
@@ -97,11 +101,11 @@
 }
 
 #[builtin]
-pub fn builtin_mantissa(x: f64) -> Result<f64> {
-	Ok(frexp(x).0)
+pub fn builtin_mantissa(x: f64) -> f64 {
+	frexp(x).0
 }
 
 #[builtin]
-pub fn builtin_exponent(x: f64) -> Result<i16> {
-	Ok(frexp(x).1)
+pub fn builtin_exponent(x: f64) -> i16 {
+	frexp(x).1
 }
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -4,7 +4,7 @@
 	error::{ErrorKind::*, Result},
 	function::{builtin, ArgLike, CallLocation, FuncVal},
 	throw,
-	typed::{Any, Either2, Either4},
+	typed::{Either2, Either4},
 	val::{equals, ArrValue},
 	Context, Either, IStr, ObjValue, Thunk, Val,
 };
@@ -12,45 +12,41 @@
 use crate::{extvar_source, Settings};
 
 #[builtin]
-pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {
+pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> usize {
 	use Either4::*;
-	Ok(match x {
+	match x {
 		A(x) => x.chars().count(),
 		B(x) => x.len(),
 		C(x) => x.len(),
 		D(f) => f.params_len(),
-	})
+	}
 }
 
 #[builtin(fields(
 	settings: Rc<RefCell<Settings>>,
 ))]
-pub fn builtin_ext_var(this: &builtin_ext_var, ctx: Context, x: IStr) -> Result<Any> {
+pub fn builtin_ext_var(this: &builtin_ext_var, ctx: Context, x: IStr) -> Result<Val> {
 	let ctx = ctx.state().create_default_context(extvar_source(&x, ""));
-	Ok(Any(this
-		.settings
+	this.settings
 		.borrow()
 		.ext_vars
 		.get(&x)
 		.cloned()
 		.ok_or_else(|| UndefinedExternalVariable(x))?
 		.evaluate_arg(ctx, true)?
-		.evaluate()?))
+		.evaluate()
 }
 
 #[builtin(fields(
 	settings: Rc<RefCell<Settings>>,
 ))]
-pub fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {
-	Ok(Any(this
-		.settings
+pub fn builtin_native(this: &builtin_native, x: IStr) -> Val {
+	this.settings
 		.borrow()
 		.ext_natives
-		.get(&name)
+		.get(&x)
 		.cloned()
-		.map_or(Val::Null, |v| {
-			Val::Func(FuncVal::Builtin(v.clone()))
-		})))
+		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v.clone())))
 }
 
 #[builtin(fields(
@@ -61,9 +57,9 @@
 	loc: CallLocation,
 	str: IStr,
 	rest: Thunk<Val>,
-) -> Result<Any> {
+) -> Result<Val> {
 	this.settings.borrow().trace_printer.print_trace(loc, str);
-	Ok(Any(rest.evaluate()?))
+	rest.evaluate()
 }
 
 #[allow(clippy::comparison_chain)]
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,7 +1,5 @@
 use jrsonnet_evaluator::{
-	error::Result,
 	function::builtin,
-	typed::VecVal,
 	val::{StrValue, Val},
 	IStr, ObjValue,
 };
@@ -9,25 +7,23 @@
 #[builtin]
 pub fn builtin_object_fields_ex(
 	obj: ObjValue,
-	inc_hidden: bool,
+	hidden: bool,
 	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
-) -> Result<VecVal> {
+) -> Vec<Val> {
 	#[cfg(feature = "exp-preserve-order")]
 	let preserve_order = preserve_order.unwrap_or(false);
 	let out = obj.fields_ex(
-		inc_hidden,
+		hidden,
 		#[cfg(feature = "exp-preserve-order")]
 		preserve_order,
 	);
-	Ok(VecVal(
-		out.into_iter()
-			.map(StrValue::Flat)
-			.map(Val::Str)
-			.collect::<Vec<_>>(),
-	))
+	out.into_iter()
+		.map(StrValue::Flat)
+		.map(Val::Str)
+		.collect::<Vec<_>>()
 }
 
 #[builtin]
-pub fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {
-	Ok(obj.has_field_ex(f, inc_hidden))
+pub fn builtin_object_has_ex(obj: ObjValue, fname: IStr, hidden: bool) -> bool {
+	obj.has_field_ex(fname, hidden)
 }
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -6,34 +6,34 @@
 	function::builtin,
 	operator::evaluate_mod_op,
 	stdlib::std_format,
-	typed::{Any, Either, Either2},
+	typed::{Either, Either2},
 	val::{equals, primitive_equals, StrValue},
 	IStr, Val,
 };
 
 #[builtin]
-pub fn builtin_mod(a: Either![f64, IStr], b: Any) -> Result<Any> {
+pub fn builtin_mod(a: Either![f64, IStr], b: Val) -> Result<Val> {
 	use Either2::*;
-	Ok(Any(evaluate_mod_op(
+	evaluate_mod_op(
 		&match a {
 			A(v) => Val::Num(v),
 			B(s) => Val::Str(StrValue::Flat(s)),
 		},
-		&b.0,
-	)?))
+		&b,
+	)
 }
 
 #[builtin]
-pub fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {
-	primitive_equals(&a.0, &b.0)
+pub fn builtin_primitive_equals(x: Val, y: Val) -> Result<bool> {
+	primitive_equals(&x, &y)
 }
 
 #[builtin]
-pub fn builtin_equals(a: Any, b: Any) -> Result<bool> {
-	equals(&a.0, &b.0)
+pub fn builtin_equals(a: Val, b: Val) -> Result<bool> {
+	equals(&a, &b)
 }
 
 #[builtin]
-pub fn builtin_format(str: IStr, vals: Any) -> Result<String> {
-	std_format(&str, vals.0)
+pub fn builtin_format(str: IStr, vals: Val) -> Result<String> {
+	std_format(&str, vals)
 }
modifiedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -1,23 +1,22 @@
 use jrsonnet_evaluator::{
 	error::{ErrorKind::RuntimeError, Result},
 	function::builtin,
-	typed::Any,
 	IStr, Val,
 };
 use serde::Deserialize;
 
 #[builtin]
-pub fn builtin_parse_json(s: IStr) -> Result<Any> {
-	let value: Val = serde_json::from_str(&s)
+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()))?;
-	Ok(Any(value))
+	Ok(value)
 }
 
 #[builtin]
-pub fn builtin_parse_yaml(s: IStr) -> Result<Any> {
+pub fn builtin_parse_yaml(str: IStr) -> Result<Val> {
 	use serde_yaml_with_quirks::DeserializingQuirks;
 	let value = serde_yaml_with_quirks::Deserializer::from_str_with_quirks(
-		&s,
+		&str,
 		DeserializingQuirks { old_octals: true },
 	);
 	let mut out = vec![];
@@ -26,11 +25,11 @@
 			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
 		out.push(val);
 	}
-	Ok(Any(if out.is_empty() {
+	Ok(if out.is_empty() {
 		Val::Null
 	} else if out.len() == 1 {
 		out.into_iter().next().unwrap()
 	} else {
 		Val::Arr(out.into())
-	}))
+	})
 }
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -2,11 +2,9 @@
 	error::Result,
 	function::{builtin, CallLocation, FuncVal},
 	throw,
-	typed::Any,
 	val::ArrValue,
 	Context, Val,
 };
-use jrsonnet_gcmodule::Cc;
 
 #[derive(Copy, Clone)]
 enum SortKeyType {
@@ -78,7 +76,7 @@
 				key_getter.evaluate(
 					ctx.clone(),
 					CallLocation::native(),
-					&(Any(value.clone()),),
+					&(value.clone(),),
 					true,
 				)?,
 			));
@@ -105,9 +103,9 @@
 	if arr.len() <= 1 {
 		return Ok(arr);
 	}
-	Ok(ArrValue::eager(Cc::new(super::sort::sort(
+	Ok(ArrValue::eager(super::sort::sort(
 		ctx,
 		arr.iter().collect::<Result<Vec<_>>>()?,
 		keyF.unwrap_or_else(FuncVal::identity),
-	)?)))
+	)?))
 }
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -2,19 +2,19 @@
 	error::{ErrorKind::*, Result},
 	function::builtin,
 	throw,
-	typed::{Either2, VecVal, M1},
+	typed::{Either2, M1},
 	val::{ArrValue, StrValue},
 	Either, IStr, Val,
 };
 
 #[builtin]
-pub const fn builtin_codepoint(str: char) -> Result<u32> {
-	Ok(str as u32)
+pub const fn builtin_codepoint(str: char) -> u32 {
+	str as u32
 }
 
 #[builtin]
-pub fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
-	Ok(str.chars().skip(from).take(len).collect())
+pub fn builtin_substr(str: IStr, from: usize, len: usize) -> String {
+	str.chars().skip(from).take(len).collect()
 }
 
 #[builtin]
@@ -23,14 +23,14 @@
 }
 
 #[builtin]
-pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
-	Ok(str.replace(&from as &str, &to as &str))
+pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> String {
+	str.replace(&from as &str, &to as &str)
 }
 
 #[builtin]
-pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {
+pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {
 	use Either2::*;
-	Ok(VecVal(match maxsplits {
+	match maxsplits {
 		A(n) => str
 			.splitn(n + 1, &c as &str)
 			.map(|s| Val::Str(StrValue::Flat(s.into())))
@@ -39,23 +39,23 @@
 			.split(&c as &str)
 			.map(|s| Val::Str(StrValue::Flat(s.into())))
 			.collect(),
-	}))
+	}
 }
 
 #[builtin]
-pub fn builtin_ascii_upper(str: IStr) -> Result<String> {
-	Ok(str.to_ascii_uppercase())
+pub fn builtin_ascii_upper(str: IStr) -> String {
+	str.to_ascii_uppercase()
 }
 
 #[builtin]
-pub fn builtin_ascii_lower(str: IStr) -> Result<String> {
-	Ok(str.to_ascii_lowercase())
+pub fn builtin_ascii_lower(str: IStr) -> String {
+	str.to_ascii_lowercase()
 }
 
 #[builtin]
-pub fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {
+pub fn builtin_find_substr(pat: IStr, str: IStr) -> ArrValue {
 	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {
-		return Ok(ArrValue::empty());
+		return ArrValue::empty();
 	}
 
 	let str = str.as_str();
@@ -74,7 +74,7 @@
 			out.push(Val::Num(ch_idx as f64))
 		}
 	}
-	Ok(out.into())
+	out.into()
 }
 
 #[builtin]
modifiedcrates/jrsonnet-stdlib/src/types.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/types.rs
+++ b/crates/jrsonnet-stdlib/src/types.rs
@@ -1,31 +1,31 @@
-use jrsonnet_evaluator::{error::Result, function::builtin, typed::Any, IStr, Val};
+use jrsonnet_evaluator::{function::builtin, IStr, Val};
 
 #[builtin]
-pub fn builtin_type(v: Any) -> Result<IStr> {
-	Ok(v.0.value_type().name().into())
+pub fn builtin_type(x: Val) -> IStr {
+	x.value_type().name().into()
 }
 
 #[builtin]
-pub fn builtin_is_string(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Str(_)))
+pub fn builtin_is_string(v: Val) -> bool {
+	matches!(v, Val::Str(_))
 }
 #[builtin]
-pub fn builtin_is_number(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Num(_)))
+pub fn builtin_is_number(v: Val) -> bool {
+	matches!(v, Val::Num(_))
 }
 #[builtin]
-pub fn builtin_is_boolean(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Bool(_)))
+pub fn builtin_is_boolean(v: Val) -> bool {
+	matches!(v, Val::Bool(_))
 }
 #[builtin]
-pub fn builtin_is_object(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Obj(_)))
+pub fn builtin_is_object(v: Val) -> bool {
+	matches!(v, Val::Obj(_))
 }
 #[builtin]
-pub fn builtin_is_array(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Arr(_)))
+pub fn builtin_is_array(v: Val) -> bool {
+	matches!(v, Val::Arr(_))
 }
 #[builtin]
-pub fn builtin_is_function(v: Any) -> Result<bool> {
-	Ok(matches!(v.0, Val::Func(_)))
+pub fn builtin_is_function(v: Val) -> bool {
+	matches!(v, Val::Func(_))
 }
modifiedtests/tests/builtin.rsdiffbeforeafterboth
--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -3,11 +3,9 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, builtin::Builtin, CallLocation, FuncVal},
-	tb,
 	typed::Typed,
 	ContextBuilder, State, Thunk, Val,
 };
-use jrsonnet_gcmodule::Cc;
 use jrsonnet_stdlib::StateExt;
 
 #[builtin]
@@ -63,7 +61,7 @@
 
 #[builtin]
 fn curry_add(a: u32) -> Result<FuncVal> {
-	Ok(FuncVal::Builtin(Cc::new(tb!(curried_add { a }))))
+	Ok(FuncVal::builtin(curried_add { a }))
 }
 
 #[test]
modifiedtests/tests/common.rsdiffbeforeafterboth
--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,3 +1,5 @@
+use std::borrow::Cow;
+
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, FuncVal},
@@ -53,13 +55,47 @@
 	Ok(true)
 }
 
+#[builtin]
+fn param_names(fun: FuncVal) -> Vec<String> {
+	match fun {
+		FuncVal::Id => vec!["x".to_string()],
+		FuncVal::Normal(func) => func
+			.params
+			.iter()
+			.map(|p| p.0.name().unwrap_or_else(|| "<unnamed>".into()).to_string())
+			.collect(),
+		FuncVal::StaticBuiltin(b) => b
+			.params()
+			.iter()
+			.map(|p| {
+				p.name
+					.as_ref()
+					.unwrap_or(&Cow::Borrowed("<unnamed>"))
+					.to_string()
+			})
+			.collect(),
+		FuncVal::Builtin(b) => b
+			.params()
+			.iter()
+			.map(|p| {
+				p.name
+					.as_ref()
+					.unwrap_or(&Cow::Borrowed("<unnamed>"))
+					.to_string()
+			})
+			.collect(),
+	}
+}
+
 #[allow(dead_code)]
 pub fn with_test(s: &State) {
 	let mut bobj = ObjValueBuilder::new();
 	bobj.member("assertThrow".into())
 		.hide()
-		.value(Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)))
-		.expect("no error");
+		.value_unchecked(Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)));
+	bobj.member("paramNames".into())
+		.hide()
+		.value_unchecked(Val::Func(FuncVal::StaticBuiltin(param_names::INST)));
 
 	s.add_global("test".into(), Thunk::evaluated(Val::Obj(bobj.build())))
 }
modifiedtests/tests/golden.rsdiffbeforeafterboth
--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -16,7 +16,7 @@
 	let s = State::default();
 	s.with_stdlib();
 	common::with_test(&s);
-	s.set_import_resolver(Box::new(FileImportResolver::default()));
+	s.set_import_resolver(FileImportResolver::default());
 	let trace_format = CompactFormat {
 		resolver: PathResolver::FileName,
 		max_trace: 20,
modifiedtests/tests/suite.rsdiffbeforeafterboth
--- a/tests/tests/suite.rs
+++ b/tests/tests/suite.rs
@@ -15,7 +15,7 @@
 	let s = State::default();
 	s.with_stdlib();
 	common::with_test(&s);
-	s.set_import_resolver(Box::new(FileImportResolver::default()));
+	s.set_import_resolver(FileImportResolver::default());
 	let trace_format = CompactFormat::default();
 
 	match s.import(file) {