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
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -16,7 +16,7 @@
 	function::CallLocation,
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
-	throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, State, Val,
+	throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, Result, State, Thunk, Val,
 };
 
 #[cfg(not(feature = "exp-preserve-order"))]
@@ -581,7 +581,7 @@
 pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
 impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
 	pub fn value(self, s: State, value: Val) -> Result<()> {
-		self.binding(s, LazyBinding::Bound(LazyVal::new_resolved(value)))
+		self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
 	}
 	pub fn bindable(self, s: State, bindable: TraceBox<dyn Bindable>) -> Result<()> {
 		self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
@@ -604,7 +604,7 @@
 pub struct ExtendBuilder<'v>(&'v mut ObjValue);
 impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
 	pub fn value(self, value: Val) {
-		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)));
+		self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
 	}
 	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
 		self.binding(LazyBinding::Bindable(Cc::new(bindable)));
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_types::ValType;67use crate::{8	cc_ptr_eq,9	error::{Error::*, LocError},10	function::FuncVal,11	gc::TraceBox,12	stdlib::manifest::{13		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,14	},15	throw, ObjValue, Result, State,16};1718pub trait LazyValValue: Trace {19	fn get(self: Box<Self>, s: State) -> Result<Val>;20}2122#[derive(Trace)]23enum LazyValInternals {24	Computed(Val),25	Errored(LocError),26	Waiting(TraceBox<dyn LazyValValue>),27	Pending,28}2930#[allow(clippy::module_name_repetitions)]31#[derive(Clone, Trace)]32pub struct LazyVal(Cc<RefCell<LazyValInternals>>);33impl LazyVal {34	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {35		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))36	}37	pub fn new_resolved(val: Val) -> Self {38		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))39	}40	pub fn force(&self, s: State) -> Result<()> {41		self.evaluate(s)?;42		Ok(())43	}44	pub fn evaluate(&self, s: State) -> Result<Val> {45		match &*self.0.borrow() {46			LazyValInternals::Computed(v) => return Ok(v.clone()),47			LazyValInternals::Errored(e) => return Err(e.clone()),48			LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),49			LazyValInternals::Waiting(..) => (),50		};51		let value = if let LazyValInternals::Waiting(value) =52			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)53		{54			value55		} else {56			unreachable!()57		};58		let new_value = match value.0.get(s) {59			Ok(v) => v,60			Err(e) => {61				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());62				return Err(e);63			}64		};65		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());66		Ok(new_value)67	}68}6970impl Debug for LazyVal {71	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72		write!(f, "Lazy")73	}74}75impl PartialEq for LazyVal {76	fn eq(&self, other: &Self) -> bool {77		cc_ptr_eq(&self.0, &other.0)78	}79}8081#[derive(Clone)]82pub enum ManifestFormat {83	YamlStream(Box<ManifestFormat>),84	Yaml {85		padding: usize,86		#[cfg(feature = "exp-preserve-order")]87		preserve_order: bool,88	},89	Json {90		padding: usize,91		#[cfg(feature = "exp-preserve-order")]92		preserve_order: bool,93	},94	ToString,95	String,96}97impl ManifestFormat {98	#[cfg(feature = "exp-preserve-order")]99	fn preserve_order(&self) -> bool {100		match self {101			ManifestFormat::YamlStream(s) => s.preserve_order(),102			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,103			ManifestFormat::Json { preserve_order, .. } => *preserve_order,104			ManifestFormat::ToString => false,105			ManifestFormat::String => false,106		}107	}108}109110#[derive(Debug, Clone, Trace)]111pub struct Slice {112	pub(crate) inner: ArrValue,113	pub(crate) from: u32,114	pub(crate) to: u32,115	pub(crate) step: u32,116}117impl Slice {118	const fn from(&self) -> usize {119		self.from as usize120	}121	const fn to(&self) -> usize {122		self.to as usize123	}124	const fn step(&self) -> usize {125		self.step as usize126	}127	const fn len(&self) -> usize {128		// TODO: use div_ceil129		let diff = self.to() - self.from();130		let rem = diff % self.step();131		let div = diff / self.step();132133		if rem == 0 {134			div135		} else {136			div + 1137		}138	}139}140141#[derive(Debug, Clone, Trace)]142#[force_tracking]143pub enum ArrValue {144	Bytes(#[skip_trace] Rc<[u8]>),145	Lazy(Cc<Vec<LazyVal>>),146	Eager(Cc<Vec<Val>>),147	Extended(Box<(Self, Self)>),148	Range(i32, i32),149	Slice(Box<Slice>),150	Reversed(Box<Self>),151}152impl ArrValue {153	pub fn new_eager() -> Self {154		Self::Eager(Cc::new(Vec::new()))155	}156157	/// # Panics158	/// If a > b159	pub fn new_range(a: i32, b: i32) -> Self {160		assert!(a <= b);161		Self::Range(a, b)162	}163164	/// # Panics165	/// If passed numbers are incorrect166	#[must_use]167	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {168		let len = self.len();169		let from = from.unwrap_or(0);170		let to = to.unwrap_or(len).min(len);171		let step = step.unwrap_or(1);172		assert!(from < to);173		assert!(step > 0);174175		Self::Slice(Box::new(Slice {176			inner: self,177			from: from as u32,178			to: to as u32,179			step: step as u32,180		}))181	}182183	pub fn len(&self) -> usize {184		match self {185			Self::Bytes(i) => i.len(),186			Self::Lazy(l) => l.len(),187			Self::Eager(e) => e.len(),188			Self::Extended(v) => v.0.len() + v.1.len(),189			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,190			Self::Reversed(i) => i.len(),191			Self::Slice(s) => s.len(),192		}193	}194195	pub fn is_empty(&self) -> bool {196		self.len() == 0197	}198199	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {200		match self {201			Self::Bytes(i) => i202				.get(index)203				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),204			Self::Lazy(vec) => {205				if let Some(v) = vec.get(index) {206					Ok(Some(v.evaluate(s)?))207				} else {208					Ok(None)209				}210			}211			Self::Eager(vec) => Ok(vec.get(index).cloned()),212			Self::Extended(v) => {213				let a_len = v.0.len();214				if a_len > index {215					v.0.get(s, index)216				} else {217					v.1.get(s, index - a_len)218				}219			}220			Self::Range(a, _) => {221				if index >= self.len() {222					return Ok(None);223				}224				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))225			}226			Self::Reversed(v) => {227				let len = v.len();228				if index >= len {229					return Ok(None);230				}231				v.get(s, len - index - 1)232			}233			Self::Slice(v) => {234				let index = v.from() + index * v.step();235				if index >= v.to() {236					return Ok(None);237				}238				v.inner.get(s, index as usize)239			}240		}241	}242243	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {244		match self {245			Self::Bytes(i) => i246				.get(index)247				.map(|b| LazyVal::new_resolved(Val::Num(f64::from(*b)))),248			Self::Lazy(vec) => vec.get(index).cloned(),249			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),250			Self::Extended(v) => {251				let a_len = v.0.len();252				if a_len > index {253					v.0.get_lazy(index)254				} else {255					v.1.get_lazy(index - a_len)256				}257			}258			Self::Range(a, _) => {259				if index >= self.len() {260					return None;261				}262				Some(LazyVal::new_resolved(Val::Num(263					((*a as isize) + index as isize) as f64,264				)))265			}266			Self::Reversed(v) => {267				let len = v.len();268				if index >= len {269					return None;270				}271				v.get_lazy(len - index - 1)272			}273			Self::Slice(s) => {274				let index = s.from() + index * s.step();275				if index >= s.to() {276					return None;277				}278				s.inner.get_lazy(index as usize)279			}280		}281	}282283	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {284		Ok(match self {285			Self::Bytes(i) => {286				let mut out = Vec::with_capacity(i.len());287				for v in i.iter() {288					out.push(Val::Num(f64::from(*v)));289				}290				Cc::new(out)291			}292			Self::Lazy(vec) => {293				let mut out = Vec::with_capacity(vec.len());294				for item in vec.iter() {295					out.push(item.evaluate(s.clone())?);296				}297				Cc::new(out)298			}299			Self::Eager(vec) => vec.clone(),300			Self::Extended(_v) => {301				let mut out = Vec::with_capacity(self.len());302				for item in self.iter(s) {303					out.push(item?);304				}305				Cc::new(out)306			}307			Self::Range(a, b) => {308				let mut out = Vec::with_capacity(self.len());309				for i in *a..*b {310					out.push(Val::Num(f64::from(i)));311				}312				Cc::new(out)313			}314			Self::Reversed(r) => {315				let mut r = r.evaluated(s)?;316				Cc::update_with(&mut r, |v| v.reverse());317				r318			}319			Self::Slice(v) => {320				let mut out = Vec::with_capacity(v.inner.len());321				for v in v322					.inner323					.iter_lazy()324					.skip(v.from())325					.take(v.to() - v.from())326					.step_by(v.step())327				{328					out.push(v.evaluate(s.clone())?);329				}330				Cc::new(out)331			}332		})333	}334335	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {336		(0..self.len()).map(move |idx| match self {337			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),338			Self::Lazy(l) => l[idx].evaluate(s.clone()),339			Self::Eager(e) => Ok(e[idx].clone()),340			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {341				self.get(s.clone(), idx).map(|e| e.expect("idx < len"))342			}343		})344	}345346	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {347		(0..self.len()).map(move |idx| match self {348			Self::Bytes(b) => LazyVal::new_resolved(Val::Num(f64::from(b[idx]))),349			Self::Lazy(l) => l[idx].clone(),350			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),351			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {352				self.get_lazy(idx).expect("idx < len")353			}354		})355	}356357	#[must_use]358	pub fn reversed(self) -> Self {359		Self::Reversed(Box::new(self))360	}361362	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {363		let mut out = Vec::with_capacity(self.len());364365		for value in self.iter(s) {366			out.push(mapper(value?)?);367		}368369		Ok(Self::Eager(Cc::new(out)))370	}371372	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {373		let mut out = Vec::with_capacity(self.len());374375		for value in self.iter(s) {376			let value = value?;377			if filter(&value)? {378				out.push(value);379			}380		}381382		Ok(Self::Eager(Cc::new(out)))383	}384385	pub fn ptr_eq(a: &Self, b: &Self) -> bool {386		match (a, b) {387			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),388			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),389			_ => false,390		}391	}392}393394impl From<Vec<LazyVal>> for ArrValue {395	fn from(v: Vec<LazyVal>) -> Self {396		Self::Lazy(Cc::new(v))397	}398}399400impl From<Vec<Val>> for ArrValue {401	fn from(v: Vec<Val>) -> Self {402		Self::Eager(Cc::new(v))403	}404}405406#[allow(clippy::module_name_repetitions)]407pub enum IndexableVal {408	Str(IStr),409	Arr(ArrValue),410}411412#[derive(Debug, Clone, Trace)]413pub enum Val {414	Bool(bool),415	Null,416	Str(IStr),417	Num(f64),418	Arr(ArrValue),419	Obj(ObjValue),420	Func(FuncVal),421}422423impl Val {424	pub const fn as_bool(&self) -> Option<bool> {425		match self {426			Val::Bool(v) => Some(*v),427			_ => None,428		}429	}430	pub const fn as_null(&self) -> Option<()> {431		match self {432			Val::Null => Some(()),433			_ => None,434		}435	}436	pub fn as_str(&self) -> Option<IStr> {437		match self {438			Val::Str(s) => Some(s.clone()),439			_ => None,440		}441	}442	pub const fn as_num(&self) -> Option<f64> {443		match self {444			Val::Num(n) => Some(*n),445			_ => None,446		}447	}448	pub fn as_arr(&self) -> Option<ArrValue> {449		match self {450			Val::Arr(a) => Some(a.clone()),451			_ => None,452		}453	}454	pub fn as_obj(&self) -> Option<ObjValue> {455		match self {456			Val::Obj(o) => Some(o.clone()),457			_ => None,458		}459	}460	pub fn as_func(&self) -> Option<FuncVal> {461		match self {462			Val::Func(f) => Some(f.clone()),463			_ => None,464		}465	}466467	/// Creates `Val::Num` after checking for numeric overflow.468	/// As numbers are `f64`, we can just check for their finity.469	pub fn new_checked_num(num: f64) -> Result<Self> {470		if num.is_finite() {471			Ok(Self::Num(num))472		} else {473			throw!(RuntimeError("overflow".into()))474		}475	}476477	pub const fn value_type(&self) -> ValType {478		match self {479			Self::Str(..) => ValType::Str,480			Self::Num(..) => ValType::Num,481			Self::Arr(..) => ValType::Arr,482			Self::Obj(..) => ValType::Obj,483			Self::Bool(_) => ValType::Bool,484			Self::Null => ValType::Null,485			Self::Func(..) => ValType::Func,486		}487	}488489	pub fn to_string(&self, s: State) -> Result<IStr> {490		Ok(match self {491			Self::Bool(true) => "true".into(),492			Self::Bool(false) => "false".into(),493			Self::Null => "null".into(),494			Self::Str(s) => s.clone(),495			v => manifest_json_ex(496				s,497				v,498				&ManifestJsonOptions {499					padding: "",500					mtype: ManifestType::ToString,501					newline: "\n",502					key_val_sep: ": ",503					#[cfg(feature = "exp-preserve-order")]504					preserve_order: false,505				},506			)?507			.into(),508		})509	}510511	/// Expects value to be object, outputs (key, manifested value) pairs512	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {513		let obj = match self {514			Self::Obj(obj) => obj,515			_ => throw!(MultiManifestOutputIsNotAObject),516		};517		let keys = obj.fields(518			#[cfg(feature = "exp-preserve-order")]519			ty.preserve_order(),520		);521		let mut out = Vec::with_capacity(keys.len());522		for key in keys {523			let value = obj524				.get(s.clone(), key.clone())?525				.expect("item in object")526				.manifest(s.clone(), ty)?;527			out.push((key, value));528		}529		Ok(out)530	}531532	/// Expects value to be array, outputs manifested values533	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {534		let arr = match self {535			Self::Arr(a) => a,536			_ => throw!(StreamManifestOutputIsNotAArray),537		};538		let mut out = Vec::with_capacity(arr.len());539		for i in arr.iter(s.clone()) {540			out.push(i?.manifest(s.clone(), ty)?);541		}542		Ok(out)543	}544545	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {546		Ok(match ty {547			ManifestFormat::YamlStream(format) => {548				let arr = match self {549					Self::Arr(a) => a,550					_ => throw!(StreamManifestOutputIsNotAArray),551				};552				let mut out = String::new();553554				match format as &ManifestFormat {555					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),556					ManifestFormat::String => throw!(StreamManifestCannotNestString),557					_ => {}558				};559560				if !arr.is_empty() {561					for v in arr.iter(s.clone()) {562						out.push_str("---\n");563						out.push_str(&v?.manifest(s.clone(), format)?);564						out.push('\n');565					}566					out.push_str("...");567				}568569				out.into()570			}571			ManifestFormat::Yaml {572				padding,573				#[cfg(feature = "exp-preserve-order")]574				preserve_order,575			} => self.to_yaml(576				s,577				*padding,578				#[cfg(feature = "exp-preserve-order")]579				*preserve_order,580			)?,581			ManifestFormat::Json {582				padding,583				#[cfg(feature = "exp-preserve-order")]584				preserve_order,585			} => self.to_json(586				s,587				*padding,588				#[cfg(feature = "exp-preserve-order")]589				*preserve_order,590			)?,591			ManifestFormat::ToString => self.to_string(s)?,592			ManifestFormat::String => match self {593				Self::Str(s) => s.clone(),594				_ => throw!(StringManifestOutputIsNotAString),595			},596		})597	}598599	/// For manifestification600	pub fn to_json(601		&self,602		s: State,603		padding: usize,604		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,605	) -> Result<IStr> {606		manifest_json_ex(607			s,608			self,609			&ManifestJsonOptions {610				padding: &" ".repeat(padding),611				mtype: if padding == 0 {612					ManifestType::Minify613				} else {614					ManifestType::Manifest615				},616				newline: "\n",617				key_val_sep: ": ",618				#[cfg(feature = "exp-preserve-order")]619				preserve_order,620			},621		)622		.map(Into::into)623	}624625	/// Calls `std.manifestJson`626	pub fn to_std_json(627		&self,628		s: State,629		padding: usize,630		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,631	) -> Result<Rc<str>> {632		manifest_json_ex(633			s,634			self,635			&ManifestJsonOptions {636				padding: &" ".repeat(padding),637				mtype: ManifestType::Std,638				newline: "\n",639				key_val_sep: ": ",640				#[cfg(feature = "exp-preserve-order")]641				preserve_order,642			},643		)644		.map(Into::into)645	}646647	pub fn to_yaml(648		&self,649		s: State,650		padding: usize,651		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,652	) -> Result<IStr> {653		let padding = &" ".repeat(padding);654		manifest_yaml_ex(655			s,656			self,657			&ManifestYamlOptions {658				padding,659				arr_element_padding: padding,660				quote_keys: false,661				#[cfg(feature = "exp-preserve-order")]662				preserve_order,663			},664		)665		.map(Into::into)666	}667	pub fn into_indexable(self) -> Result<IndexableVal> {668		Ok(match self {669			Val::Str(s) => IndexableVal::Str(s),670			Val::Arr(arr) => IndexableVal::Arr(arr),671			_ => throw!(ValueIsNotIndexable(self.value_type())),672		})673	}674}675676const fn is_function_like(val: &Val) -> bool {677	matches!(val, Val::Func(_))678}679680/// Native implementation of `std.primitiveEquals`681pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {682	Ok(match (val_a, val_b) {683		(Val::Bool(a), Val::Bool(b)) => a == b,684		(Val::Null, Val::Null) => true,685		(Val::Str(a), Val::Str(b)) => a == b,686		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,687		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(688			"primitiveEquals operates on primitive types, got array".into(),689		)),690		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(691			"primitiveEquals operates on primitive types, got object".into(),692		)),693		(a, b) if is_function_like(a) && is_function_like(b) => {694			throw!(RuntimeError("cannot test equality of functions".into()))695		}696		(_, _) => false,697	})698}699700/// Native implementation of `std.equals`701pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {702	if val_a.value_type() != val_b.value_type() {703		return Ok(false);704	}705	match (val_a, val_b) {706		(Val::Arr(a), Val::Arr(b)) => {707			if ArrValue::ptr_eq(a, b) {708				return Ok(true);709			}710			if a.len() != b.len() {711				return Ok(false);712			}713			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {714				if !equals(s.clone(), &a?, &b?)? {715					return Ok(false);716				}717			}718			Ok(true)719		}720		(Val::Obj(a), Val::Obj(b)) => {721			if ObjValue::ptr_eq(a, b) {722				return Ok(true);723			}724			let fields = a.fields(725				#[cfg(feature = "exp-preserve-order")]726				false,727			);728			if fields729				!= b.fields(730					#[cfg(feature = "exp-preserve-order")]731					false,732				) {733				return Ok(false);734			}735			for field in fields {736				if !equals(737					s.clone(),738					&a.get(s.clone(), field.clone())?.expect("field exists"),739					&b.get(s.clone(), field)?.expect("field exists"),740				)? {741					return Ok(false);742				}743			}744			Ok(true)745		}746		(a, b) => Ok(primitive_equals(a, b)?),747	}748}
after · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_types::ValType;67use crate::{8	cc_ptr_eq,9	error::{Error::*, LocError},10	function::FuncVal,11	gc::TraceBox,12	stdlib::manifest::{13		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,14	},15	throw, ObjValue, Result, State,16};1718pub trait ThunkValue: Trace {19	type Output;20	fn get(self: Box<Self>, s: State) -> Result<Self::Output>;21}2223#[derive(Trace)]24enum ThunkInner<T> {25	Computed(T),26	Errored(LocError),27	Waiting(TraceBox<dyn ThunkValue<Output = T>>),28	Pending,29}3031#[allow(clippy::module_name_repetitions)]32#[derive(Clone, Trace)]33pub struct Thunk<T>(Cc<RefCell<ThunkInner<T>>>);34impl<T> Thunk<T>35where36	T: Clone + Trace,37{38	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {39		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))40	}41	pub fn evaluated(val: T) -> Self {42		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))43	}44	pub fn force(&self, s: State) -> Result<()> {45		self.evaluate(s)?;46		Ok(())47	}48	pub fn evaluate(&self, s: State) -> Result<T> {49		match &*self.0.borrow() {50			ThunkInner::Computed(v) => return Ok(v.clone()),51			ThunkInner::Errored(e) => return Err(e.clone()),52			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),53			ThunkInner::Waiting(..) => (),54		};55		let value = if let ThunkInner::Waiting(value) =56			std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)57		{58			value59		} else {60			unreachable!()61		};62		let new_value = match value.0.get(s) {63			Ok(v) => v,64			Err(e) => {65				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());66				return Err(e);67			}68		};69		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());70		Ok(new_value)71	}72}7374impl<T: Debug> Debug for Thunk<T> {75	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {76		write!(f, "Lazy")77	}78}79impl<T> PartialEq for Thunk<T> {80	fn eq(&self, other: &Self) -> bool {81		cc_ptr_eq(&self.0, &other.0)82	}83}8485#[derive(Clone)]86pub enum ManifestFormat {87	YamlStream(Box<ManifestFormat>),88	Yaml {89		padding: usize,90		#[cfg(feature = "exp-preserve-order")]91		preserve_order: bool,92	},93	Json {94		padding: usize,95		#[cfg(feature = "exp-preserve-order")]96		preserve_order: bool,97	},98	ToString,99	String,100}101impl ManifestFormat {102	#[cfg(feature = "exp-preserve-order")]103	fn preserve_order(&self) -> bool {104		match self {105			ManifestFormat::YamlStream(s) => s.preserve_order(),106			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,107			ManifestFormat::Json { preserve_order, .. } => *preserve_order,108			ManifestFormat::ToString => false,109			ManifestFormat::String => false,110		}111	}112}113114#[derive(Debug, Clone, Trace)]115pub struct Slice {116	pub(crate) inner: ArrValue,117	pub(crate) from: u32,118	pub(crate) to: u32,119	pub(crate) step: u32,120}121impl Slice {122	const fn from(&self) -> usize {123		self.from as usize124	}125	const fn to(&self) -> usize {126		self.to as usize127	}128	const fn step(&self) -> usize {129		self.step as usize130	}131	const fn len(&self) -> usize {132		// TODO: use div_ceil133		let diff = self.to() - self.from();134		let rem = diff % self.step();135		let div = diff / self.step();136137		if rem == 0 {138			div139		} else {140			div + 1141		}142	}143}144145#[derive(Debug, Clone, Trace)]146#[force_tracking]147pub enum ArrValue {148	Bytes(#[skip_trace] Rc<[u8]>),149	Lazy(Cc<Vec<Thunk<Val>>>),150	Eager(Cc<Vec<Val>>),151	Extended(Box<(Self, Self)>),152	Range(i32, i32),153	Slice(Box<Slice>),154	Reversed(Box<Self>),155}156impl ArrValue {157	pub fn new_eager() -> Self {158		Self::Eager(Cc::new(Vec::new()))159	}160161	/// # Panics162	/// If a > b163	pub fn new_range(a: i32, b: i32) -> Self {164		assert!(a <= b);165		Self::Range(a, b)166	}167168	/// # Panics169	/// If passed numbers are incorrect170	#[must_use]171	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {172		let len = self.len();173		let from = from.unwrap_or(0);174		let to = to.unwrap_or(len).min(len);175		let step = step.unwrap_or(1);176		assert!(from < to);177		assert!(step > 0);178179		Self::Slice(Box::new(Slice {180			inner: self,181			from: from as u32,182			to: to as u32,183			step: step as u32,184		}))185	}186187	pub fn len(&self) -> usize {188		match self {189			Self::Bytes(i) => i.len(),190			Self::Lazy(l) => l.len(),191			Self::Eager(e) => e.len(),192			Self::Extended(v) => v.0.len() + v.1.len(),193			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,194			Self::Reversed(i) => i.len(),195			Self::Slice(s) => s.len(),196		}197	}198199	pub fn is_empty(&self) -> bool {200		self.len() == 0201	}202203	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {204		match self {205			Self::Bytes(i) => i206				.get(index)207				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),208			Self::Lazy(vec) => {209				if let Some(v) = vec.get(index) {210					Ok(Some(v.evaluate(s)?))211				} else {212					Ok(None)213				}214			}215			Self::Eager(vec) => Ok(vec.get(index).cloned()),216			Self::Extended(v) => {217				let a_len = v.0.len();218				if a_len > index {219					v.0.get(s, index)220				} else {221					v.1.get(s, index - a_len)222				}223			}224			Self::Range(a, _) => {225				if index >= self.len() {226					return Ok(None);227				}228				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))229			}230			Self::Reversed(v) => {231				let len = v.len();232				if index >= len {233					return Ok(None);234				}235				v.get(s, len - index - 1)236			}237			Self::Slice(v) => {238				let index = v.from() + index * v.step();239				if index >= v.to() {240					return Ok(None);241				}242				v.inner.get(s, index as usize)243			}244		}245	}246247	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {248		match self {249			Self::Bytes(i) => i250				.get(index)251				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),252			Self::Lazy(vec) => vec.get(index).cloned(),253			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),254			Self::Extended(v) => {255				let a_len = v.0.len();256				if a_len > index {257					v.0.get_lazy(index)258				} else {259					v.1.get_lazy(index - a_len)260				}261			}262			Self::Range(a, _) => {263				if index >= self.len() {264					return None;265				}266				Some(Thunk::evaluated(Val::Num(267					((*a as isize) + index as isize) as f64,268				)))269			}270			Self::Reversed(v) => {271				let len = v.len();272				if index >= len {273					return None;274				}275				v.get_lazy(len - index - 1)276			}277			Self::Slice(s) => {278				let index = s.from() + index * s.step();279				if index >= s.to() {280					return None;281				}282				s.inner.get_lazy(index as usize)283			}284		}285	}286287	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {288		Ok(match self {289			Self::Bytes(i) => {290				let mut out = Vec::with_capacity(i.len());291				for v in i.iter() {292					out.push(Val::Num(f64::from(*v)));293				}294				Cc::new(out)295			}296			Self::Lazy(vec) => {297				let mut out = Vec::with_capacity(vec.len());298				for item in vec.iter() {299					out.push(item.evaluate(s.clone())?);300				}301				Cc::new(out)302			}303			Self::Eager(vec) => vec.clone(),304			Self::Extended(_v) => {305				let mut out = Vec::with_capacity(self.len());306				for item in self.iter(s) {307					out.push(item?);308				}309				Cc::new(out)310			}311			Self::Range(a, b) => {312				let mut out = Vec::with_capacity(self.len());313				for i in *a..*b {314					out.push(Val::Num(f64::from(i)));315				}316				Cc::new(out)317			}318			Self::Reversed(r) => {319				let mut r = r.evaluated(s)?;320				Cc::update_with(&mut r, |v| v.reverse());321				r322			}323			Self::Slice(v) => {324				let mut out = Vec::with_capacity(v.inner.len());325				for v in v326					.inner327					.iter_lazy()328					.skip(v.from())329					.take(v.to() - v.from())330					.step_by(v.step())331				{332					out.push(v.evaluate(s.clone())?);333				}334				Cc::new(out)335			}336		})337	}338339	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {340		(0..self.len()).map(move |idx| match self {341			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),342			Self::Lazy(l) => l[idx].evaluate(s.clone()),343			Self::Eager(e) => Ok(e[idx].clone()),344			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {345				self.get(s.clone(), idx).map(|e| e.expect("idx < len"))346			}347		})348	}349350	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {351		(0..self.len()).map(move |idx| match self {352			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),353			Self::Lazy(l) => l[idx].clone(),354			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),355			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {356				self.get_lazy(idx).expect("idx < len")357			}358		})359	}360361	#[must_use]362	pub fn reversed(self) -> Self {363		Self::Reversed(Box::new(self))364	}365366	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {367		let mut out = Vec::with_capacity(self.len());368369		for value in self.iter(s) {370			out.push(mapper(value?)?);371		}372373		Ok(Self::Eager(Cc::new(out)))374	}375376	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {377		let mut out = Vec::with_capacity(self.len());378379		for value in self.iter(s) {380			let value = value?;381			if filter(&value)? {382				out.push(value);383			}384		}385386		Ok(Self::Eager(Cc::new(out)))387	}388389	pub fn ptr_eq(a: &Self, b: &Self) -> bool {390		match (a, b) {391			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),392			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),393			_ => false,394		}395	}396}397398impl From<Vec<Thunk<Val>>> for ArrValue {399	fn from(v: Vec<Thunk<Val>>) -> Self {400		Self::Lazy(Cc::new(v))401	}402}403404impl From<Vec<Val>> for ArrValue {405	fn from(v: Vec<Val>) -> Self {406		Self::Eager(Cc::new(v))407	}408}409410#[allow(clippy::module_name_repetitions)]411pub enum IndexableVal {412	Str(IStr),413	Arr(ArrValue),414}415416#[derive(Debug, Clone, Trace)]417pub enum Val {418	Bool(bool),419	Null,420	Str(IStr),421	Num(f64),422	Arr(ArrValue),423	Obj(ObjValue),424	Func(FuncVal),425}426427impl Val {428	pub const fn as_bool(&self) -> Option<bool> {429		match self {430			Val::Bool(v) => Some(*v),431			_ => None,432		}433	}434	pub const fn as_null(&self) -> Option<()> {435		match self {436			Val::Null => Some(()),437			_ => None,438		}439	}440	pub fn as_str(&self) -> Option<IStr> {441		match self {442			Val::Str(s) => Some(s.clone()),443			_ => None,444		}445	}446	pub const fn as_num(&self) -> Option<f64> {447		match self {448			Val::Num(n) => Some(*n),449			_ => None,450		}451	}452	pub fn as_arr(&self) -> Option<ArrValue> {453		match self {454			Val::Arr(a) => Some(a.clone()),455			_ => None,456		}457	}458	pub fn as_obj(&self) -> Option<ObjValue> {459		match self {460			Val::Obj(o) => Some(o.clone()),461			_ => None,462		}463	}464	pub fn as_func(&self) -> Option<FuncVal> {465		match self {466			Val::Func(f) => Some(f.clone()),467			_ => None,468		}469	}470471	/// Creates `Val::Num` after checking for numeric overflow.472	/// As numbers are `f64`, we can just check for their finity.473	pub fn new_checked_num(num: f64) -> Result<Self> {474		if num.is_finite() {475			Ok(Self::Num(num))476		} else {477			throw!(RuntimeError("overflow".into()))478		}479	}480481	pub const fn value_type(&self) -> ValType {482		match self {483			Self::Str(..) => ValType::Str,484			Self::Num(..) => ValType::Num,485			Self::Arr(..) => ValType::Arr,486			Self::Obj(..) => ValType::Obj,487			Self::Bool(_) => ValType::Bool,488			Self::Null => ValType::Null,489			Self::Func(..) => ValType::Func,490		}491	}492493	pub fn to_string(&self, s: State) -> Result<IStr> {494		Ok(match self {495			Self::Bool(true) => "true".into(),496			Self::Bool(false) => "false".into(),497			Self::Null => "null".into(),498			Self::Str(s) => s.clone(),499			v => manifest_json_ex(500				s,501				v,502				&ManifestJsonOptions {503					padding: "",504					mtype: ManifestType::ToString,505					newline: "\n",506					key_val_sep: ": ",507					#[cfg(feature = "exp-preserve-order")]508					preserve_order: false,509				},510			)?511			.into(),512		})513	}514515	/// Expects value to be object, outputs (key, manifested value) pairs516	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {517		let obj = match self {518			Self::Obj(obj) => obj,519			_ => throw!(MultiManifestOutputIsNotAObject),520		};521		let keys = obj.fields(522			#[cfg(feature = "exp-preserve-order")]523			ty.preserve_order(),524		);525		let mut out = Vec::with_capacity(keys.len());526		for key in keys {527			let value = obj528				.get(s.clone(), key.clone())?529				.expect("item in object")530				.manifest(s.clone(), ty)?;531			out.push((key, value));532		}533		Ok(out)534	}535536	/// Expects value to be array, outputs manifested values537	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {538		let arr = match self {539			Self::Arr(a) => a,540			_ => throw!(StreamManifestOutputIsNotAArray),541		};542		let mut out = Vec::with_capacity(arr.len());543		for i in arr.iter(s.clone()) {544			out.push(i?.manifest(s.clone(), ty)?);545		}546		Ok(out)547	}548549	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {550		Ok(match ty {551			ManifestFormat::YamlStream(format) => {552				let arr = match self {553					Self::Arr(a) => a,554					_ => throw!(StreamManifestOutputIsNotAArray),555				};556				let mut out = String::new();557558				match format as &ManifestFormat {559					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),560					ManifestFormat::String => throw!(StreamManifestCannotNestString),561					_ => {}562				};563564				if !arr.is_empty() {565					for v in arr.iter(s.clone()) {566						out.push_str("---\n");567						out.push_str(&v?.manifest(s.clone(), format)?);568						out.push('\n');569					}570					out.push_str("...");571				}572573				out.into()574			}575			ManifestFormat::Yaml {576				padding,577				#[cfg(feature = "exp-preserve-order")]578				preserve_order,579			} => self.to_yaml(580				s,581				*padding,582				#[cfg(feature = "exp-preserve-order")]583				*preserve_order,584			)?,585			ManifestFormat::Json {586				padding,587				#[cfg(feature = "exp-preserve-order")]588				preserve_order,589			} => self.to_json(590				s,591				*padding,592				#[cfg(feature = "exp-preserve-order")]593				*preserve_order,594			)?,595			ManifestFormat::ToString => self.to_string(s)?,596			ManifestFormat::String => match self {597				Self::Str(s) => s.clone(),598				_ => throw!(StringManifestOutputIsNotAString),599			},600		})601	}602603	/// For manifestification604	pub fn to_json(605		&self,606		s: State,607		padding: usize,608		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,609	) -> Result<IStr> {610		manifest_json_ex(611			s,612			self,613			&ManifestJsonOptions {614				padding: &" ".repeat(padding),615				mtype: if padding == 0 {616					ManifestType::Minify617				} else {618					ManifestType::Manifest619				},620				newline: "\n",621				key_val_sep: ": ",622				#[cfg(feature = "exp-preserve-order")]623				preserve_order,624			},625		)626		.map(Into::into)627	}628629	/// Calls `std.manifestJson`630	pub fn to_std_json(631		&self,632		s: State,633		padding: usize,634		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,635	) -> Result<Rc<str>> {636		manifest_json_ex(637			s,638			self,639			&ManifestJsonOptions {640				padding: &" ".repeat(padding),641				mtype: ManifestType::Std,642				newline: "\n",643				key_val_sep: ": ",644				#[cfg(feature = "exp-preserve-order")]645				preserve_order,646			},647		)648		.map(Into::into)649	}650651	pub fn to_yaml(652		&self,653		s: State,654		padding: usize,655		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,656	) -> Result<IStr> {657		let padding = &" ".repeat(padding);658		manifest_yaml_ex(659			s,660			self,661			&ManifestYamlOptions {662				padding,663				arr_element_padding: padding,664				quote_keys: false,665				#[cfg(feature = "exp-preserve-order")]666				preserve_order,667			},668		)669		.map(Into::into)670	}671	pub fn into_indexable(self) -> Result<IndexableVal> {672		Ok(match self {673			Val::Str(s) => IndexableVal::Str(s),674			Val::Arr(arr) => IndexableVal::Arr(arr),675			_ => throw!(ValueIsNotIndexable(self.value_type())),676		})677	}678}679680const fn is_function_like(val: &Val) -> bool {681	matches!(val, Val::Func(_))682}683684/// Native implementation of `std.primitiveEquals`685pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {686	Ok(match (val_a, val_b) {687		(Val::Bool(a), Val::Bool(b)) => a == b,688		(Val::Null, Val::Null) => true,689		(Val::Str(a), Val::Str(b)) => a == b,690		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,691		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(692			"primitiveEquals operates on primitive types, got array".into(),693		)),694		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(695			"primitiveEquals operates on primitive types, got object".into(),696		)),697		(a, b) if is_function_like(a) && is_function_like(b) => {698			throw!(RuntimeError("cannot test equality of functions".into()))699		}700		(_, _) => false,701	})702}703704/// Native implementation of `std.equals`705pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {706	if val_a.value_type() != val_b.value_type() {707		return Ok(false);708	}709	match (val_a, val_b) {710		(Val::Arr(a), Val::Arr(b)) => {711			if ArrValue::ptr_eq(a, b) {712				return Ok(true);713			}714			if a.len() != b.len() {715				return Ok(false);716			}717			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {718				if !equals(s.clone(), &a?, &b?)? {719					return Ok(false);720				}721			}722			Ok(true)723		}724		(Val::Obj(a), Val::Obj(b)) => {725			if ObjValue::ptr_eq(a, b) {726				return Ok(true);727			}728			let fields = a.fields(729				#[cfg(feature = "exp-preserve-order")]730				false,731			);732			if fields733				!= b.fields(734					#[cfg(feature = "exp-preserve-order")]735					false,736				) {737				return Ok(false);738			}739			for field in fields {740				if !equals(741					s.clone(),742					&a.get(s.clone(), field.clone())?.expect("field exists"),743					&b.get(s.clone(), field)?.expect("field exists"),744				)? {745					return Ok(false);746				}747			}748			Ok(true)749		}750		(a, b) => Ok(primitive_equals(a, b)?),751	}752}
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 {