git.delta.rocks / jrsonnet / refs/commits / 88a0ba11fe45

difftreelog

feat field destructuring

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

22 files changed

modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -9,7 +9,7 @@
 use jrsonnet_evaluator::{
 	error::{Error, LocError},
 	function::builtin::{BuiltinParam, NativeCallback, NativeCallbackHandler},
-	gc::TraceBox,
+	tb,
 	typed::Typed,
 	IStr, State, Val,
 };
@@ -78,9 +78,9 @@
 	vm.add_native(
 		name,
 		#[allow(deprecated)]
-		Cc::new(TraceBox(Box::new(NativeCallback::new(
+		Cc::new(tb!(NativeCallback::new(
 			params,
-			TraceBox(Box::new(JsonnetNativeCallbackHandler { ctx, cb })),
-		)))),
+			tb!(JsonnetNativeCallbackHandler { ctx, cb }),
+		))),
 	)
 }
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -5,7 +5,7 @@
 use std::{ffi::CStr, os::raw::c_char};
 
 use gcmodule::Cc;
-use jrsonnet_evaluator::{val::ArrValue, LazyVal, State, Val};
+use jrsonnet_evaluator::{val::ArrValue, State, Thunk, Val};
 
 /// # Safety
 ///
@@ -18,7 +18,8 @@
 			for item in old.iter_lazy() {
 				new.push(item);
 			}
-			new.push(LazyVal::new_resolved(val.clone()));
+
+			new.push(Thunk::evaluated(val.clone()));
 			*arr = Val::Arr(ArrValue::Lazy(Cc::new(new)));
 		}
 		_ => panic!("should receive array"),
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -16,6 +16,8 @@
     "jrsonnet-evaluator/exp-serde-preserve-order",
     "jrsonnet-cli/exp-preserve-order",
 ]
+# Destructuring of locals
+exp-destruct = ["jrsonnet-evaluator/exp-destruct"]
 
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -18,6 +18,8 @@
 # Allows to preserve field order in objects
 exp-preserve-order = []
 exp-serde-preserve-order = ["serde_json/preserve_order"]
+# Implements field destructuring
+exp-destruct = []
 
 [dependencies]
 jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,12 +4,12 @@
 use jrsonnet_interner::IStr;
 
 use crate::{
-	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, FutureWrapper, LazyBinding,
-	LazyVal, ObjValue, Result, State, Val,
+	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, LazyBinding, ObjValue, Pending,
+	Result, State, Thunk, Val,
 };
 
 #[derive(Clone, Trace)]
-pub struct ContextCreator(pub Context, pub FutureWrapper<GcHashMap<IStr, LazyBinding>>);
+pub struct ContextCreator(pub Context, pub Pending<GcHashMap<IStr, LazyBinding>>);
 impl ContextCreator {
 	pub fn create(
 		&self,
@@ -43,8 +43,8 @@
 #[derive(Debug, Clone, Trace)]
 pub struct Context(Cc<ContextInternals>);
 impl Context {
-	pub fn new_future() -> FutureWrapper<Self> {
-		FutureWrapper::new()
+	pub fn new_future() -> Pending<Self> {
+		Pending::new()
 	}
 
 	pub fn dollar(&self) -> &Option<ObjValue> {
@@ -68,7 +68,7 @@
 		}))
 	}
 
-	pub fn binding(&self, name: IStr) -> Result<LazyVal> {
+	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
 		Ok(self
 			.0
 			.bindings
@@ -80,7 +80,7 @@
 		self.0.bindings.contains_key(&name)
 	}
 	#[must_use]
-	pub fn into_future(self, ctx: FutureWrapper<Self>) -> Self {
+	pub fn into_future(self, ctx: Pending<Self>) -> Self {
 		{
 			ctx.0.borrow_mut().replace(self);
 		}
@@ -90,7 +90,7 @@
 	#[must_use]
 	pub fn with_var(self, name: IStr, value: Val) -> Self {
 		let mut new_bindings = GcHashMap::with_capacity(1);
-		new_bindings.insert(name, LazyVal::new_resolved(value));
+		new_bindings.insert(name, Thunk::evaluated(value));
 		self.extend(new_bindings, None, None, None)
 	}
 
@@ -102,7 +102,7 @@
 	#[must_use]
 	pub fn extend(
 		self,
-		new_bindings: GcHashMap<IStr, LazyVal>,
+		new_bindings: GcHashMap<IStr, Thunk<Val>>,
 		new_dollar: Option<ObjValue>,
 		new_this: Option<ObjValue>,
 		new_super_obj: Option<ObjValue>,
@@ -124,7 +124,7 @@
 		}))
 	}
 	#[must_use]
-	pub fn extend_bound(self, new_bindings: GcHashMap<IStr, LazyVal>) -> Self {
+	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)
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -3,8 +3,8 @@
 use gcmodule::{Cc, Trace};
 
 #[derive(Clone, Trace)]
-pub struct FutureWrapper<V: Trace + 'static>(pub Cc<RefCell<Option<V>>>);
-impl<T: Trace + 'static> FutureWrapper<T> {
+pub struct Pending<V: Trace + 'static>(pub Cc<RefCell<Option<V>>>);
+impl<T: Trace + 'static> Pending<T> {
 	pub fn new() -> Self {
 		Self(Cc::new(RefCell::new(None)))
 	}
@@ -15,7 +15,7 @@
 		self.0.borrow_mut().replace(value);
 	}
 }
-impl<T: Clone + Trace + 'static> FutureWrapper<T> {
+impl<T: Clone + Trace + 'static> Pending<T> {
 	/// # Panics
 	/// If wrapper is not yet filled
 	pub fn unwrap(&self) -> T {
@@ -23,7 +23,7 @@
 	}
 }
 
-impl<T: Trace + 'static> Default for FutureWrapper<T> {
+impl<T: Trace + 'static> Default for Pending<T> {
 	fn default() -> Self {
 		Self::new()
 	}
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -45,6 +45,9 @@
 
 	#[error("variable is not defined: {0}")]
 	VariableIsNotDefined(IStr),
+	#[error("duplicate local var: {0}")]
+	DuplicateLocalVar(IStr),
+
 	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
 	TypeMismatch(&'static str, Vec<ValType>, ValType),
 	#[error("no such field: {0}")]
addedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -0,0 +1,294 @@
+use gcmodule::Trace;
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
+
+use crate::{
+	error::{Error::*, Result},
+	evaluate, evaluate_method,
+	gc::GcHashMap,
+	tb, throw,
+	val::ThunkValue,
+	Context, Pending, State, Thunk, Val,
+};
+
+fn destruct(
+	d: &Destruct,
+	parent: Thunk<Val>,
+	new_bindings: &mut GcHashMap<IStr, Thunk<Val>>,
+) -> Result<()> {
+	Ok(match d {
+		Destruct::Full(v) => {
+			let old = new_bindings.insert(v.clone(), parent);
+			if old.is_some() {
+				throw!(DuplicateLocalVar(v.clone()))
+			}
+		}
+		#[cfg(feature = "exp-destruct")]
+		Destruct::Skip => {}
+		#[cfg(feature = "exp-destruct")]
+		Destruct::Array { start, rest, end } => {
+			use jrsonnet_parser::DestructRest;
+
+			use crate::{throw_runtime, val::ArrValue};
+
+			#[derive(Trace)]
+			struct DataThunk {
+				parent: Thunk<Val>,
+				min_len: usize,
+				has_rest: bool,
+			}
+			impl ThunkValue for DataThunk {
+				type Output = ArrValue;
+
+				fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+					let v = self.parent.evaluate(s)?;
+					let arr = match v {
+						Val::Arr(a) => a,
+						_ => throw_runtime!("expected array"),
+					};
+					if !self.has_rest {
+						if arr.len() != self.min_len {
+							throw_runtime!("expected {} elements, got {}", self.min_len, arr.len())
+						}
+					} else if arr.len() < self.min_len {
+						throw_runtime!(
+							"expected at least {} elements, but array was only {}",
+							self.min_len,
+							arr.len()
+						)
+					}
+					Ok(arr)
+				}
+			}
+
+			let full = Thunk::new(tb!(DataThunk {
+				min_len: start.len() + end.len(),
+				has_rest: rest.is_some(),
+				parent,
+			}));
+
+			{
+				#[derive(Trace)]
+				struct BaseThunk {
+					full: Thunk<ArrValue>,
+					index: usize,
+				}
+				impl ThunkValue for BaseThunk {
+					type Output = Val;
+
+					fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+						let full = self.full.evaluate(s.clone())?;
+						Ok(full.get(s, self.index)?.expect("length is checked"))
+					}
+				}
+				for (i, d) in start.iter().enumerate() {
+					destruct(
+						d,
+						Thunk::new(tb!(BaseThunk {
+							full: full.clone(),
+							index: i,
+						})),
+						new_bindings,
+					)?;
+				}
+			}
+
+			match rest {
+				Some(DestructRest::Keep(v)) => {
+					#[derive(Trace)]
+					struct RestThunk {
+						full: Thunk<ArrValue>,
+						start: usize,
+						end: usize,
+					}
+					impl ThunkValue for RestThunk {
+						type Output = Val;
+
+						fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+							let full = self.full.evaluate(s)?;
+							let to = full.len() - self.end;
+							Ok(Val::Arr(full.slice(Some(self.start), Some(to), None)))
+						}
+					}
+
+					destruct(
+						&Destruct::Full(v.clone()),
+						Thunk::new(tb!(RestThunk {
+							full: full.clone(),
+							start: start.len(),
+							end: end.len(),
+						})),
+						new_bindings,
+					)?;
+				}
+				Some(DestructRest::Drop) => {}
+				None => {}
+			}
+
+			{
+				#[derive(Trace)]
+				struct EndThunk {
+					full: Thunk<ArrValue>,
+					index: usize,
+					end: usize,
+				}
+				impl ThunkValue for EndThunk {
+					type Output = Val;
+
+					fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+						let full = self.full.evaluate(s.clone())?;
+						Ok(full
+							.get(s, full.len() - self.end + self.index)?
+							.expect("length is checked"))
+					}
+				}
+				for (i, d) in end.iter().enumerate() {
+					destruct(
+						d,
+						Thunk::new(tb!(EndThunk {
+							full: full.clone(),
+							index: i,
+							end: end.len(),
+						})),
+						new_bindings,
+					)?;
+				}
+			}
+		}
+		#[cfg(feature = "exp-destruct")]
+		Destruct::Object { fields, rest } => {
+			use jrsonnet_parser::DestructRest;
+
+			use crate::{obj::ObjValue, throw_runtime};
+
+			#[derive(Trace)]
+			struct DataThunk {
+				parent: Thunk<Val>,
+				field_names: Vec<IStr>,
+				has_rest: bool,
+			}
+			impl ThunkValue for DataThunk {
+				type Output = ObjValue;
+
+				fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+					let v = self.parent.evaluate(s)?;
+					let obj = match v {
+						Val::Obj(o) => o,
+						_ => throw_runtime!("expected object"),
+					};
+					for field in &self.field_names {
+						if !obj.has_field_ex(field.clone(), true) {
+							throw_runtime!("missing field: {}", field);
+						}
+					}
+					if !self.has_rest {
+						let len = obj.len();
+						if len != self.field_names.len() {
+							throw_runtime!("too many fields, and rest not found");
+						}
+					}
+					Ok(obj)
+				}
+			}
+			let field_names: Vec<_> = fields.iter().map(|f| f.0.clone()).collect();
+			let full = Thunk::new(tb!(DataThunk {
+				parent,
+				field_names: field_names.clone(),
+				has_rest: rest.is_some()
+			}));
+
+			for (field, d) in fields {
+				#[derive(Trace)]
+				struct FieldThunk {
+					full: Thunk<ObjValue>,
+					field: IStr,
+				}
+				impl ThunkValue for FieldThunk {
+					type Output = Val;
+
+					fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+						let full = self.full.evaluate(s.clone())?;
+						let field = full.get(s, self.field)?.expect("shape is checked");
+						Ok(field)
+					}
+				}
+				let value = Thunk::new(tb!(FieldThunk {
+					full: full.clone(),
+					field: field.clone()
+				}));
+				if let Some(d) = d {
+					destruct(d, value, new_bindings)?;
+				} else {
+					destruct(&Destruct::Full(field.clone()), value, new_bindings)?;
+				}
+			}
+		}
+	})
+}
+
+pub fn evaluate_dest(
+	d: &BindSpec,
+	fctx: Pending<Context>,
+	new_bindings: &mut GcHashMap<IStr, Thunk<Val>>,
+) -> Result<()> {
+	match d {
+		BindSpec::Field { into, value } => {
+			#[derive(Trace)]
+			struct EvaluateThunkValue {
+				fctx: Pending<Context>,
+				expr: LocExpr,
+			}
+			impl ThunkValue for EvaluateThunkValue {
+				type Output = Val;
+				fn get(self: Box<Self>, s: State) -> Result<Self::Output> {
+					evaluate(s, self.fctx.unwrap(), &self.expr)
+				}
+			}
+			// TODO: Generate some name, as destructure spec may be used with plain functions
+			let data = Thunk::new(tb!(EvaluateThunkValue {
+				fctx,
+				expr: value.clone(),
+			}));
+			destruct(into, data, new_bindings)?;
+		}
+		BindSpec::Function {
+			name,
+			params,
+			value,
+		} => {
+			#[derive(Trace)]
+			struct MethodThunk {
+				fctx: Pending<Context>,
+				name: IStr,
+				params: ParamsDesc,
+				value: LocExpr,
+			}
+			impl ThunkValue for MethodThunk {
+				type Output = Val;
+
+				fn get(self: Box<Self>, _s: State) -> Result<Self::Output> {
+					Ok(evaluate_method(
+						self.fctx.unwrap(),
+						self.name,
+						self.params,
+						self.value,
+					))
+				}
+			}
+
+			let old = new_bindings.insert(
+				name.clone(),
+				Thunk::new(tb!(MethodThunk {
+					fctx,
+					name: name.clone(),
+					params: params.clone(),
+					value: value.clone()
+				})),
+			);
+			if old.is_some() {
+				throw!(DuplicateLocalVar(name.clone()))
+			}
+		}
+	}
+	Ok(())
+}
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,189 +1,157 @@
 use gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
-	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,
+	ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, ForSpecData, IfSpecData,
 	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
 };
 use jrsonnet_types::ValType;
 
 use crate::{
+	destructure::evaluate_dest,
 	error::Error::*,
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
 	function::{CallLocation, FuncDesc, FuncVal},
-	gc::TraceBox,
 	stdlib::{std_slice, BUILTINS},
-	throw,
+	tb, throw,
 	typed::Typed,
-	val::{ArrValue, LazyValValue},
-	Bindable, Context, ContextCreator, FutureWrapper, GcHashMap, LazyBinding, LazyVal, ObjValue,
-	ObjValueBuilder, ObjectAssertion, Result, State, Val,
+	val::{ArrValue, Thunk, ThunkValue},
+	Bindable, Context, ContextCreator, GcHashMap, LazyBinding, ObjValue, ObjValueBuilder,
+	ObjectAssertion, Pending, Result, State, Val,
 };
+pub mod destructure;
 pub mod operator;
 
-pub fn evaluate_binding_in_future(b: &BindSpec, fctx: FutureWrapper<Context>) -> LazyVal {
-	let b = b.clone();
-	if let Some(params) = &b.params {
-		#[derive(Trace)]
-		struct LazyMethodBinding {
-			fctx: FutureWrapper<Context>,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
-		}
-		impl LazyValValue for LazyMethodBinding {
-			fn get(self: Box<Self>, _: State) -> Result<Val> {
-				Ok(evaluate_method(
-					self.fctx.unwrap(),
-					self.name,
-					self.params,
-					self.value,
-				))
+#[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,
+					)
+				}
+			}
 
-		let params = params.clone();
+			#[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,
 
-		LazyVal::new(TraceBox(Box::new(LazyMethodBinding {
-			fctx,
-			name: b.name.clone(),
-			params,
-			value: b.value.clone(),
-		})))
-	} else {
-		#[derive(Trace)]
-		struct LazyNamedBinding {
-			fctx: FutureWrapper<Context>,
-			name: IStr,
-			value: LocExpr,
-		}
-		impl LazyValValue for LazyNamedBinding {
-			fn get(self: Box<Self>, s: State) -> Result<Val> {
-				evaluate_named(s, self.fctx.unwrap(), &self.value, self.name)
+						cctx: self.cctx.clone(),
+						name: self.name.clone(),
+						value: self.value.clone(),
+					})))
+				}
 			}
-		}
-		LazyVal::new(TraceBox(Box::new(LazyNamedBinding {
-			fctx,
-			name: b.name.clone(),
-			value: b.value,
-		})))
-	}
-}
 
-#[allow(clippy::too_many_lines)]
-pub fn evaluate_binding(b: &BindSpec, cctx: ContextCreator) -> (IStr, LazyBinding) {
-	let b = b.clone();
-	if let Some(params) = &b.params {
-		#[derive(Trace)]
-		struct BindableMethodLazyVal {
-			this: Option<ObjValue>,
-			super_obj: Option<ObjValue>,
-
-			cctx: ContextCreator,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
-		}
-		impl LazyValValue for BindableMethodLazyVal {
-			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,
-				))
-			}
+			Ok((
+				name.clone(),
+				LazyBinding::Bindable(Cc::new(tb!(BindableNamed {
+					cctx,
+					name: name.clone(),
+					value: value.clone(),
+				}))),
+			))
 		}
-
-		#[derive(Trace)]
-		struct BindableMethod {
-			cctx: ContextCreator,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
+		#[cfg(feature = "exp-destruct")]
+		BindSpec::Field { into: _, .. } => {
+			use crate::throw_runtime;
+			throw_runtime!("destructuring is not yet supported here")
 		}
-		impl Bindable for BindableMethod {
-			fn bind(
-				&self,
-				_: State,
+		BindSpec::Function {
+			name,
+			params,
+			value,
+		} => {
+			#[derive(Trace)]
+			struct BindableMethodThunk {
 				this: Option<ObjValue>,
 				super_obj: Option<ObjValue>,
-			) -> Result<LazyVal> {
-				Ok(LazyVal::new(TraceBox(Box::new(BindableMethodLazyVal {
-					this,
-					super_obj,
 
-					cctx: self.cctx.clone(),
-					name: self.name.clone(),
-					params: self.params.clone(),
-					value: self.value.clone(),
-				}))))
+				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,
+					))
+				}
+			}
 
-		let params = params.clone();
-
-		(
-			b.name.clone(),
-			LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableMethod {
-				cctx,
-				name: b.name.clone(),
-				params,
-				value: b.value.clone(),
-			})))),
-		)
-	} else {
-		#[derive(Trace)]
-		struct BindableNamedLazyVal {
-			this: Option<ObjValue>,
-			super_obj: Option<ObjValue>,
+			#[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: ContextCreator,
-			name: IStr,
-			value: LocExpr,
-		}
-		impl LazyValValue for BindableNamedLazyVal {
-			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,
-				)
+						cctx: self.cctx.clone(),
+						name: self.name.clone(),
+						params: self.params.clone(),
+						value: self.value.clone(),
+					})))
+				}
 			}
-		}
 
-		#[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<LazyVal> {
-				Ok(LazyVal::new(TraceBox(Box::new(BindableNamedLazyVal {
-					this,
-					super_obj,
+			let params = params.clone();
 
-					cctx: self.cctx.clone(),
-					name: self.name.clone(),
-					value: self.value.clone(),
-				}))))
-			}
+			Ok((
+				name.clone(),
+				LazyBinding::Bindable(Cc::new(tb!(BindableMethod {
+					cctx,
+					name: name.clone(),
+					params,
+					value,
+				}))),
+			))
 		}
-
-		(
-			b.name.clone(),
-			LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableNamed {
-				cctx,
-				name: b.name.clone(),
-				value: b.value.clone(),
-			})))),
-		)
 	}
 }
 
@@ -252,19 +220,20 @@
 
 #[allow(clippy::too_many_lines)]
 pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {
-	let new_bindings = FutureWrapper::new();
-	let future_this = FutureWrapper::new();
+	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 (n, b) in members
+		for r in members
 			.iter()
 			.filter_map(|m| match m {
 				Member::BindStmt(b) => Some(b.clone()),
 				_ => None,
 			})
-			.map(|b| evaluate_binding(&b, cctx.clone()))
+			.map(|b| evaluate_binding(b.clone(), cctx.clone()))
 		{
+			let (n, b) = r?;
 			bindings.insert(n, b);
 		}
 		new_bindings.fill(bindings);
@@ -292,8 +261,8 @@
 						s: State,
 						this: Option<ObjValue>,
 						super_obj: Option<ObjValue>,
-					) -> Result<LazyVal> {
-						Ok(LazyVal::new_resolved(evaluate_named(
+					) -> Result<Thunk<Val>> {
+						Ok(Thunk::evaluated(evaluate_named(
 							s.clone(),
 							self.cctx.create(s, this, super_obj)?,
 							&self.value,
@@ -316,11 +285,11 @@
 					.with_location(value.1.clone())
 					.bindable(
 						s.clone(),
-						TraceBox(Box::new(ObjMemberBinding {
+						tb!(ObjMemberBinding {
 							cctx: cctx.clone(),
 							value: value.clone(),
 							name,
-						})),
+						}),
 					)?;
 			}
 			Member::Field(FieldMember {
@@ -342,8 +311,8 @@
 						s: State,
 						this: Option<ObjValue>,
 						super_obj: Option<ObjValue>,
-					) -> Result<LazyVal> {
-						Ok(LazyVal::new_resolved(evaluate_method(
+					) -> Result<Thunk<Val>> {
+						Ok(Thunk::evaluated(evaluate_method(
 							self.cctx.create(s, this, super_obj)?,
 							self.name.clone(),
 							self.params.clone(),
@@ -364,12 +333,12 @@
 					.with_location(value.1.clone())
 					.bindable(
 						s.clone(),
-						TraceBox(Box::new(ObjMemberBinding {
+						tb!(ObjMemberBinding {
 							cctx: cctx.clone(),
 							value: value.clone(),
 							params: params.clone(),
 							name,
-						})),
+						}),
 					)?;
 			}
 			Member::BindStmt(_) => {}
@@ -390,10 +359,10 @@
 						evaluate_assert(s, ctx, &self.assert)
 					}
 				}
-				builder.assert(TraceBox(Box::new(ObjectAssert {
+				builder.assert(tb!(ObjectAssert {
 					cctx: cctx.clone(),
 					assert: stmt.clone(),
-				})));
+				}));
 			}
 		}
 	}
@@ -406,19 +375,20 @@
 	Ok(match object {
 		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,
 		ObjBody::ObjComp(obj) => {
-			let future_this = FutureWrapper::new();
+			let future_this = Pending::new();
 			let mut builder = ObjValueBuilder::new();
 			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {
-				let new_bindings = FutureWrapper::new();
+				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 (n, b) in obj
+				for r in obj
 					.pre_locals
 					.iter()
 					.chain(obj.post_locals.iter())
-					.map(|b| evaluate_binding(b, cctx.clone()))
+					.map(|b| evaluate_binding(b.clone(), cctx.clone()))
 				{
+					let (n, b) = r?;
 					bindings.insert(n, b);
 				}
 				new_bindings.fill(bindings.clone());
@@ -439,8 +409,8 @@
 								s: State,
 								this: Option<ObjValue>,
 								_super_obj: Option<ObjValue>,
-							) -> Result<LazyVal> {
-								Ok(LazyVal::new_resolved(evaluate(
+							) -> Result<Thunk<Val>> {
+								Ok(Thunk::evaluated(evaluate(
 									s,
 									self.ctx.clone().extend(GcHashMap::new(), None, this, None),
 									&self.value,
@@ -453,10 +423,10 @@
 							.with_add(obj.plus)
 							.bindable(
 								s.clone(),
-								TraceBox(Box::new(ObjCompBinding {
+								tb!(ObjCompBinding {
 									ctx,
 									value: obj.value.clone(),
-								})),
+								}),
 							)?;
 					}
 					v => throw!(FieldMustBeStringGot(v.value_type())),
@@ -620,11 +590,11 @@
 			}
 		}
 		LocalExpr(bindings, returned) => {
-			let mut new_bindings: GcHashMap<IStr, LazyVal> =
+			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =
 				GcHashMap::with_capacity(bindings.len());
 			let fctx = Context::new_future();
 			for b in bindings {
-				new_bindings.insert(b.name.clone(), evaluate_binding_in_future(b, fctx.clone()));
+				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
 			}
 			let ctx = ctx.extend_bound(new_bindings).into_future(fctx);
 			evaluate(s, ctx, &returned.clone())?
@@ -638,15 +608,16 @@
 					ctx: Context,
 					item: LocExpr,
 				}
-				impl LazyValValue for ArrayElement {
+				impl ThunkValue for ArrayElement {
+					type Output = Val;
 					fn get(self: Box<Self>, s: State) -> Result<Val> {
 						evaluate(s, self.ctx, &self.item)
 					}
 				}
-				out.push(LazyVal::new(TraceBox(Box::new(ArrayElement {
+				out.push(Thunk::new(tb!(ArrayElement {
 					ctx: ctx.clone(),
 					item: item.clone(),
-				}))));
+				})));
 			}
 			Val::Arr(out.into())
 		}
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -5,34 +5,34 @@
 use jrsonnet_parser::{ArgsDesc, LocExpr};
 
 use crate::{
-	error::Result, evaluate, gc::TraceBox, typed::Typed, val::LazyValValue, Context, LazyVal,
-	State, Val,
+	error::Result, evaluate, tb, typed::Typed, val::ThunkValue, Context, State, Thunk, Val,
 };
 
 #[derive(Trace)]
-struct EvaluateLazyVal {
+struct EvaluateThunk {
 	ctx: Context,
 	expr: LocExpr,
 }
-impl LazyValValue for EvaluateLazyVal {
+impl ThunkValue for EvaluateThunk {
+	type Output = Val;
 	fn get(self: Box<Self>, s: State) -> Result<Val> {
 		evaluate(s, self.ctx, &self.expr)
 	}
 }
 
 pub trait ArgLike {
-	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<LazyVal>;
+	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;
 }
 
 impl ArgLike for &LocExpr {
-	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<LazyVal> {
+	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
 		Ok(if tailstrict {
-			LazyVal::new_resolved(evaluate(s, ctx, self)?)
+			Thunk::evaluated(evaluate(s, ctx, self)?)
 		} else {
-			LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+			Thunk::new(tb!(EvaluateThunk {
 				ctx,
 				expr: (*self).clone(),
-			})))
+			}))
 		})
 	}
 }
@@ -41,9 +41,9 @@
 where
 	T: Typed + Clone,
 {
-	fn evaluate_arg(&self, s: State, _ctx: Context, _tailstrict: bool) -> Result<LazyVal> {
+	fn evaluate_arg(&self, s: State, _ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {
 		let val = T::into_untyped(self.clone(), s)?;
-		Ok(LazyVal::new_resolved(val))
+		Ok(Thunk::evaluated(val))
 	}
 }
 
@@ -53,18 +53,18 @@
 	Val(Val),
 }
 impl ArgLike for TlaArg {
-	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<LazyVal> {
+	fn evaluate_arg(&self, s: State, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
 		match self {
-			TlaArg::String(s) => Ok(LazyVal::new_resolved(Val::Str(s.clone()))),
+			TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(s.clone()))),
 			TlaArg::Code(code) => Ok(if tailstrict {
-				LazyVal::new_resolved(evaluate(s, ctx, code)?)
+				Thunk::evaluated(evaluate(s, ctx, code)?)
 			} else {
-				LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+				Thunk::new(tb!(EvaluateThunk {
 					ctx,
 					expr: code.clone(),
-				})))
+				}))
 			}),
-			TlaArg::Val(val) => Ok(LazyVal::new_resolved(val.clone())),
+			TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),
 		}
 	}
 }
@@ -83,14 +83,14 @@
 		s: State,
 		ctx: Context,
 		tailstrict: bool,
-		handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 	) -> Result<()>;
 	fn named_iter(
 		&self,
 		s: State,
 		ctx: Context,
 		tailstrict: bool,
-		handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 	) -> Result<()>;
 	fn named_names(&self, handler: &mut dyn FnMut(&IStr));
 }
@@ -105,18 +105,18 @@
 		s: State,
 		ctx: Context,
 		tailstrict: bool,
-		handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		for (id, arg) in self.unnamed.iter().enumerate() {
 			handler(
 				id,
 				if tailstrict {
-					LazyVal::new_resolved(evaluate(s.clone(), ctx.clone(), arg)?)
+					Thunk::evaluated(evaluate(s.clone(), ctx.clone(), arg)?)
 				} else {
-					LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+					Thunk::new(tb!(EvaluateThunk {
 						ctx: ctx.clone(),
 						expr: arg.clone(),
-					})))
+					}))
 				},
 			)?;
 		}
@@ -128,18 +128,18 @@
 		s: State,
 		ctx: Context,
 		tailstrict: bool,
-		handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		for (name, arg) in &self.named {
 			handler(
 				name,
 				if tailstrict {
-					LazyVal::new_resolved(evaluate(s.clone(), ctx.clone(), arg)?)
+					Thunk::evaluated(evaluate(s.clone(), ctx.clone(), arg)?)
 				} else {
-					LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+					Thunk::new(tb!(EvaluateThunk {
 						ctx: ctx.clone(),
 						expr: arg.clone(),
-					})))
+					}))
 				},
 			)?;
 		}
@@ -164,7 +164,7 @@
 		_s: State,
 		_ctx: Context,
 		_tailstrict: bool,
-		_handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		Ok(())
 	}
@@ -174,7 +174,7 @@
 		s: State,
 		ctx: Context,
 		tailstrict: bool,
-		handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		for (name, value) in self.iter() {
 			handler(
@@ -205,7 +205,7 @@
 				s: State,
 				ctx: Context,
 				tailstrict: bool,
-				handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+				handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 			) -> Result<()> {
 				let mut i = 0usize;
 				let ($($gen,)*) = self;
@@ -220,7 +220,7 @@
 				_s: State,
 				_ctx: Context,
 				_tailstrict: bool,
-				_handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+				_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 			) -> Result<()> {
 				Ok(())
 			}
@@ -236,7 +236,7 @@
 				_s: State,
 				_ctx: Context,
 				_tailstrict: bool,
-				_handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+				_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 			) -> Result<()> {
 				Ok(())
 			}
@@ -246,7 +246,7 @@
 				s: State,
 				ctx: Context,
 				tailstrict: bool,
-				handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+				handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 			) -> Result<()> {
 				let ($($gen,)*) = self;
 				$(
@@ -285,7 +285,7 @@
 		_s: State,
 		_ctx: Context,
 		_tailstrict: bool,
-		_handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,
+		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		Ok(())
 	}
@@ -295,7 +295,7 @@
 		_s: State,
 		_ctx: Context,
 		_tailstrict: bool,
-		_handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
+		_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		Ok(())
 	}
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -9,20 +9,21 @@
 use crate::{
 	error::{Error::*, Result},
 	evaluate_named,
-	gc::{GcHashMap, TraceBox},
-	throw,
-	val::LazyValValue,
-	Context, FutureWrapper, LazyVal, State, Val,
+	gc::GcHashMap,
+	tb, throw,
+	val::ThunkValue,
+	Context, Pending, State, Thunk, Val,
 };
 
 #[derive(Trace)]
-struct EvaluateNamedLazyVal {
-	ctx: FutureWrapper<Context>,
+struct EvaluateNamedThunk {
+	ctx: Pending<Context>,
 	name: IStr,
 	value: LocExpr,
 }
 
-impl LazyValValue for EvaluateNamedLazyVal {
+impl ThunkValue for EvaluateNamedThunk {
+	type Output = Val;
 	fn get(self: Box<Self>, s: State) -> Result<Val> {
 		evaluate_named(s, self.ctx.unwrap(), &self.value, self.name)
 	}
@@ -83,11 +84,11 @@
 
 			defaults.insert(
 				param.0.clone(),
-				LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
+				Thunk::new(tb!(EvaluateNamedThunk {
 					ctx: fctx.clone(),
 					name: param.0.clone(),
 					value: param.1.clone().expect("default exists"),
-				}))),
+				})),
 			);
 			filled_args += 1;
 		}
@@ -131,7 +132,7 @@
 	params: &[BuiltinParam],
 	args: &dyn ArgsLike,
 	tailstrict: bool,
-) -> Result<GcHashMap<BuiltinParamName, LazyVal>> {
+) -> Result<GcHashMap<BuiltinParamName, Thunk<Val>>> {
 	let mut passed_args = GcHashMap::with_capacity(params.len());
 	if args.unnamed_len() > params.len() {
 		throw!(TooManyArgsFunctionHas(params.len()))
@@ -191,7 +192,8 @@
 pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {
 	#[derive(Trace)]
 	struct DependsOnUnbound(IStr);
-	impl LazyValValue for DependsOnUnbound {
+	impl ThunkValue for DependsOnUnbound {
+		type Output = Val;
 		fn get(self: Box<Self>, _: State) -> Result<Val> {
 			Err(FunctionParameterNotBoundInCall(self.0.clone()).into())
 		}
@@ -205,16 +207,16 @@
 		if let Some(v) = &param.1 {
 			bindings.insert(
 				param.0.clone(),
-				LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
+				Thunk::new(tb!(EvaluateNamedThunk {
 					ctx: fctx.clone(),
 					name: param.0.clone(),
 					value: v.clone(),
-				}))),
+				})),
 			);
 		} else {
 			bindings.insert(
 				param.0.clone(),
-				LazyVal::new(TraceBox(Box::new(DependsOnUnbound(param.0.clone())))),
+				Thunk::new(tb!(DependsOnUnbound(param.0.clone()))),
 			);
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -10,8 +10,15 @@
 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
 #[derive(Debug, Clone)]
 pub struct TraceBox<T: ?Sized>(pub Box<T>);
+#[macro_export]
+macro_rules! tb {
+	($v:expr) => {
+		$crate::gc::TraceBox(Box::new($v))
+	};
+}
 
 impl<T: ?Sized + Trace> Trace for TraceBox<T> {
 	fn trace(&self, tracer: &mut Tracer) {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -58,7 +58,7 @@
 use jrsonnet_parser::*;
 pub use obj::*;
 use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
-pub use val::{LazyVal, ManifestFormat, Val};
+pub use val::{ManifestFormat, Thunk, Val};
 
 pub trait Bindable: Trace + 'static {
 	fn bind(
@@ -66,13 +66,13 @@
 		s: State,
 		this: Option<ObjValue>,
 		super_obj: Option<ObjValue>,
-	) -> Result<LazyVal>;
+	) -> Result<Thunk<Val>>;
 }
 
 #[derive(Clone, Trace)]
 pub enum LazyBinding {
 	Bindable(Cc<TraceBox<dyn Bindable>>),
-	Bound(LazyVal),
+	Bound(Thunk<Val>),
 }
 
 impl Debug for LazyBinding {
@@ -86,7 +86,7 @@
 		s: State,
 		this: Option<ObjValue>,
 		super_obj: Option<ObjValue>,
-	) -> Result<LazyVal> {
+	) -> Result<Thunk<Val>> {
 		match self {
 			Self::Bindable(v) => v.bind(s, this, super_obj),
 			Self::Bound(v) => Ok(v.clone()),
@@ -343,7 +343,7 @@
 		let globals = &self.settings().globals;
 		let mut new_bindings = GcHashMap::with_capacity(globals.len());
 		for (name, value) in globals.iter() {
-			new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));
+			new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));
 		}
 		Context::new().extend_bound(new_bindings)
 	}
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -1,27 +1,27 @@
 use gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 
-use crate::{GcHashMap, LazyVal};
+use crate::{GcHashMap, Thunk, Val};
 
 #[derive(Trace)]
 #[force_tracking]
 pub struct LayeredHashMapInternals {
 	parent: Option<LayeredHashMap>,
-	current: GcHashMap<IStr, LazyVal>,
+	current: GcHashMap<IStr, Thunk<Val>>,
 }
 
 #[derive(Trace)]
 pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
 
 impl LayeredHashMap {
-	pub fn extend(self, new_layer: GcHashMap<IStr, LazyVal>) -> Self {
+	pub fn extend(self, new_layer: GcHashMap<IStr, Thunk<Val>>) -> Self {
 		Self(Cc::new(LayeredHashMapInternals {
 			parent: Some(self),
 			current: new_layer,
 		}))
 	}
 
-	pub fn get(&self, key: &IStr) -> Option<&LazyVal> {
+	pub fn get(&self, key: &IStr) -> Option<&Thunk<Val>> {
 		(self.0)
 			.current
 			.get(key)
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, LazyVal, Result, State, 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(LazyVal::new_resolved(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(LazyVal::new_resolved(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/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -15,41 +15,45 @@
 	throw, ObjValue, Result, State,
 };
 
-pub trait LazyValValue: Trace {
-	fn get(self: Box<Self>, s: State) -> Result<Val>;
+pub trait ThunkValue: Trace {
+	type Output;
+	fn get(self: Box<Self>, s: State) -> Result<Self::Output>;
 }
 
 #[derive(Trace)]
-enum LazyValInternals {
-	Computed(Val),
+enum ThunkInner<T> {
+	Computed(T),
 	Errored(LocError),
-	Waiting(TraceBox<dyn LazyValValue>),
+	Waiting(TraceBox<dyn ThunkValue<Output = T>>),
 	Pending,
 }
 
 #[allow(clippy::module_name_repetitions)]
 #[derive(Clone, Trace)]
-pub struct LazyVal(Cc<RefCell<LazyValInternals>>);
-impl LazyVal {
-	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {
-		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))
+pub struct Thunk<T>(Cc<RefCell<ThunkInner<T>>>);
+impl<T> Thunk<T>
+where
+	T: Clone + Trace,
+{
+	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))
 	}
-	pub fn new_resolved(val: Val) -> Self {
-		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))
+	pub fn evaluated(val: T) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))
 	}
 	pub fn force(&self, s: State) -> Result<()> {
 		self.evaluate(s)?;
 		Ok(())
 	}
-	pub fn evaluate(&self, s: State) -> Result<Val> {
+	pub fn evaluate(&self, s: State) -> Result<T> {
 		match &*self.0.borrow() {
-			LazyValInternals::Computed(v) => return Ok(v.clone()),
-			LazyValInternals::Errored(e) => return Err(e.clone()),
-			LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),
-			LazyValInternals::Waiting(..) => (),
+			ThunkInner::Computed(v) => return Ok(v.clone()),
+			ThunkInner::Errored(e) => return Err(e.clone()),
+			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
+			ThunkInner::Waiting(..) => (),
 		};
-		let value = if let LazyValInternals::Waiting(value) =
-			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)
+		let value = if let ThunkInner::Waiting(value) =
+			std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)
 		{
 			value
 		} else {
@@ -58,21 +62,21 @@
 		let new_value = match value.0.get(s) {
 			Ok(v) => v,
 			Err(e) => {
-				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());
+				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());
 				return Err(e);
 			}
 		};
-		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());
+		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());
 		Ok(new_value)
 	}
 }
 
-impl Debug for LazyVal {
+impl<T: Debug> Debug for Thunk<T> {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "Lazy")
 	}
 }
-impl PartialEq for LazyVal {
+impl<T> PartialEq for Thunk<T> {
 	fn eq(&self, other: &Self) -> bool {
 		cc_ptr_eq(&self.0, &other.0)
 	}
@@ -142,7 +146,7 @@
 #[force_tracking]
 pub enum ArrValue {
 	Bytes(#[skip_trace] Rc<[u8]>),
-	Lazy(Cc<Vec<LazyVal>>),
+	Lazy(Cc<Vec<Thunk<Val>>>),
 	Eager(Cc<Vec<Val>>),
 	Extended(Box<(Self, Self)>),
 	Range(i32, i32),
@@ -240,13 +244,13 @@
 		}
 	}
 
-	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {
+	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
 		match self {
 			Self::Bytes(i) => i
 				.get(index)
-				.map(|b| LazyVal::new_resolved(Val::Num(f64::from(*b)))),
+				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),
 			Self::Lazy(vec) => vec.get(index).cloned(),
-			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),
+			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),
 			Self::Extended(v) => {
 				let a_len = v.0.len();
 				if a_len > index {
@@ -259,7 +263,7 @@
 				if index >= self.len() {
 					return None;
 				}
-				Some(LazyVal::new_resolved(Val::Num(
+				Some(Thunk::evaluated(Val::Num(
 					((*a as isize) + index as isize) as f64,
 				)))
 			}
@@ -343,11 +347,11 @@
 		})
 	}
 
-	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
+	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {
 		(0..self.len()).map(move |idx| match self {
-			Self::Bytes(b) => LazyVal::new_resolved(Val::Num(f64::from(b[idx]))),
+			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),
 			Self::Lazy(l) => l[idx].clone(),
-			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
+			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),
 			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {
 				self.get_lazy(idx).expect("idx < len")
 			}
@@ -391,8 +395,8 @@
 	}
 }
 
-impl From<Vec<LazyVal>> for ArrValue {
-	fn from(v: Vec<LazyVal>) -> Self {
+impl From<Vec<Thunk<Val>>> for ArrValue {
+	fn from(v: Vec<Thunk<Val>>) -> Self {
 		Self::Lazy(Cc::new(v))
 	}
 }
modifiedcrates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ b/crates/jrsonnet-evaluator/tests/builtin.rs
@@ -7,6 +7,7 @@
 	error::Result,
 	function::{builtin, builtin::Builtin, CallLocation, FuncVal},
 	gc::TraceBox,
+	tb,
 	typed::Typed,
 	State, Val,
 };
@@ -70,9 +71,7 @@
 
 #[builtin]
 fn curry_add(a: u32) -> Result<FuncVal> {
-	Ok(FuncVal::Builtin(Cc::new(TraceBox(Box::new(curried_add {
-		a,
-	})))))
+	Ok(FuncVal::Builtin(Cc::new(tb!(curried_add { a }))))
 }
 
 #[test]
modifiedcrates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, FuncVal},
-	throw_runtime, LazyVal, ObjValueBuilder, State, Val,
+	throw_runtime, ObjValueBuilder, State, Thunk, Val,
 };
 
 #[macro_export]
@@ -38,7 +38,7 @@
 }
 
 #[builtin]
-fn assert_throw(s: State, lazy: LazyVal, message: String) -> Result<bool> {
+fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
 	match lazy.evaluate(s) {
 		Ok(_) => {
 			throw_runtime!("expected argument to throw on evaluation, but it returned instead")
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -150,7 +150,7 @@
 			return Ok(Self::State);
 		} else if type_is_path(ty, "CallLocation").is_some() {
 			return Ok(Self::Location);
-		} else if type_is_path(ty, "LazyVal").is_some() {
+		} else if type_is_path(ty, "Thunk").is_some() {
 			return Ok(Self::Lazy {
 				is_option: false,
 				name: ident.to_string(),
@@ -163,7 +163,7 @@
 		}
 
 		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {
-			if type_is_path(ty, "LazyVal").is_some() {
+			if type_is_path(ty, "Thunk").is_some() {
 				return Ok(Self::Lazy {
 					is_option: true,
 					name: ident.to_string(),
modifiedcrates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -6,6 +6,9 @@
 license = "MIT"
 edition = "2021"
 
+[features]
+exp-destruct = []
+
 [dependencies]
 jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
 
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -179,10 +179,44 @@
 
 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, PartialEq, Trace)]
-pub struct BindSpec {
-	pub name: IStr,
-	pub params: Option<ParamsDesc>,
-	pub value: LocExpr,
+pub enum DestructRest {
+	/// ...rest
+	Keep(IStr),
+	/// ...
+	Drop,
+}
+
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[derive(Debug, Clone, PartialEq, Trace)]
+pub enum Destruct {
+	Full(IStr),
+	#[cfg(feature = "exp-destruct")]
+	Skip,
+	#[cfg(feature = "exp-destruct")]
+	Array {
+		start: Vec<Destruct>,
+		rest: Option<DestructRest>,
+		end: Vec<Destruct>,
+	},
+	#[cfg(feature = "exp-destruct")]
+	Object {
+		fields: Vec<(IStr, Option<Destruct>)>,
+		rest: Option<DestructRest>,
+	},
+}
+
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[derive(Debug, Clone, PartialEq, Trace)]
+pub enum BindSpec {
+	Field {
+		into: Destruct,
+		value: LocExpr,
+	},
+	Function {
+		name: IStr,
+		params: ParamsDesc,
+		value: LocExpr,
+	},
 }
 
 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -55,18 +55,18 @@
 
 		/// Reserved word followed by any non-alphanumberic
 		rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
-		rule id() = quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")
+		rule id() -> IStr = v:$(quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")) { v.into() }
 
 		rule keyword(id: &'static str) -> ()
 			= ##parse_string_literal(id) end_of_ident()
 
-		pub rule param(s: &ParserSettings) -> expr::Param = name:$(id()) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name.into(), expr) }
+		pub rule param(s: &ParserSettings) -> expr::Param = name:id() expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr) }
 		pub rule params(s: &ParserSettings) -> expr::ParamsDesc
 			= params:param(s) ** comma() comma()? { expr::ParamsDesc(Rc::new(params)) }
 			/ { expr::ParamsDesc(Rc::new(Vec::new())) }
 
 		pub rule arg(s: &ParserSettings) -> (Option<IStr>, LocExpr)
-			= quiet! { name:(s:$(id()) _ "=" _ {s})? expr:expr(s) {(name.map(Into::into), expr)} }
+			= quiet! { name:(s:id() _ "=" _ {s})? expr:expr(s) {(name, expr)} }
 			/ expected!("<argument>")
 
 		pub rule args(s: &ParserSettings) -> expr::ArgsDesc
@@ -89,9 +89,52 @@
 				Ok(expr::ArgsDesc::new(unnamed, named))
 			}
 
+		pub rule destruct_rest() -> expr::DestructRest
+			= "..." into:(_ into:id() {into})? {if let Some(into) = into {
+				expr::DestructRest::Keep(into)
+			} else {expr::DestructRest::Drop}}
+		pub rule destruct_array(s: &ParserSettings) -> expr::Destruct
+			= "[" _ start:destruct(s)**comma() rest:(
+				comma() _ rest:destruct_rest()? end:(
+					comma() end:destruct(s)**comma() (_ comma())? {end}
+					/ comma()? {Vec::new()}
+				) {(rest, end)}
+				/ comma()? {(None, Vec::new())}
+			) _ "]" {?
+				#[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Array {
+					start,
+					rest: rest.0,
+					end: rest.1,
+				});
+				#[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")
+			}
+		pub rule destruct_object(s: &ParserSettings) -> expr::Destruct
+			= "{" _
+				fields:(name:id() _ into:(":" _ into:destruct(s) {into})? {(name, into)})**comma()
+				rest:(
+					comma() rest:destruct_rest()? {rest}
+					/ comma()? {None}
+				)
+			_ "}" {?
+				#[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Object {
+					fields,
+					rest,
+				});
+				#[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")
+			}
+		pub rule destruct(s: &ParserSettings) -> expr::Destruct
+			= v:id() {expr::Destruct::Full(v)}
+			/ "?" {?
+				#[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Skip);
+				#[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")
+			}
+			/ arr:destruct_array(s) {arr}
+			/ obj:destruct_object(s) {obj}
+
 		pub rule bind(s: &ParserSettings) -> expr::BindSpec
-			= name:$(id()) _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: None, value: expr}}
-			/ name:$(id()) _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: Some(params), value: expr}}
+			= into:destruct(s) _ "=" _ expr:expr(s) {expr::BindSpec::Field{into, value: expr}}
+			/ name:id() _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec::Function{name, params, value: expr}}
+
 		pub rule assertion(s: &ParserSettings) -> expr::AssertStmt
 			= keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }
 
@@ -122,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.into())}
 			/ name:string() {expr::FieldName::Fixed(name.into())}
 			/ "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}
 		pub rule visibility() -> expr::Visibility
@@ -167,7 +210,7 @@
 		pub rule ifspec(s: &ParserSettings) -> IfSpecData
 			= keyword("if") _ expr:expr(s) {IfSpecData(expr)}
 		pub rule forspec(s: &ParserSettings) -> ForSpecData
-			= keyword("for") _ id:$(id()) _ keyword("in") _ cond:expr(s) {ForSpecData(id.into(), cond)}
+			= keyword("for") _ id:id() _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}
 		pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>
 			= s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}
 		pub rule local_expr(s: &ParserSettings) -> Expr
@@ -187,9 +230,9 @@
 		pub rule number_expr(s: &ParserSettings) -> Expr
 			= n:number() { expr::Expr::Num(n) }
 		pub rule var_expr(s: &ParserSettings) -> Expr
-			= n:$(id()) { expr::Expr::Var(n.into()) }
+			= n:id() { expr::Expr::Var(n) }
 		pub rule id_loc(s: &ParserSettings) -> LocExpr
-			= a:position!() n:$(id()) b:position!() { LocExpr(Rc::new(expr::Expr::Str(n.into())), ExprLocation(s.file_name.clone(), a,b)) }
+			= a:position!() n:id() b:position!() { LocExpr(Rc::new(expr::Expr::Str(n)), ExprLocation(s.file_name.clone(), a,b)) }
 		pub rule if_then_else_expr(s: &ParserSettings) -> Expr
 			= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{
 				cond,
@@ -212,7 +255,7 @@
 
 			/ quiet!{"$intrinsicThisFile" {Expr::IntrinsicThisFile}}
 			/ quiet!{"$intrinsicId" {Expr::IntrinsicId}}
-			/ quiet!{"$intrinsic(" name:$(id()) ")" {Expr::Intrinsic(name.into())}}
+			/ quiet!{"$intrinsic(" name:id() ")" {Expr::Intrinsic(name)}}
 
 			/ string_expr(s) / number_expr(s)
 			/ array_expr(s)
@@ -693,9 +736,8 @@
 						ObjExtend(
 							el!(Obj(ObjBody::MemberList(vec![])), 0, 2),
 							ObjBody::MemberList(vec![
-								Member::BindStmt(BindSpec {
-									name: "x".into(),
-									params: None,
+								Member::BindStmt(BindSpec::Field {
+									into: Destruct::Full("x".into()),
 									value: el!(Num(1.0), 15, 16)
 								}),
 								Member::Field(FieldMember {