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

difftreelog

refactor better rebinding handling

Yaroslav Bolyukin2022-04-24parent: #88a0ba1.patch.diff
in: master

15 files changed

modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,34 +4,15 @@
 use jrsonnet_interner::IStr;
 
 use crate::{
-	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, LazyBinding, ObjValue, Pending,
-	Result, State, Thunk, Val,
+	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result,
+	Thunk, Val,
 };
 
-#[derive(Clone, Trace)]
-pub struct ContextCreator(pub Context, pub Pending<GcHashMap<IStr, LazyBinding>>);
-impl ContextCreator {
-	pub fn create(
-		&self,
-		s: State,
-		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
-	) -> Result<Context> {
-		self.0.clone().extend_unbound(
-			s,
-			self.1.clone().unwrap(),
-			self.0.dollar().clone().or_else(|| this.clone()),
-			this,
-			super_obj,
-		)
-	}
-}
-
 #[derive(Trace)]
 struct ContextInternals {
 	dollar: Option<ObjValue>,
+	sup: Option<ObjValue>,
 	this: Option<ObjValue>,
-	super_obj: Option<ObjValue>,
 	bindings: LayeredHashMap,
 }
 impl Debug for ContextInternals {
@@ -56,14 +37,14 @@
 	}
 
 	pub fn super_obj(&self) -> &Option<ObjValue> {
-		&self.0.super_obj
+		&self.0.sup
 	}
 
 	pub fn new() -> Self {
 		Self(Cc::new(ContextInternals {
 			dollar: None,
 			this: None,
-			super_obj: None,
+			sup: None,
 			bindings: LayeredHashMap::default(),
 		}))
 	}
@@ -92,11 +73,6 @@
 		let mut new_bindings = GcHashMap::with_capacity(1);
 		new_bindings.insert(name, Thunk::evaluated(value));
 		self.extend(new_bindings, None, None, None)
-	}
-
-	#[must_use]
-	pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
-		self.extend(GcHashMap::new(), None, Some(new_this), new_super_obj)
 	}
 
 	#[must_use]
@@ -104,13 +80,13 @@
 		self,
 		new_bindings: GcHashMap<IStr, Thunk<Val>>,
 		new_dollar: Option<ObjValue>,
+		new_sup: Option<ObjValue>,
 		new_this: Option<ObjValue>,
-		new_super_obj: Option<ObjValue>,
 	) -> Self {
 		let ctx = &self.0;
 		let dollar = new_dollar.or_else(|| ctx.dollar.clone());
 		let this = new_this.or_else(|| ctx.this.clone());
-		let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
+		let sup = new_sup.or_else(|| ctx.sup.clone());
 		let bindings = if new_bindings.is_empty() {
 			ctx.bindings.clone()
 		} else {
@@ -118,32 +94,10 @@
 		};
 		Self(Cc::new(ContextInternals {
 			dollar,
+			sup,
 			this,
-			super_obj,
 			bindings,
 		}))
-	}
-	#[must_use]
-	pub fn extend_bound(self, new_bindings: GcHashMap<IStr, Thunk<Val>>) -> Self {
-		let new_this = self.0.this.clone();
-		let new_super_obj = self.0.super_obj.clone();
-		self.extend(new_bindings, None, new_this, new_super_obj)
-	}
-	pub fn extend_unbound(
-		self,
-		s: State,
-		new_bindings: GcHashMap<IStr, LazyBinding>,
-		new_dollar: Option<ObjValue>,
-		new_this: Option<ObjValue>,
-		new_super_obj: Option<ObjValue>,
-	) -> Result<Self> {
-		let this = new_this.or_else(|| self.0.this.clone());
-		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
-		let mut new = GcHashMap::with_capacity(new_bindings.len());
-		for (k, v) in new_bindings.0 {
-			new.insert(k, v.evaluate(s.clone(), this.clone(), super_obj.clone())?);
-		}
-		Ok(self.extend(new, new_dollar, this, super_obj))
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -11,12 +11,13 @@
 	Context, Pending, State, Thunk, Val,
 };
 
+#[allow(clippy::too_many_lines)]
 fn destruct(
 	d: &Destruct,
 	parent: Thunk<Val>,
 	new_bindings: &mut GcHashMap<IStr, Thunk<Val>>,
 ) -> Result<()> {
-	Ok(match d {
+	match d {
 		Destruct::Full(v) => {
 			let old = new_bindings.insert(v.clone(), parent);
 			if old.is_some() {
@@ -157,8 +158,6 @@
 		}
 		#[cfg(feature = "exp-destruct")]
 		Destruct::Object { fields, rest } => {
-			use jrsonnet_parser::DestructRest;
-
 			use crate::{obj::ObjValue, throw_runtime};
 
 			#[derive(Trace)]
@@ -223,7 +222,8 @@
 				}
 			}
 		}
-	})
+	}
+	Ok(())
 }
 
 pub fn evaluate_dest(
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,7 +1,9 @@
+use std::rc::Rc;
+
 use gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
-	ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, ForSpecData, IfSpecData,
+	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,
 	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
 };
 use jrsonnet_types::ValType;
@@ -14,147 +16,13 @@
 	stdlib::{std_slice, BUILTINS},
 	tb, throw,
 	typed::Typed,
-	val::{ArrValue, Thunk, ThunkValue},
-	Bindable, Context, ContextCreator, GcHashMap, LazyBinding, ObjValue, ObjValueBuilder,
-	ObjectAssertion, Pending, Result, State, Val,
+	val::{ArrValue, CachedBindable, Thunk, ThunkValue},
+	Bindable, Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+	State, Val,
 };
 pub mod destructure;
 pub mod operator;
-
-#[allow(clippy::too_many_lines)]
-pub fn evaluate_binding(b: BindSpec, cctx: ContextCreator) -> Result<(IStr, LazyBinding)> {
-	match b {
-		BindSpec::Field {
-			into: Destruct::Full(name),
-			value,
-		} => {
-			#[derive(Trace)]
-			struct BindableNamedThunk {
-				this: Option<ObjValue>,
-				super_obj: Option<ObjValue>,
-
-				cctx: ContextCreator,
-				name: IStr,
-				value: LocExpr,
-			}
-			impl ThunkValue for BindableNamedThunk {
-				type Output = Val;
-				fn get(self: Box<Self>, s: State) -> Result<Val> {
-					evaluate_named(
-						s.clone(),
-						self.cctx.create(s, self.this, self.super_obj)?,
-						&self.value,
-						self.name,
-					)
-				}
-			}
-
-			#[derive(Trace)]
-			struct BindableNamed {
-				cctx: ContextCreator,
-				name: IStr,
-				value: LocExpr,
-			}
-			impl Bindable for BindableNamed {
-				fn bind(
-					&self,
-					_: State,
-					this: Option<ObjValue>,
-					super_obj: Option<ObjValue>,
-				) -> Result<Thunk<Val>> {
-					Ok(Thunk::new(tb!(BindableNamedThunk {
-						this,
-						super_obj,
 
-						cctx: self.cctx.clone(),
-						name: self.name.clone(),
-						value: self.value.clone(),
-					})))
-				}
-			}
-
-			Ok((
-				name.clone(),
-				LazyBinding::Bindable(Cc::new(tb!(BindableNamed {
-					cctx,
-					name: name.clone(),
-					value: value.clone(),
-				}))),
-			))
-		}
-		#[cfg(feature = "exp-destruct")]
-		BindSpec::Field { into: _, .. } => {
-			use crate::throw_runtime;
-			throw_runtime!("destructuring is not yet supported here")
-		}
-		BindSpec::Function {
-			name,
-			params,
-			value,
-		} => {
-			#[derive(Trace)]
-			struct BindableMethodThunk {
-				this: Option<ObjValue>,
-				super_obj: Option<ObjValue>,
-
-				cctx: ContextCreator,
-				name: IStr,
-				params: ParamsDesc,
-				value: LocExpr,
-			}
-			impl ThunkValue for BindableMethodThunk {
-				type Output = Val;
-				fn get(self: Box<Self>, s: State) -> Result<Val> {
-					Ok(evaluate_method(
-						self.cctx.create(s, self.this, self.super_obj)?,
-						self.name,
-						self.params,
-						self.value,
-					))
-				}
-			}
-
-			#[derive(Trace)]
-			struct BindableMethod {
-				cctx: ContextCreator,
-				name: IStr,
-				params: ParamsDesc,
-				value: LocExpr,
-			}
-			impl Bindable for BindableMethod {
-				fn bind(
-					&self,
-					_: State,
-					this: Option<ObjValue>,
-					super_obj: Option<ObjValue>,
-				) -> Result<Thunk<Val>> {
-					Ok(Thunk::<Val>::new(tb!(BindableMethodThunk {
-						this,
-						super_obj,
-
-						cctx: self.cctx.clone(),
-						name: self.name.clone(),
-						params: self.params.clone(),
-						value: self.value.clone(),
-					})))
-				}
-			}
-
-			let params = params.clone();
-
-			Ok((
-				name.clone(),
-				LazyBinding::Bindable(Cc::new(tb!(BindableMethod {
-					cctx,
-					name: name.clone(),
-					params,
-					value,
-				}))),
-			))
-		}
-	}
-}
-
 pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
 	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {
 		name,
@@ -218,28 +86,65 @@
 	Ok(())
 }
 
+trait CloneableBindable<T>: Bindable<Bound = T> + Clone {}
+
+fn evaluate_object_locals(
+	fctx: Pending<Context>,
+	locals: Rc<Vec<BindSpec>>,
+) -> impl CloneableBindable<Context> {
+	#[derive(Trace, Clone)]
+	struct WithObjectLocals {
+		fctx: Pending<Context>,
+		locals: Rc<Vec<BindSpec>>,
+	}
+	impl CloneableBindable<Context> for WithObjectLocals {}
+	impl Bindable for WithObjectLocals {
+		type Bound = Context;
+
+		fn bind(
+			&self,
+			_s: State,
+			sup: Option<ObjValue>,
+			this: Option<ObjValue>,
+		) -> Result<Context> {
+			let fctx = Context::new_future();
+			let mut new_bindings = GcHashMap::new();
+			for b in self.locals.iter() {
+				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+			}
+
+			let ctx = self.fctx.unwrap();
+			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());
+
+			let ctx = ctx
+				.extend(new_bindings, new_dollar, sup, this)
+				.into_future(fctx);
+
+			Ok(ctx)
+		}
+	}
+
+	WithObjectLocals { fctx, locals }
+}
+
 #[allow(clippy::too_many_lines)]
 pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {
-	let new_bindings = Pending::new();
-	let future_this = Pending::new();
-	let cctx = ContextCreator(ctx.clone(), new_bindings.clone());
-	{
-		let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());
-		for r in members
+	let mut builder = ObjValueBuilder::new();
+	let locals = Rc::new(
+		members
 			.iter()
 			.filter_map(|m| match m {
-				Member::BindStmt(b) => Some(b.clone()),
+				Member::BindStmt(bind) => Some(bind.clone()),
 				_ => None,
 			})
-			.map(|b| evaluate_binding(b.clone(), cctx.clone()))
-		{
-			let (n, b) = r?;
-			bindings.insert(n, b);
-		}
-		new_bindings.fill(bindings);
-	}
+			.collect::<Vec<_>>(),
+	);
+
+	let fctx = Context::new_future();
+
+	// We have single context for all fields, so we can cache binds
+	let uctx = CachedBindable::new(evaluate_object_locals(fctx.clone(), locals));
 
-	let mut builder = ObjValueBuilder::new();
 	for member in members.iter() {
 		match member {
 			Member::Field(FieldMember {
@@ -250,21 +155,22 @@
 				value,
 			}) => {
 				#[derive(Trace)]
-				struct ObjMemberBinding {
-					cctx: ContextCreator,
+				struct ObjMemberBinding<B> {
+					uctx: B,
 					value: LocExpr,
 					name: IStr,
 				}
-				impl Bindable for ObjMemberBinding {
+				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {
+					type Bound = Thunk<Val>;
 					fn bind(
 						&self,
 						s: State,
+						sup: Option<ObjValue>,
 						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
 					) -> Result<Thunk<Val>> {
 						Ok(Thunk::evaluated(evaluate_named(
 							s.clone(),
-							self.cctx.create(s, this, super_obj)?,
+							self.uctx.bind(s, sup, this)?,
 							&self.value,
 							self.name.clone(),
 						)?))
@@ -286,9 +192,9 @@
 					.bindable(
 						s.clone(),
 						tb!(ObjMemberBinding {
-							cctx: cctx.clone(),
+							uctx: uctx.clone(),
 							value: value.clone(),
-							name,
+							name: name.clone()
 						}),
 					)?;
 			}
@@ -299,21 +205,22 @@
 				..
 			}) => {
 				#[derive(Trace)]
-				struct ObjMemberBinding {
-					cctx: ContextCreator,
+				struct ObjMemberBinding<B> {
+					uctx: B,
 					value: LocExpr,
 					params: ParamsDesc,
 					name: IStr,
 				}
-				impl Bindable for ObjMemberBinding {
+				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {
+					type Bound = Thunk<Val>;
 					fn bind(
 						&self,
 						s: State,
+						sup: Option<ObjValue>,
 						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
 					) -> Result<Thunk<Val>> {
 						Ok(Thunk::evaluated(evaluate_method(
-							self.cctx.create(s, this, super_obj)?,
+							self.uctx.bind(s, sup, this)?,
 							self.name.clone(),
 							self.params.clone(),
 							self.value.clone(),
@@ -334,40 +241,42 @@
 					.bindable(
 						s.clone(),
 						tb!(ObjMemberBinding {
-							cctx: cctx.clone(),
+							uctx: uctx.clone(),
 							value: value.clone(),
 							params: params.clone(),
-							name,
+							name: name.clone()
 						}),
 					)?;
 			}
 			Member::BindStmt(_) => {}
 			Member::AssertStmt(stmt) => {
 				#[derive(Trace)]
-				struct ObjectAssert {
-					cctx: ContextCreator,
+				struct ObjectAssert<B> {
+					uctx: B,
 					assert: AssertStmt,
 				}
-				impl ObjectAssertion for ObjectAssert {
+				impl<B: Bindable<Bound = Context>> ObjectAssertion for ObjectAssert<B> {
 					fn run(
 						&self,
 						s: State,
+						sup: Option<ObjValue>,
 						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
 					) -> Result<()> {
-						let ctx = self.cctx.create(s.clone(), this, super_obj)?;
+						let ctx = self.uctx.bind(s.clone(), sup, this)?;
 						evaluate_assert(s, ctx, &self.assert)
 					}
 				}
 				builder.assert(tb!(ObjectAssert {
-					cctx: cctx.clone(),
+					uctx: uctx.clone(),
 					assert: stmt.clone(),
 				}));
 			}
 		}
 	}
 	let this = builder.build();
-	future_this.fill(this.clone());
+	let _ctx = ctx
+		.extend(GcHashMap::new(), None, None, Some(this.clone()))
+		.into_future(fctx);
 	Ok(this)
 }
 
@@ -375,44 +284,45 @@
 	Ok(match object {
 		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,
 		ObjBody::ObjComp(obj) => {
-			let future_this = Pending::new();
 			let mut builder = ObjValueBuilder::new();
-			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {
-				let new_bindings = Pending::new();
-				let cctx = ContextCreator(ctx.clone(), new_bindings.clone());
-				let mut bindings: GcHashMap<IStr, LazyBinding> =
-					GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());
-				for r in obj
-					.pre_locals
+			let locals = Rc::new(
+				obj.pre_locals
 					.iter()
 					.chain(obj.post_locals.iter())
-					.map(|b| evaluate_binding(b.clone(), cctx.clone()))
-				{
-					let (n, b) = r?;
-					bindings.insert(n, b);
-				}
-				new_bindings.fill(bindings.clone());
-				let ctx = ctx.extend_unbound(s.clone(), bindings, None, None, None)?;
+					.cloned()
+					.collect::<Vec<_>>(),
+			);
+			let mut ctxs = vec![];
+			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {
 				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;
+				let fctx = Context::new_future();
+				ctxs.push((ctx, fctx.clone()));
+				let uctx = evaluate_object_locals(fctx, locals.clone());
 
 				match key {
 					Val::Null => {}
 					Val::Str(n) => {
 						#[derive(Trace)]
-						struct ObjCompBinding {
-							ctx: Context,
+						struct ObjCompBinding<B> {
+							uctx: B,
 							value: LocExpr,
 						}
-						impl Bindable for ObjCompBinding {
+						impl<B: Bindable<Bound = Context>> Bindable for ObjCompBinding<B> {
+							type Bound = Thunk<Val>;
 							fn bind(
 								&self,
 								s: State,
+								sup: Option<ObjValue>,
 								this: Option<ObjValue>,
-								_super_obj: Option<ObjValue>,
 							) -> Result<Thunk<Val>> {
 								Ok(Thunk::evaluated(evaluate(
-									s,
-									self.ctx.clone().extend(GcHashMap::new(), None, this, None),
+									s.clone(),
+									self.uctx.bind(s, sup, this.clone())?.extend(
+										GcHashMap::new(),
+										None,
+										None,
+										this,
+									),
 									&self.value,
 								)?))
 							}
@@ -424,7 +334,7 @@
 							.bindable(
 								s.clone(),
 								tb!(ObjCompBinding {
-									ctx,
+									uctx,
 									value: obj.value.clone(),
 								}),
 							)?;
@@ -436,7 +346,11 @@
 			})?;
 
 			let this = builder.build();
-			future_this.fill(this.clone());
+			for (ctx, fctx) in ctxs {
+				let _ctx = ctx
+					.extend(GcHashMap::new(), None, None, Some(this.clone()))
+					.into_future(fctx);
+			}
 			this
 		}
 	})
@@ -596,7 +510,7 @@
 			for b in bindings {
 				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
 			}
-			let ctx = ctx.extend_bound(new_bindings).into_future(fctx);
+			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);
 			evaluate(s, ctx, &returned.clone())?
 		}
 		Arr(items) => {
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -139,11 +139,12 @@
 	) -> Result<Val> {
 		match self {
 			Self::Id => {
+				#[allow(clippy::unnecessary_wraps)]
 				#[builtin]
-				fn builtin_id(v: Any) -> Result<Any> {
+				const fn builtin_id(v: Any) -> Result<Any> {
 					Ok(v)
 				}
-				static ID: &'static builtin_id = &builtin_id {};
+				static ID: &builtin_id = &builtin_id {};
 
 				ID.call(s, call_ctx, loc, args)
 			}
@@ -159,10 +160,10 @@
 		self.evaluate(s, Context::default(), CallLocation::native(), args, true)
 	}
 
-	pub fn is_identity(&self) -> bool {
+	pub const fn is_identity(&self) -> bool {
 		matches!(self, Self::Id)
 	}
-	pub fn identity() -> Self {
+	pub const fn identity() -> Self {
 		Self::Id
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -111,7 +111,7 @@
 
 		Ok(body_ctx
 			.extend(passed_args, None, None, None)
-			.extend_bound(defaults)
+			.extend(defaults, None, None, None)
 			.into_future(fctx))
 	} else {
 		let body_ctx = body_ctx.extend(passed_args, None, None, None);
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -10,7 +10,7 @@
 use rustc_hash::{FxHashMap, FxHashSet};
 
 /// Replacement for box, which assumes that the underlying type is [`Trace`]
-/// Used in places, where Cc<dyn Trait> should be used instead, but it can't, because CoerceUnsiced is not stable
+/// Used in places, where `Cc<dyn Trait>` should be used instead, but it can't, because `CoerceUnsiced` is not stable
 #[derive(Debug, Clone)]
 pub struct TraceBox<T: ?Sized>(pub Box<T>);
 #[macro_export]
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -61,17 +61,13 @@
 pub use val::{ManifestFormat, Thunk, Val};
 
 pub trait Bindable: Trace + 'static {
-	fn bind(
-		&self,
-		s: State,
-		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
-	) -> Result<Thunk<Val>>;
+	type Bound;
+	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
 }
 
 #[derive(Clone, Trace)]
 pub enum LazyBinding {
-	Bindable(Cc<TraceBox<dyn Bindable>>),
+	Bindable(Cc<TraceBox<dyn Bindable<Bound = Thunk<Val>>>>),
 	Bound(Thunk<Val>),
 }
 
@@ -84,11 +80,11 @@
 	pub fn evaluate(
 		&self,
 		s: State,
+		sup: Option<ObjValue>,
 		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
 	) -> Result<Thunk<Val>> {
 		match self {
-			Self::Bindable(v) => v.bind(s, this, super_obj),
+			Self::Bindable(v) => v.bind(s, sup, this),
 			Self::Bound(v) => Ok(v.clone()),
 		}
 	}
@@ -345,7 +341,7 @@
 		for (name, value) in globals.iter() {
 			new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));
 		}
-		Context::new().extend_bound(new_bindings)
+		Context::new().extend(new_bindings, None, None, None)
 	}
 
 	/// Executes code creating a new stack frame
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	cell::RefCell,3	fmt::Debug,4	hash::{Hash, Hasher},5	ptr::addr_of,6};78use gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14	cc_ptr_eq,15	error::{Error::*, LocError},16	function::CallLocation,17	gc::{GcHashMap, GcHashSet, TraceBox},18	operator::evaluate_add_op,19	throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, Result, State, Thunk, Val,20};2122#[cfg(not(feature = "exp-preserve-order"))]23mod ordering {24	#![allow(25		// This module works as stub for preserve-order feature26		clippy::unused_self,27	)]2829	use gcmodule::Trace;3031	#[derive(Clone, Copy, Default, Debug, Trace)]32	pub struct FieldIndex;33	impl FieldIndex {34		pub const fn next(self) -> Self {35			Self36		}37	}3839	#[derive(Clone, Copy, Default, Debug, Trace)]40	pub struct SuperDepth;41	impl SuperDepth {42		pub const fn deeper(self) -> Self {43			Self44		}45	}4647	#[derive(Clone, Copy)]48	pub struct FieldSortKey;49	impl FieldSortKey {50		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {51			Self52		}53	}54}5556#[cfg(feature = "exp-preserve-order")]57mod ordering {58	use std::cmp::Reverse;5960	use gcmodule::Trace;6162	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]63	pub struct FieldIndex(u32);64	impl FieldIndex {65		pub fn next(self) -> Self {66			Self(self.0 + 1)67		}68	}6970	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]71	pub struct SuperDepth(u32);72	impl SuperDepth {73		pub fn deeper(self) -> Self {74			Self(self.0 + 1)75		}76	}7778	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]79	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);80	impl FieldSortKey {81		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {82			Self(Reverse(depth), index)83		}84		pub fn collide(self, other: Self) -> Self {85			if self.0 .0 > other.0 .0 {86				self87			} else if self.0 .0 < other.0 .0 {88				other89			} else {90				unreachable!("object can't have two fields with same name")91			}92		}93	}94}9596use ordering::*;9798#[allow(clippy::module_name_repetitions)]99#[derive(Debug, Trace)]100pub struct ObjMember {101	pub add: bool,102	pub visibility: Visibility,103	original_index: FieldIndex,104	pub invoke: LazyBinding,105	pub location: Option<ExprLocation>,106}107108pub trait ObjectAssertion: Trace {109	fn run(&self, s: State, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;110}111112// Field => This113type CacheKey = (IStr, WeakObjValue);114115#[derive(Trace)]116enum CacheValue {117	Cached(Val),118	NotFound,119	Pending,120	Errored(LocError),121}122123#[allow(clippy::module_name_repetitions)]124#[derive(Trace)]125#[force_tracking]126pub struct ObjValueInternals {127	super_obj: Option<ObjValue>,128	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129	assertions_ran: RefCell<GcHashSet<ObjValue>>,130	this_obj: Option<ObjValue>,131	this_entries: Cc<GcHashMap<IStr, ObjMember>>,132	value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,133}134135#[derive(Clone, Trace)]136pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);137138impl PartialEq for WeakObjValue {139	fn eq(&self, other: &Self) -> bool {140		weak_ptr_eq(self.0.clone(), other.0.clone())141	}142}143144impl Eq for WeakObjValue {}145impl Hash for WeakObjValue {146	fn hash<H: Hasher>(&self, hasher: &mut H) {147		hasher.write_usize(weak_raw(self.0.clone()) as usize);148	}149}150151#[allow(clippy::module_name_repetitions)]152#[derive(Clone, Trace)]153pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);154impl Debug for ObjValue {155	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {156		if let Some(super_obj) = self.0.super_obj.as_ref() {157			if f.alternate() {158				write!(f, "{:#?}", super_obj)?;159			} else {160				write!(f, "{:?}", super_obj)?;161			}162			write!(f, " + ")?;163		}164		let mut debug = f.debug_struct("ObjValue");165		for (name, member) in self.0.this_entries.iter() {166			debug.field(name, member);167		}168		debug.finish_non_exhaustive()169	}170}171172impl ObjValue {173	pub fn new(174		super_obj: Option<Self>,175		this_entries: Cc<GcHashMap<IStr, ObjMember>>,176		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,177	) -> Self {178		Self(Cc::new(ObjValueInternals {179			super_obj,180			assertions,181			assertions_ran: RefCell::new(GcHashSet::new()),182			this_obj: None,183			this_entries,184			value_cache: RefCell::new(GcHashMap::new()),185		}))186	}187	pub fn new_empty() -> Self {188		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))189	}190	#[must_use]191	pub fn extend_from(&self, super_obj: Self) -> Self {192		match &self.0.super_obj {193			None => Self::new(194				Some(super_obj),195				self.0.this_entries.clone(),196				self.0.assertions.clone(),197			),198			Some(v) => Self::new(199				Some(v.extend_from(super_obj)),200				self.0.this_entries.clone(),201				self.0.assertions.clone(),202			),203		}204	}205	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {206		let mut new = GcHashMap::with_capacity(1);207		new.insert(key, value);208		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))209	}210	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {211		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())212	}213214	#[must_use]215	pub fn with_this(&self, this_obj: Self) -> Self {216		Self(Cc::new(ObjValueInternals {217			super_obj: self.0.super_obj.clone(),218			assertions: self.0.assertions.clone(),219			assertions_ran: RefCell::new(GcHashSet::new()),220			this_obj: Some(this_obj),221			this_entries: self.0.this_entries.clone(),222			value_cache: RefCell::new(GcHashMap::new()),223		}))224	}225226	pub fn len(&self) -> usize {227		self.fields_visibility()228			.into_iter()229			.filter(|(_, (visible, _))| *visible)230			.count()231	}232233	pub fn is_empty(&self) -> bool {234		if !self.0.this_entries.is_empty() {235			return false;236		}237		self.0.super_obj.as_ref().map_or(true, Self::is_empty)238	}239240	/// Run callback for every field found in object241	pub(crate) fn enum_fields(242		&self,243		depth: SuperDepth,244		handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,245	) -> bool {246		if let Some(s) = &self.0.super_obj {247			if s.enum_fields(depth.deeper(), handler) {248				return true;249			}250		}251		for (name, member) in self.0.this_entries.iter() {252			if handler(depth, name, member) {253				return true;254			}255		}256		false257	}258259	pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {260		let mut out = FxHashMap::default();261		self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {262			let new_sort_key = FieldSortKey::new(depth, member.original_index);263			match member.visibility {264				Visibility::Normal => {265					let entry = out.entry(name.clone());266					let v = entry.or_insert((true, new_sort_key));267					v.1 = new_sort_key;268				}269				Visibility::Hidden => {270					out.insert(name.clone(), (false, new_sort_key));271				}272				Visibility::Unhide => {273					out.insert(name.clone(), (true, new_sort_key));274				}275			};276			false277		});278		out279	}280	pub fn fields_ex(281		&self,282		include_hidden: bool,283		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,284	) -> Vec<IStr> {285		#[cfg(feature = "exp-preserve-order")]286		if preserve_order {287			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self288				.fields_visibility()289				.into_iter()290				.filter(|(_, (visible, _))| include_hidden || *visible)291				.enumerate()292				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))293				.unzip();294			keys.sort_unstable_by_key(|v| v.0);295			// Reorder in-place by resulting indexes296			for i in 0..fields.len() {297				let x = fields[i].clone();298				let mut j = i;299				loop {300					let k = keys[j].1;301					keys[j].1 = j;302					if k == i {303						break;304					}305					fields[j] = fields[k].clone();306					j = k307				}308				fields[j] = x;309			}310			return fields;311		}312313		let mut fields: Vec<_> = self314			.fields_visibility()315			.into_iter()316			.filter(|(_, (visible, _))| include_hidden || *visible)317			.map(|(k, _)| k)318			.collect();319		fields.sort_unstable();320		fields321	}322	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {323		self.fields_ex(324			false,325			#[cfg(feature = "exp-preserve-order")]326			preserve_order,327		)328	}329330	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {331		if let Some(m) = self.0.this_entries.get(&name) {332			Some(match &m.visibility {333				Visibility::Normal => self334					.0335					.super_obj336					.as_ref()337					.and_then(|super_obj| super_obj.field_visibility(name))338					.unwrap_or(Visibility::Normal),339				v => *v,340			})341		} else if let Some(super_obj) = &self.0.super_obj {342			super_obj.field_visibility(name)343		} else {344			None345		}346	}347348	fn has_field_include_hidden(&self, name: IStr) -> bool {349		if self.0.this_entries.contains_key(&name) {350			true351		} else if let Some(super_obj) = &self.0.super_obj {352			super_obj.has_field_include_hidden(name)353		} else {354			false355		}356	}357358	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {359		if include_hidden {360			self.has_field_include_hidden(name)361		} else {362			self.has_field(name)363		}364	}365	pub fn has_field(&self, name: IStr) -> bool {366		self.field_visibility(name)367			.map_or(false, |v| v.is_visible())368	}369370	pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {371		self.run_assertions(s.clone())?;372		self.get_raw(s, key, self.0.this_obj.as_ref())373	}374375	// pub fn extend_with(self, key: )376377	fn get_raw(&self, s: State, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {378		let real_this = real_this.unwrap_or(self);379		let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));380381		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {382			return Ok(match v {383				CacheValue::Cached(v) => Some(v.clone()),384				CacheValue::NotFound => None,385				CacheValue::Pending => throw!(InfiniteRecursionDetected),386				CacheValue::Errored(e) => return Err(e.clone()),387			});388		}389		self.0390			.value_cache391			.borrow_mut()392			.insert(cache_key.clone(), CacheValue::Pending);393		let fill_error = |e: LocError| {394			self.0395				.value_cache396				.borrow_mut()397				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));398			e399		};400		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {401			(Some(k), None) => Ok(Some(402				self.evaluate_this(s, k, real_this).map_err(fill_error)?,403			)),404			(Some(k), Some(super_obj)) => {405				let our = self406					.evaluate_this(s.clone(), k, real_this)407					.map_err(fill_error)?;408				if k.add {409					super_obj410						.get_raw(s.clone(), key, Some(real_this))411						.map_err(fill_error)?412						.map_or(Ok(Some(our.clone())), |v| {413							Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))414						})415				} else {416					Ok(Some(our))417				}418			}419			(None, Some(super_obj)) => super_obj.get_raw(s, key, Some(real_this)),420			(None, None) => Ok(None),421		}422		.map_err(fill_error)?;423		self.0.value_cache.borrow_mut().insert(424			cache_key,425			match &value {426				Some(v) => CacheValue::Cached(v.clone()),427				None => CacheValue::NotFound,428			},429		);430		Ok(value)431	}432	fn evaluate_this(&self, s: State, v: &ObjMember, real_this: &Self) -> Result<Val> {433		v.invoke434			.evaluate(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())?435			.evaluate(s)436	}437438	fn run_assertions_raw(&self, s: State, real_this: &Self) -> Result<()> {439		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {440			for assertion in self.0.assertions.iter() {441				if let Err(e) =442					assertion.run(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())443				{444					self.0.assertions_ran.borrow_mut().remove(real_this);445					return Err(e);446				}447			}448			if let Some(super_obj) = &self.0.super_obj {449				super_obj.run_assertions_raw(s, real_this)?;450			}451		}452		Ok(())453	}454	pub fn run_assertions(&self, s: State) -> Result<()> {455		self.run_assertions_raw(s, self)456	}457458	pub fn ptr_eq(a: &Self, b: &Self) -> bool {459		cc_ptr_eq(&a.0, &b.0)460	}461}462463impl PartialEq for ObjValue {464	fn eq(&self, other: &Self) -> bool {465		cc_ptr_eq(&self.0, &other.0)466	}467}468469impl Eq for ObjValue {}470impl Hash for ObjValue {471	fn hash<H: Hasher>(&self, hasher: &mut H) {472		hasher.write_usize(addr_of!(*self.0) as usize);473	}474}475476#[allow(clippy::module_name_repetitions)]477pub struct ObjValueBuilder {478	super_obj: Option<ObjValue>,479	map: GcHashMap<IStr, ObjMember>,480	assertions: Vec<TraceBox<dyn ObjectAssertion>>,481	next_field_index: FieldIndex,482}483impl ObjValueBuilder {484	pub fn new() -> Self {485		Self::with_capacity(0)486	}487	pub fn with_capacity(capacity: usize) -> Self {488		Self {489			super_obj: None,490			map: GcHashMap::with_capacity(capacity),491			assertions: Vec::new(),492			next_field_index: FieldIndex::default(),493		}494	}495	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {496		self.assertions.reserve_exact(capacity);497		self498	}499	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {500		self.super_obj = Some(super_obj);501		self502	}503504	pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {505		self.assertions.push(assertion);506		self507	}508	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {509		let field_index = self.next_field_index;510		self.next_field_index = self.next_field_index.next();511		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)512	}513514	pub fn build(self) -> ObjValue {515		ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))516	}517}518impl Default for ObjValueBuilder {519	fn default() -> Self {520		Self::with_capacity(0)521	}522}523524#[allow(clippy::module_name_repetitions)]525#[must_use = "value not added unless binding() was called"]526pub struct ObjMemberBuilder<Kind> {527	kind: Kind,528	name: IStr,529	add: bool,530	visibility: Visibility,531	original_index: FieldIndex,532	location: Option<ExprLocation>,533}534535#[allow(clippy::missing_const_for_fn)]536impl<Kind> ObjMemberBuilder<Kind> {537	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {538		Self {539			kind,540			name,541			original_index,542			add: false,543			visibility: Visibility::Normal,544			location: None,545		}546	}547548	pub const fn with_add(mut self, add: bool) -> Self {549		self.add = add;550		self551	}552	pub fn add(self) -> Self {553		self.with_add(true)554	}555	pub fn with_visibility(mut self, visibility: Visibility) -> Self {556		self.visibility = visibility;557		self558	}559	pub fn hide(self) -> Self {560		self.with_visibility(Visibility::Hidden)561	}562	pub fn with_location(mut self, location: ExprLocation) -> Self {563		self.location = Some(location);564		self565	}566	fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {567		(568			self.kind,569			self.name,570			ObjMember {571				add: self.add,572				visibility: self.visibility,573				original_index: self.original_index,574				invoke: binding,575				location: self.location,576			},577		)578	}579}580581pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);582impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {583	pub fn value(self, s: State, value: Val) -> Result<()> {584		self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))585	}586	pub fn bindable(self, s: State, bindable: TraceBox<dyn Bindable>) -> Result<()> {587		self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))588	}589	pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {590		let (receiver, name, member) = self.build_member(binding);591		let location = member.location.clone();592		let old = receiver.0.map.insert(name.clone(), member);593		if old.is_some() {594			s.push(595				CallLocation(location.as_ref()),596				|| format!("field <{}> initializtion", name.clone()),597				|| throw!(DuplicateFieldName(name.clone())),598			)?;599		}600		Ok(())601	}602}603604pub struct ExtendBuilder<'v>(&'v mut ObjValue);605impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {606	pub fn value(self, value: Val) {607		self.binding(LazyBinding::Bound(Thunk::evaluated(value)));608	}609	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {610		self.binding(LazyBinding::Bindable(Cc::new(bindable)));611	}612	pub fn binding(self, binding: LazyBinding) {613		let (receiver, name, member) = self.build_member(binding);614		let new = receiver.0.clone();615		*receiver.0 = new.extend_with_raw_member(name, member);616	}617}
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -466,7 +466,7 @@
 	Ok(ArrValue::Eager(sort::sort(
 		s.clone(),
 		arr.evaluated(s)?,
-		keyF.unwrap_or(FuncVal::identity()),
+		keyF.unwrap_or_else(FuncVal::identity),
 	)?))
 }
 
modifiedcrates/jrsonnet-evaluator/src/stdlib/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/sort.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/sort.rs
@@ -68,7 +68,23 @@
 	if values.len() <= 1 {
 		return Ok(values);
 	}
-	if !key_getter.is_identity() {
+	if key_getter.is_identity() {
+		// Fast path, identity key getter
+		let mut values = (*values).clone();
+		let sort_type = get_sort_type(&mut values, |k| k)?;
+		match sort_type {
+			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
+				Val::Num(n) => NonNaNf64(*n),
+				_ => unreachable!(),
+			}),
+			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
+				Val::Str(s) => s.clone(),
+				_ => unreachable!(),
+			}),
+			SortKeyType::Unknown => unreachable!(),
+		};
+		Ok(Cc::new(values))
+	} else {
 		// Slow path, user provided key getter
 		let mut vk = Vec::with_capacity(values.len());
 		for value in values.iter() {
@@ -90,21 +106,5 @@
 			SortKeyType::Unknown => unreachable!(),
 		};
 		Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
-	} else {
-		// Fast path, identity key getter
-		let mut values = (*values).clone();
-		let sort_type = get_sort_type(&mut values, |k| k)?;
-		match sort_type {
-			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
-				Val::Num(n) => NonNaNf64(*n),
-				_ => unreachable!(),
-			}),
-			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
-				Val::Str(s) => s.clone(),
-				_ => unreachable!(),
-			}),
-			SortKeyType::Unknown => unreachable!(),
-		};
-		Ok(Cc::new(values))
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -8,11 +8,11 @@
 	cc_ptr_eq,
 	error::{Error::*, LocError},
 	function::FuncVal,
-	gc::TraceBox,
+	gc::{GcHashMap, TraceBox},
 	stdlib::manifest::{
 		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
 	},
-	throw, ObjValue, Result, State,
+	throw, Bindable, ObjValue, Result, State, WeakObjValue,
 };
 
 pub trait ThunkValue: Trace {
@@ -71,6 +71,47 @@
 	}
 }
 
+type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
+
+#[derive(Trace, Clone)]
+pub struct CachedBindable<I, T>
+where
+	I: Bindable<Bound = T>,
+{
+	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,
+	value: I,
+}
+impl<I: Bindable<Bound = T>, T: Trace> CachedBindable<I, T> {
+	pub fn new(value: I) -> Self {
+		Self {
+			cache: Cc::new(RefCell::new(GcHashMap::new())),
+			value,
+		}
+	}
+}
+impl<I: Bindable<Bound = T>, T: Clone + Trace> Bindable for CachedBindable<I, T> {
+	type Bound = T;
+	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {
+		let cache_key = (
+			sup.as_ref().map(|s| s.clone().downgrade()),
+			this.as_ref().map(|t| t.clone().downgrade()),
+		);
+		{
+			if let Some(t) = self.cache.borrow().get(&cache_key) {
+				return Ok(t.clone());
+			}
+		}
+		let bound = self.value.bind(s, sup, this)?;
+
+		{
+			let mut cache = self.cache.borrow_mut();
+			cache.insert(cache_key, bound.clone());
+		}
+
+		Ok(bound)
+	}
+}
+
 impl<T: Debug> Debug for Thunk<T> {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "Lazy")
modifiedcrates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ b/crates/jrsonnet-evaluator/tests/builtin.rs
@@ -6,7 +6,6 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, builtin::Builtin, CallLocation, FuncVal},
-	gc::TraceBox,
 	tb,
 	typed::Typed,
 	State, Val,
modifiedcrates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -30,8 +30,18 @@
 		if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
 			::jrsonnet_evaluator::throw_runtime!(
 				"assertion failed: a != b\na={:#?}\nb={:#?}",
-				$a.to_json($s.clone(), 2)?,
-				$b.to_json($s.clone(), 2)?,
+				$a.to_json(
+					$s.clone(),
+					2,
+					#[cfg(feature = "exp-preserve-order")]
+					false
+				)?,
+				$b.to_json(
+					$s.clone(),
+					2,
+					#[cfg(feature = "exp-preserve-order")]
+					false
+				)?,
 			)
 		}
 	}};
modifiedcrates/jrsonnet-evaluator/tests/golden.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/golden.rs
+++ b/crates/jrsonnet-evaluator/tests/golden.rs
@@ -24,7 +24,12 @@
 		Ok(v) => v,
 		Err(e) => return s.stringify_err(&e),
 	};
-	match v.to_json(s.clone(), 3) {
+	match v.to_json(
+		s.clone(),
+		3,
+		#[cfg(feature = "exp-preserve-order")]
+		false,
+	) {
 		Ok(v) => v.to_string(),
 		Err(e) => s.stringify_err(&e),
 	}
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -165,7 +165,7 @@
 			/ string_block() } / expected!("<string>")
 
 		pub rule field_name(s: &ParserSettings) -> expr::FieldName
-			= name:id() {expr::FieldName::Fixed(name.into())}
+			= name:id() {expr::FieldName::Fixed(name)}
 			/ name:string() {expr::FieldName::Fixed(name.into())}
 			/ "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}
 		pub rule visibility() -> expr::Visibility