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

difftreelog

refactor better rebinding handling

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

15 files changed

modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,34 +4,15 @@
 use jrsonnet_interner::IStr;
 
 use crate::{
-	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, LazyBinding, ObjValue, Pending,
-	Result, State, Thunk, Val,
+	cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result,
+	Thunk, Val,
 };
 
-#[derive(Clone, Trace)]
-pub struct ContextCreator(pub Context, pub Pending<GcHashMap<IStr, LazyBinding>>);
-impl ContextCreator {
-	pub fn create(
-		&self,
-		s: State,
-		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
-	) -> Result<Context> {
-		self.0.clone().extend_unbound(
-			s,
-			self.1.clone().unwrap(),
-			self.0.dollar().clone().or_else(|| this.clone()),
-			this,
-			super_obj,
-		)
-	}
-}
-
 #[derive(Trace)]
 struct ContextInternals {
 	dollar: Option<ObjValue>,
+	sup: Option<ObjValue>,
 	this: Option<ObjValue>,
-	super_obj: Option<ObjValue>,
 	bindings: LayeredHashMap,
 }
 impl Debug for ContextInternals {
@@ -56,14 +37,14 @@
 	}
 
 	pub fn super_obj(&self) -> &Option<ObjValue> {
-		&self.0.super_obj
+		&self.0.sup
 	}
 
 	pub fn new() -> Self {
 		Self(Cc::new(ContextInternals {
 			dollar: None,
 			this: None,
-			super_obj: None,
+			sup: None,
 			bindings: LayeredHashMap::default(),
 		}))
 	}
@@ -92,11 +73,6 @@
 		let mut new_bindings = GcHashMap::with_capacity(1);
 		new_bindings.insert(name, Thunk::evaluated(value));
 		self.extend(new_bindings, None, None, None)
-	}
-
-	#[must_use]
-	pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
-		self.extend(GcHashMap::new(), None, Some(new_this), new_super_obj)
 	}
 
 	#[must_use]
@@ -104,13 +80,13 @@
 		self,
 		new_bindings: GcHashMap<IStr, Thunk<Val>>,
 		new_dollar: Option<ObjValue>,
+		new_sup: Option<ObjValue>,
 		new_this: Option<ObjValue>,
-		new_super_obj: Option<ObjValue>,
 	) -> Self {
 		let ctx = &self.0;
 		let dollar = new_dollar.or_else(|| ctx.dollar.clone());
 		let this = new_this.or_else(|| ctx.this.clone());
-		let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
+		let sup = new_sup.or_else(|| ctx.sup.clone());
 		let bindings = if new_bindings.is_empty() {
 			ctx.bindings.clone()
 		} else {
@@ -118,32 +94,10 @@
 		};
 		Self(Cc::new(ContextInternals {
 			dollar,
+			sup,
 			this,
-			super_obj,
 			bindings,
 		}))
-	}
-	#[must_use]
-	pub fn extend_bound(self, new_bindings: GcHashMap<IStr, Thunk<Val>>) -> Self {
-		let new_this = self.0.this.clone();
-		let new_super_obj = self.0.super_obj.clone();
-		self.extend(new_bindings, None, new_this, new_super_obj)
-	}
-	pub fn extend_unbound(
-		self,
-		s: State,
-		new_bindings: GcHashMap<IStr, LazyBinding>,
-		new_dollar: Option<ObjValue>,
-		new_this: Option<ObjValue>,
-		new_super_obj: Option<ObjValue>,
-	) -> Result<Self> {
-		let this = new_this.or_else(|| self.0.this.clone());
-		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
-		let mut new = GcHashMap::with_capacity(new_bindings.len());
-		for (k, v) in new_bindings.0 {
-			new.insert(k, v.evaluate(s.clone(), this.clone(), super_obj.clone())?);
-		}
-		Ok(self.extend(new, new_dollar, this, super_obj))
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -11,12 +11,13 @@
 	Context, Pending, State, Thunk, Val,
 };
 
+#[allow(clippy::too_many_lines)]
 fn destruct(
 	d: &Destruct,
 	parent: Thunk<Val>,
 	new_bindings: &mut GcHashMap<IStr, Thunk<Val>>,
 ) -> Result<()> {
-	Ok(match d {
+	match d {
 		Destruct::Full(v) => {
 			let old = new_bindings.insert(v.clone(), parent);
 			if old.is_some() {
@@ -157,8 +158,6 @@
 		}
 		#[cfg(feature = "exp-destruct")]
 		Destruct::Object { fields, rest } => {
-			use jrsonnet_parser::DestructRest;
-
 			use crate::{obj::ObjValue, throw_runtime};
 
 			#[derive(Trace)]
@@ -223,7 +222,8 @@
 				}
 			}
 		}
-	})
+	}
+	Ok(())
 }
 
 pub fn evaluate_dest(
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use gcmodule::{Cc, Trace};2use jrsonnet_interner::IStr;3use jrsonnet_parser::{4	ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, ForSpecData, IfSpecData,5	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,6};7use jrsonnet_types::ValType;89use crate::{10	destructure::evaluate_dest,11	error::Error::*,12	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},13	function::{CallLocation, FuncDesc, FuncVal},14	stdlib::{std_slice, BUILTINS},15	tb, throw,16	typed::Typed,17	val::{ArrValue, Thunk, ThunkValue},18	Bindable, Context, ContextCreator, GcHashMap, LazyBinding, ObjValue, ObjValueBuilder,19	ObjectAssertion, Pending, Result, State, Val,20};21pub mod destructure;22pub mod operator;2324#[allow(clippy::too_many_lines)]25pub fn evaluate_binding(b: BindSpec, cctx: ContextCreator) -> Result<(IStr, LazyBinding)> {26	match b {27		BindSpec::Field {28			into: Destruct::Full(name),29			value,30		} => {31			#[derive(Trace)]32			struct BindableNamedThunk {33				this: Option<ObjValue>,34				super_obj: Option<ObjValue>,3536				cctx: ContextCreator,37				name: IStr,38				value: LocExpr,39			}40			impl ThunkValue for BindableNamedThunk {41				type Output = Val;42				fn get(self: Box<Self>, s: State) -> Result<Val> {43					evaluate_named(44						s.clone(),45						self.cctx.create(s, self.this, self.super_obj)?,46						&self.value,47						self.name,48					)49				}50			}5152			#[derive(Trace)]53			struct BindableNamed {54				cctx: ContextCreator,55				name: IStr,56				value: LocExpr,57			}58			impl Bindable for BindableNamed {59				fn bind(60					&self,61					_: State,62					this: Option<ObjValue>,63					super_obj: Option<ObjValue>,64				) -> Result<Thunk<Val>> {65					Ok(Thunk::new(tb!(BindableNamedThunk {66						this,67						super_obj,6869						cctx: self.cctx.clone(),70						name: self.name.clone(),71						value: self.value.clone(),72					})))73				}74			}7576			Ok((77				name.clone(),78				LazyBinding::Bindable(Cc::new(tb!(BindableNamed {79					cctx,80					name: name.clone(),81					value: value.clone(),82				}))),83			))84		}85		#[cfg(feature = "exp-destruct")]86		BindSpec::Field { into: _, .. } => {87			use crate::throw_runtime;88			throw_runtime!("destructuring is not yet supported here")89		}90		BindSpec::Function {91			name,92			params,93			value,94		} => {95			#[derive(Trace)]96			struct BindableMethodThunk {97				this: Option<ObjValue>,98				super_obj: Option<ObjValue>,99100				cctx: ContextCreator,101				name: IStr,102				params: ParamsDesc,103				value: LocExpr,104			}105			impl ThunkValue for BindableMethodThunk {106				type Output = Val;107				fn get(self: Box<Self>, s: State) -> Result<Val> {108					Ok(evaluate_method(109						self.cctx.create(s, self.this, self.super_obj)?,110						self.name,111						self.params,112						self.value,113					))114				}115			}116117			#[derive(Trace)]118			struct BindableMethod {119				cctx: ContextCreator,120				name: IStr,121				params: ParamsDesc,122				value: LocExpr,123			}124			impl Bindable for BindableMethod {125				fn bind(126					&self,127					_: State,128					this: Option<ObjValue>,129					super_obj: Option<ObjValue>,130				) -> Result<Thunk<Val>> {131					Ok(Thunk::<Val>::new(tb!(BindableMethodThunk {132						this,133						super_obj,134135						cctx: self.cctx.clone(),136						name: self.name.clone(),137						params: self.params.clone(),138						value: self.value.clone(),139					})))140				}141			}142143			let params = params.clone();144145			Ok((146				name.clone(),147				LazyBinding::Bindable(Cc::new(tb!(BindableMethod {148					cctx,149					name: name.clone(),150					params,151					value,152				}))),153			))154		}155	}156}157158pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {159	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {160		name,161		ctx,162		params,163		body,164	})))165}166167pub fn evaluate_field_name(168	s: State,169	ctx: Context,170	field_name: &jrsonnet_parser::FieldName,171) -> Result<Option<IStr>> {172	Ok(match field_name {173		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),174		jrsonnet_parser::FieldName::Dyn(expr) => s.push(175			CallLocation::new(&expr.1),176			|| "evaluating field name".to_string(),177			|| {178				let value = evaluate(s.clone(), ctx, expr)?;179				if matches!(value, Val::Null) {180					Ok(None)181				} else {182					Ok(Some(IStr::from_untyped(value, s.clone())?))183				}184			},185		)?,186	})187}188189pub fn evaluate_comp(190	s: State,191	ctx: Context,192	specs: &[CompSpec],193	callback: &mut impl FnMut(Context) -> Result<()>,194) -> Result<()> {195	match specs.get(0) {196		None => callback(ctx)?,197		Some(CompSpec::IfSpec(IfSpecData(cond))) => {198			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {199				evaluate_comp(s, ctx, &specs[1..], callback)?;200			}201		}202		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {203			match evaluate(s.clone(), ctx.clone(), expr)? {204				Val::Arr(list) => {205					for item in list.iter(s.clone()) {206						evaluate_comp(207							s.clone(),208							ctx.clone().with_var(var.clone(), item?.clone()),209							&specs[1..],210							callback,211						)?;212					}213				}214				_ => throw!(InComprehensionCanOnlyIterateOverArray),215			}216		}217	}218	Ok(())219}220221#[allow(clippy::too_many_lines)]222pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {223	let new_bindings = Pending::new();224	let future_this = Pending::new();225	let cctx = ContextCreator(ctx.clone(), new_bindings.clone());226	{227		let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());228		for r in members229			.iter()230			.filter_map(|m| match m {231				Member::BindStmt(b) => Some(b.clone()),232				_ => None,233			})234			.map(|b| evaluate_binding(b.clone(), cctx.clone()))235		{236			let (n, b) = r?;237			bindings.insert(n, b);238		}239		new_bindings.fill(bindings);240	}241242	let mut builder = ObjValueBuilder::new();243	for member in members.iter() {244		match member {245			Member::Field(FieldMember {246				name,247				plus,248				params: None,249				visibility,250				value,251			}) => {252				#[derive(Trace)]253				struct ObjMemberBinding {254					cctx: ContextCreator,255					value: LocExpr,256					name: IStr,257				}258				impl Bindable for ObjMemberBinding {259					fn bind(260						&self,261						s: State,262						this: Option<ObjValue>,263						super_obj: Option<ObjValue>,264					) -> Result<Thunk<Val>> {265						Ok(Thunk::evaluated(evaluate_named(266							s.clone(),267							self.cctx.create(s, this, super_obj)?,268							&self.value,269							self.name.clone(),270						)?))271					}272				}273274				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;275				let name = if let Some(name) = name {276					name277				} else {278					continue;279				};280281				builder282					.member(name.clone())283					.with_add(*plus)284					.with_visibility(*visibility)285					.with_location(value.1.clone())286					.bindable(287						s.clone(),288						tb!(ObjMemberBinding {289							cctx: cctx.clone(),290							value: value.clone(),291							name,292						}),293					)?;294			}295			Member::Field(FieldMember {296				name,297				params: Some(params),298				value,299				..300			}) => {301				#[derive(Trace)]302				struct ObjMemberBinding {303					cctx: ContextCreator,304					value: LocExpr,305					params: ParamsDesc,306					name: IStr,307				}308				impl Bindable for ObjMemberBinding {309					fn bind(310						&self,311						s: State,312						this: Option<ObjValue>,313						super_obj: Option<ObjValue>,314					) -> Result<Thunk<Val>> {315						Ok(Thunk::evaluated(evaluate_method(316							self.cctx.create(s, this, super_obj)?,317							self.name.clone(),318							self.params.clone(),319							self.value.clone(),320						)))321					}322				}323324				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {325					name326				} else {327					continue;328				};329330				builder331					.member(name.clone())332					.hide()333					.with_location(value.1.clone())334					.bindable(335						s.clone(),336						tb!(ObjMemberBinding {337							cctx: cctx.clone(),338							value: value.clone(),339							params: params.clone(),340							name,341						}),342					)?;343			}344			Member::BindStmt(_) => {}345			Member::AssertStmt(stmt) => {346				#[derive(Trace)]347				struct ObjectAssert {348					cctx: ContextCreator,349					assert: AssertStmt,350				}351				impl ObjectAssertion for ObjectAssert {352					fn run(353						&self,354						s: State,355						this: Option<ObjValue>,356						super_obj: Option<ObjValue>,357					) -> Result<()> {358						let ctx = self.cctx.create(s.clone(), this, super_obj)?;359						evaluate_assert(s, ctx, &self.assert)360					}361				}362				builder.assert(tb!(ObjectAssert {363					cctx: cctx.clone(),364					assert: stmt.clone(),365				}));366			}367		}368	}369	let this = builder.build();370	future_this.fill(this.clone());371	Ok(this)372}373374pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {375	Ok(match object {376		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,377		ObjBody::ObjComp(obj) => {378			let future_this = Pending::new();379			let mut builder = ObjValueBuilder::new();380			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {381				let new_bindings = Pending::new();382				let cctx = ContextCreator(ctx.clone(), new_bindings.clone());383				let mut bindings: GcHashMap<IStr, LazyBinding> =384					GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());385				for r in obj386					.pre_locals387					.iter()388					.chain(obj.post_locals.iter())389					.map(|b| evaluate_binding(b.clone(), cctx.clone()))390				{391					let (n, b) = r?;392					bindings.insert(n, b);393				}394				new_bindings.fill(bindings.clone());395				let ctx = ctx.extend_unbound(s.clone(), bindings, None, None, None)?;396				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;397398				match key {399					Val::Null => {}400					Val::Str(n) => {401						#[derive(Trace)]402						struct ObjCompBinding {403							ctx: Context,404							value: LocExpr,405						}406						impl Bindable for ObjCompBinding {407							fn bind(408								&self,409								s: State,410								this: Option<ObjValue>,411								_super_obj: Option<ObjValue>,412							) -> Result<Thunk<Val>> {413								Ok(Thunk::evaluated(evaluate(414									s,415									self.ctx.clone().extend(GcHashMap::new(), None, this, None),416									&self.value,417								)?))418							}419						}420						builder421							.member(n)422							.with_location(obj.value.1.clone())423							.with_add(obj.plus)424							.bindable(425								s.clone(),426								tb!(ObjCompBinding {427									ctx,428									value: obj.value.clone(),429								}),430							)?;431					}432					v => throw!(FieldMustBeStringGot(v.value_type())),433				}434435				Ok(())436			})?;437438			let this = builder.build();439			future_this.fill(this.clone());440			this441		}442	})443}444445pub fn evaluate_apply(446	s: State,447	ctx: Context,448	value: &LocExpr,449	args: &ArgsDesc,450	loc: CallLocation,451	tailstrict: bool,452) -> Result<Val> {453	let value = evaluate(s.clone(), ctx.clone(), value)?;454	Ok(match value {455		Val::Func(f) => {456			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);457			if tailstrict {458				body()?459			} else {460				s.push(loc, || format!("function <{}> call", f.name()), body)?461			}462		}463		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),464	})465}466467pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {468	let value = &assertion.0;469	let msg = &assertion.1;470	let assertion_result = s.push(471		CallLocation::new(&value.1),472		|| "assertion condition".to_owned(),473		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),474	)?;475	if !assertion_result {476		s.push(477			CallLocation::new(&value.1),478			|| "assertion failure".to_owned(),479			|| {480				if let Some(msg) = msg {481					throw!(AssertionFailed(482						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?483					));484				}485				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));486			},487		)?;488	}489	Ok(())490}491492pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {493	use Expr::*;494	let LocExpr(raw_expr, _loc) = expr;495	Ok(match &**raw_expr {496		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),497		_ => evaluate(s, ctx, expr)?,498	})499}500501#[allow(clippy::too_many_lines)]502pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {503	use Expr::*;504	let LocExpr(expr, loc) = expr;505	// let bp = with_state(|s| s.0.stop_at.borrow().clone());506	Ok(match &**expr {507		Literal(LiteralType::This) => {508			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)509		}510		Literal(LiteralType::Super) => Val::Obj(511			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(512				ctx.this()513					.clone()514					.expect("if super exists - then this should to"),515			),516		),517		Literal(LiteralType::Dollar) => {518			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)519		}520		Literal(LiteralType::True) => Val::Bool(true),521		Literal(LiteralType::False) => Val::Bool(false),522		Literal(LiteralType::Null) => Val::Null,523		Parened(e) => evaluate(s, ctx, e)?,524		Str(v) => Val::Str(v.clone()),525		Num(v) => Val::new_checked_num(*v)?,526		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,527		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,528		Var(name) => s.push(529			CallLocation::new(loc),530			|| format!("variable <{}> access", name),531			|| ctx.binding(name.clone())?.evaluate(s.clone()),532		)?,533		Index(value, index) => {534			match (535				evaluate(s.clone(), ctx.clone(), value)?,536				evaluate(s.clone(), ctx, index)?,537			) {538				(Val::Obj(v), Val::Str(key)) => s.push(539					CallLocation::new(loc),540					|| format!("field <{}> access", key),541					|| match v.get(s.clone(), key.clone()) {542						Ok(Some(v)) => Ok(v),543						Ok(None) => throw!(NoSuchField(key.clone())),544						Err(e) if matches!(e.error(), MagicThisFileUsed) => {545							Ok(Val::Str(loc.0.to_string_lossy().into()))546						}547						Err(e) => Err(e),548					},549				)?,550				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(551					ValType::Obj,552					ValType::Str,553					n.value_type(),554				)),555556				(Val::Arr(v), Val::Num(n)) => {557					if n.fract() > f64::EPSILON {558						throw!(FractionalIndex)559					}560					v.get(s, n as usize)?561						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?562				}563				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),564				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(565					ValType::Arr,566					ValType::Num,567					n.value_type(),568				)),569570				(Val::Str(s), Val::Num(n)) => Val::Str({571					let v: IStr = s572						.chars()573						.skip(n as usize)574						.take(1)575						.collect::<String>()576						.into();577					if v.is_empty() {578						let size = s.chars().count();579						throw!(StringBoundsError(n as usize, size))580					}581					v582				}),583				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(584					ValType::Str,585					ValType::Num,586					n.value_type(),587				)),588589				(v, _) => throw!(CantIndexInto(v.value_type())),590			}591		}592		LocalExpr(bindings, returned) => {593			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =594				GcHashMap::with_capacity(bindings.len());595			let fctx = Context::new_future();596			for b in bindings {597				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;598			}599			let ctx = ctx.extend_bound(new_bindings).into_future(fctx);600			evaluate(s, ctx, &returned.clone())?601		}602		Arr(items) => {603			let mut out = Vec::with_capacity(items.len());604			for item in items {605				// TODO: Implement ArrValue::Lazy with same context for every element?606				#[derive(Trace)]607				struct ArrayElement {608					ctx: Context,609					item: LocExpr,610				}611				impl ThunkValue for ArrayElement {612					type Output = Val;613					fn get(self: Box<Self>, s: State) -> Result<Val> {614						evaluate(s, self.ctx, &self.item)615					}616				}617				out.push(Thunk::new(tb!(ArrayElement {618					ctx: ctx.clone(),619					item: item.clone(),620				})));621			}622			Val::Arr(out.into())623		}624		ArrComp(expr, comp_specs) => {625			let mut out = Vec::new();626			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {627				out.push(evaluate(s.clone(), ctx, expr)?);628				Ok(())629			})?;630			Val::Arr(ArrValue::Eager(Cc::new(out)))631		}632		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),633		ObjExtend(a, b) => evaluate_add_op(634			s.clone(),635			&evaluate(s.clone(), ctx.clone(), a)?,636			&Val::Obj(evaluate_object(s, ctx, b)?),637		)?,638		Apply(value, args, tailstrict) => {639			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?640		}641		Function(params, body) => {642			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())643		}644		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(645			BUILTINS646				.with(|b| b.get(name).copied())647				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,648		)),649		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),650		IntrinsicId => Val::Func(FuncVal::identity()),651		AssertExpr(assert, returned) => {652			evaluate_assert(s.clone(), ctx.clone(), assert)?;653			evaluate(s, ctx, returned)?654		}655		ErrorStmt(e) => s.push(656			CallLocation::new(loc),657			|| "error statement".to_owned(),658			|| {659				throw!(RuntimeError(660					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,661				))662			},663		)?,664		IfElse {665			cond,666			cond_then,667			cond_else,668		} => {669			if s.push(670				CallLocation::new(loc),671				|| "if condition".to_owned(),672				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),673			)? {674				evaluate(s, ctx, cond_then)?675			} else {676				match cond_else {677					Some(v) => evaluate(s, ctx, v)?,678					None => Val::Null,679				}680			}681		}682		Slice(value, desc) => {683			fn parse_idx<T: Typed>(684				loc: CallLocation,685				s: State,686				ctx: &Context,687				expr: &Option<LocExpr>,688				desc: &'static str,689			) -> Result<Option<T>> {690				if let Some(value) = expr {691					Ok(Some(s.push(692						loc,693						|| format!("slice {}", desc),694						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),695					)?))696				} else {697					Ok(None)698				}699			}700701			let indexable = evaluate(s.clone(), ctx.clone(), value)?;702			let loc = CallLocation::new(loc);703704			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;705			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;706			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;707708			std_slice(indexable.into_indexable()?, start, end, step)?709		}710		Import(path) => {711			let tmp = loc.clone().0;712			let mut import_location = tmp.to_path_buf();713			import_location.pop();714			s.push(715				CallLocation::new(loc),716				|| format!("import {:?}", path),717				|| s.import_file(&import_location, path),718			)?719		}720		ImportStr(path) => {721			let tmp = loc.clone().0;722			let mut import_location = tmp.to_path_buf();723			import_location.pop();724			Val::Str(s.import_file_str(&import_location, path)?)725		}726		ImportBin(path) => {727			let tmp = loc.clone().0;728			let mut import_location = tmp.to_path_buf();729			import_location.pop();730			let bytes = s.import_file_bin(&import_location, path)?;731			Val::Arr(ArrValue::Bytes(bytes))732		}733	})734}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,7	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedBindable, Thunk, ThunkValue},20	Bindable, Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,21	State, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(36	s: State,37	ctx: Context,38	field_name: &jrsonnet_parser::FieldName,39) -> Result<Option<IStr>> {40	Ok(match field_name {41		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),42		jrsonnet_parser::FieldName::Dyn(expr) => s.push(43			CallLocation::new(&expr.1),44			|| "evaluating field name".to_string(),45			|| {46				let value = evaluate(s.clone(), ctx, expr)?;47				if matches!(value, Val::Null) {48					Ok(None)49				} else {50					Ok(Some(IStr::from_untyped(value, s.clone())?))51				}52			},53		)?,54	})55}5657pub fn evaluate_comp(58	s: State,59	ctx: Context,60	specs: &[CompSpec],61	callback: &mut impl FnMut(Context) -> Result<()>,62) -> Result<()> {63	match specs.get(0) {64		None => callback(ctx)?,65		Some(CompSpec::IfSpec(IfSpecData(cond))) => {66			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {67				evaluate_comp(s, ctx, &specs[1..], callback)?;68			}69		}70		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {71			match evaluate(s.clone(), ctx.clone(), expr)? {72				Val::Arr(list) => {73					for item in list.iter(s.clone()) {74						evaluate_comp(75							s.clone(),76							ctx.clone().with_var(var.clone(), item?.clone()),77							&specs[1..],78							callback,79						)?;80					}81				}82				_ => throw!(InComprehensionCanOnlyIterateOverArray),83			}84		}85	}86	Ok(())87}8889trait CloneableBindable<T>: Bindable<Bound = T> + Clone {}9091fn evaluate_object_locals(92	fctx: Pending<Context>,93	locals: Rc<Vec<BindSpec>>,94) -> impl CloneableBindable<Context> {95	#[derive(Trace, Clone)]96	struct WithObjectLocals {97		fctx: Pending<Context>,98		locals: Rc<Vec<BindSpec>>,99	}100	impl CloneableBindable<Context> for WithObjectLocals {}101	impl Bindable for WithObjectLocals {102		type Bound = Context;103104		fn bind(105			&self,106			_s: State,107			sup: Option<ObjValue>,108			this: Option<ObjValue>,109		) -> Result<Context> {110			let fctx = Context::new_future();111			let mut new_bindings = GcHashMap::new();112			for b in self.locals.iter() {113				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;114			}115116			let ctx = self.fctx.unwrap();117			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());118119			let ctx = ctx120				.extend(new_bindings, new_dollar, sup, this)121				.into_future(fctx);122123			Ok(ctx)124		}125	}126127	WithObjectLocals { fctx, locals }128}129130#[allow(clippy::too_many_lines)]131pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {132	let mut builder = ObjValueBuilder::new();133	let locals = Rc::new(134		members135			.iter()136			.filter_map(|m| match m {137				Member::BindStmt(bind) => Some(bind.clone()),138				_ => None,139			})140			.collect::<Vec<_>>(),141	);142143	let fctx = Context::new_future();144145	// We have single context for all fields, so we can cache binds146	let uctx = CachedBindable::new(evaluate_object_locals(fctx.clone(), locals));147148	for member in members.iter() {149		match member {150			Member::Field(FieldMember {151				name,152				plus,153				params: None,154				visibility,155				value,156			}) => {157				#[derive(Trace)]158				struct ObjMemberBinding<B> {159					uctx: B,160					value: LocExpr,161					name: IStr,162				}163				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {164					type Bound = Thunk<Val>;165					fn bind(166						&self,167						s: State,168						sup: Option<ObjValue>,169						this: Option<ObjValue>,170					) -> Result<Thunk<Val>> {171						Ok(Thunk::evaluated(evaluate_named(172							s.clone(),173							self.uctx.bind(s, sup, this)?,174							&self.value,175							self.name.clone(),176						)?))177					}178				}179180				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;181				let name = if let Some(name) = name {182					name183				} else {184					continue;185				};186187				builder188					.member(name.clone())189					.with_add(*plus)190					.with_visibility(*visibility)191					.with_location(value.1.clone())192					.bindable(193						s.clone(),194						tb!(ObjMemberBinding {195							uctx: uctx.clone(),196							value: value.clone(),197							name: name.clone()198						}),199					)?;200			}201			Member::Field(FieldMember {202				name,203				params: Some(params),204				value,205				..206			}) => {207				#[derive(Trace)]208				struct ObjMemberBinding<B> {209					uctx: B,210					value: LocExpr,211					params: ParamsDesc,212					name: IStr,213				}214				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {215					type Bound = Thunk<Val>;216					fn bind(217						&self,218						s: State,219						sup: Option<ObjValue>,220						this: Option<ObjValue>,221					) -> Result<Thunk<Val>> {222						Ok(Thunk::evaluated(evaluate_method(223							self.uctx.bind(s, sup, this)?,224							self.name.clone(),225							self.params.clone(),226							self.value.clone(),227						)))228					}229				}230231				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {232					name233				} else {234					continue;235				};236237				builder238					.member(name.clone())239					.hide()240					.with_location(value.1.clone())241					.bindable(242						s.clone(),243						tb!(ObjMemberBinding {244							uctx: uctx.clone(),245							value: value.clone(),246							params: params.clone(),247							name: name.clone()248						}),249					)?;250			}251			Member::BindStmt(_) => {}252			Member::AssertStmt(stmt) => {253				#[derive(Trace)]254				struct ObjectAssert<B> {255					uctx: B,256					assert: AssertStmt,257				}258				impl<B: Bindable<Bound = Context>> ObjectAssertion for ObjectAssert<B> {259					fn run(260						&self,261						s: State,262						sup: Option<ObjValue>,263						this: Option<ObjValue>,264					) -> Result<()> {265						let ctx = self.uctx.bind(s.clone(), sup, this)?;266						evaluate_assert(s, ctx, &self.assert)267					}268				}269				builder.assert(tb!(ObjectAssert {270					uctx: uctx.clone(),271					assert: stmt.clone(),272				}));273			}274		}275	}276	let this = builder.build();277	let _ctx = ctx278		.extend(GcHashMap::new(), None, None, Some(this.clone()))279		.into_future(fctx);280	Ok(this)281}282283pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {284	Ok(match object {285		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,286		ObjBody::ObjComp(obj) => {287			let mut builder = ObjValueBuilder::new();288			let locals = Rc::new(289				obj.pre_locals290					.iter()291					.chain(obj.post_locals.iter())292					.cloned()293					.collect::<Vec<_>>(),294			);295			let mut ctxs = vec![];296			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {297				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;298				let fctx = Context::new_future();299				ctxs.push((ctx, fctx.clone()));300				let uctx = evaluate_object_locals(fctx, locals.clone());301302				match key {303					Val::Null => {}304					Val::Str(n) => {305						#[derive(Trace)]306						struct ObjCompBinding<B> {307							uctx: B,308							value: LocExpr,309						}310						impl<B: Bindable<Bound = Context>> Bindable for ObjCompBinding<B> {311							type Bound = Thunk<Val>;312							fn bind(313								&self,314								s: State,315								sup: Option<ObjValue>,316								this: Option<ObjValue>,317							) -> Result<Thunk<Val>> {318								Ok(Thunk::evaluated(evaluate(319									s.clone(),320									self.uctx.bind(s, sup, this.clone())?.extend(321										GcHashMap::new(),322										None,323										None,324										this,325									),326									&self.value,327								)?))328							}329						}330						builder331							.member(n)332							.with_location(obj.value.1.clone())333							.with_add(obj.plus)334							.bindable(335								s.clone(),336								tb!(ObjCompBinding {337									uctx,338									value: obj.value.clone(),339								}),340							)?;341					}342					v => throw!(FieldMustBeStringGot(v.value_type())),343				}344345				Ok(())346			})?;347348			let this = builder.build();349			for (ctx, fctx) in ctxs {350				let _ctx = ctx351					.extend(GcHashMap::new(), None, None, Some(this.clone()))352					.into_future(fctx);353			}354			this355		}356	})357}358359pub fn evaluate_apply(360	s: State,361	ctx: Context,362	value: &LocExpr,363	args: &ArgsDesc,364	loc: CallLocation,365	tailstrict: bool,366) -> Result<Val> {367	let value = evaluate(s.clone(), ctx.clone(), value)?;368	Ok(match value {369		Val::Func(f) => {370			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);371			if tailstrict {372				body()?373			} else {374				s.push(loc, || format!("function <{}> call", f.name()), body)?375			}376		}377		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),378	})379}380381pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {382	let value = &assertion.0;383	let msg = &assertion.1;384	let assertion_result = s.push(385		CallLocation::new(&value.1),386		|| "assertion condition".to_owned(),387		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),388	)?;389	if !assertion_result {390		s.push(391			CallLocation::new(&value.1),392			|| "assertion failure".to_owned(),393			|| {394				if let Some(msg) = msg {395					throw!(AssertionFailed(396						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?397					));398				}399				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));400			},401		)?;402	}403	Ok(())404}405406pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {407	use Expr::*;408	let LocExpr(raw_expr, _loc) = expr;409	Ok(match &**raw_expr {410		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),411		_ => evaluate(s, ctx, expr)?,412	})413}414415#[allow(clippy::too_many_lines)]416pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {417	use Expr::*;418	let LocExpr(expr, loc) = expr;419	// let bp = with_state(|s| s.0.stop_at.borrow().clone());420	Ok(match &**expr {421		Literal(LiteralType::This) => {422			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)423		}424		Literal(LiteralType::Super) => Val::Obj(425			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(426				ctx.this()427					.clone()428					.expect("if super exists - then this should to"),429			),430		),431		Literal(LiteralType::Dollar) => {432			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)433		}434		Literal(LiteralType::True) => Val::Bool(true),435		Literal(LiteralType::False) => Val::Bool(false),436		Literal(LiteralType::Null) => Val::Null,437		Parened(e) => evaluate(s, ctx, e)?,438		Str(v) => Val::Str(v.clone()),439		Num(v) => Val::new_checked_num(*v)?,440		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,441		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,442		Var(name) => s.push(443			CallLocation::new(loc),444			|| format!("variable <{}> access", name),445			|| ctx.binding(name.clone())?.evaluate(s.clone()),446		)?,447		Index(value, index) => {448			match (449				evaluate(s.clone(), ctx.clone(), value)?,450				evaluate(s.clone(), ctx, index)?,451			) {452				(Val::Obj(v), Val::Str(key)) => s.push(453					CallLocation::new(loc),454					|| format!("field <{}> access", key),455					|| match v.get(s.clone(), key.clone()) {456						Ok(Some(v)) => Ok(v),457						Ok(None) => throw!(NoSuchField(key.clone())),458						Err(e) if matches!(e.error(), MagicThisFileUsed) => {459							Ok(Val::Str(loc.0.to_string_lossy().into()))460						}461						Err(e) => Err(e),462					},463				)?,464				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(465					ValType::Obj,466					ValType::Str,467					n.value_type(),468				)),469470				(Val::Arr(v), Val::Num(n)) => {471					if n.fract() > f64::EPSILON {472						throw!(FractionalIndex)473					}474					v.get(s, n as usize)?475						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?476				}477				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),478				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(479					ValType::Arr,480					ValType::Num,481					n.value_type(),482				)),483484				(Val::Str(s), Val::Num(n)) => Val::Str({485					let v: IStr = s486						.chars()487						.skip(n as usize)488						.take(1)489						.collect::<String>()490						.into();491					if v.is_empty() {492						let size = s.chars().count();493						throw!(StringBoundsError(n as usize, size))494					}495					v496				}),497				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(498					ValType::Str,499					ValType::Num,500					n.value_type(),501				)),502503				(v, _) => throw!(CantIndexInto(v.value_type())),504			}505		}506		LocalExpr(bindings, returned) => {507			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =508				GcHashMap::with_capacity(bindings.len());509			let fctx = Context::new_future();510			for b in bindings {511				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;512			}513			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);514			evaluate(s, ctx, &returned.clone())?515		}516		Arr(items) => {517			let mut out = Vec::with_capacity(items.len());518			for item in items {519				// TODO: Implement ArrValue::Lazy with same context for every element?520				#[derive(Trace)]521				struct ArrayElement {522					ctx: Context,523					item: LocExpr,524				}525				impl ThunkValue for ArrayElement {526					type Output = Val;527					fn get(self: Box<Self>, s: State) -> Result<Val> {528						evaluate(s, self.ctx, &self.item)529					}530				}531				out.push(Thunk::new(tb!(ArrayElement {532					ctx: ctx.clone(),533					item: item.clone(),534				})));535			}536			Val::Arr(out.into())537		}538		ArrComp(expr, comp_specs) => {539			let mut out = Vec::new();540			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {541				out.push(evaluate(s.clone(), ctx, expr)?);542				Ok(())543			})?;544			Val::Arr(ArrValue::Eager(Cc::new(out)))545		}546		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),547		ObjExtend(a, b) => evaluate_add_op(548			s.clone(),549			&evaluate(s.clone(), ctx.clone(), a)?,550			&Val::Obj(evaluate_object(s, ctx, b)?),551		)?,552		Apply(value, args, tailstrict) => {553			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?554		}555		Function(params, body) => {556			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())557		}558		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(559			BUILTINS560				.with(|b| b.get(name).copied())561				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,562		)),563		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),564		IntrinsicId => Val::Func(FuncVal::identity()),565		AssertExpr(assert, returned) => {566			evaluate_assert(s.clone(), ctx.clone(), assert)?;567			evaluate(s, ctx, returned)?568		}569		ErrorStmt(e) => s.push(570			CallLocation::new(loc),571			|| "error statement".to_owned(),572			|| {573				throw!(RuntimeError(574					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,575				))576			},577		)?,578		IfElse {579			cond,580			cond_then,581			cond_else,582		} => {583			if s.push(584				CallLocation::new(loc),585				|| "if condition".to_owned(),586				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),587			)? {588				evaluate(s, ctx, cond_then)?589			} else {590				match cond_else {591					Some(v) => evaluate(s, ctx, v)?,592					None => Val::Null,593				}594			}595		}596		Slice(value, desc) => {597			fn parse_idx<T: Typed>(598				loc: CallLocation,599				s: State,600				ctx: &Context,601				expr: &Option<LocExpr>,602				desc: &'static str,603			) -> Result<Option<T>> {604				if let Some(value) = expr {605					Ok(Some(s.push(606						loc,607						|| format!("slice {}", desc),608						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),609					)?))610				} else {611					Ok(None)612				}613			}614615			let indexable = evaluate(s.clone(), ctx.clone(), value)?;616			let loc = CallLocation::new(loc);617618			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;619			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;620			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;621622			std_slice(indexable.into_indexable()?, start, end, step)?623		}624		Import(path) => {625			let tmp = loc.clone().0;626			let mut import_location = tmp.to_path_buf();627			import_location.pop();628			s.push(629				CallLocation::new(loc),630				|| format!("import {:?}", path),631				|| s.import_file(&import_location, path),632			)?633		}634		ImportStr(path) => {635			let tmp = loc.clone().0;636			let mut import_location = tmp.to_path_buf();637			import_location.pop();638			Val::Str(s.import_file_str(&import_location, path)?)639		}640		ImportBin(path) => {641			let tmp = loc.clone().0;642			let mut import_location = tmp.to_path_buf();643			import_location.pop();644			let bytes = s.import_file_bin(&import_location, path)?;645			Val::Arr(ArrValue::Bytes(bytes))646		}647	})648}
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -139,11 +139,12 @@
 	) -> Result<Val> {
 		match self {
 			Self::Id => {
+				#[allow(clippy::unnecessary_wraps)]
 				#[builtin]
-				fn builtin_id(v: Any) -> Result<Any> {
+				const fn builtin_id(v: Any) -> Result<Any> {
 					Ok(v)
 				}
-				static ID: &'static builtin_id = &builtin_id {};
+				static ID: &builtin_id = &builtin_id {};
 
 				ID.call(s, call_ctx, loc, args)
 			}
@@ -159,10 +160,10 @@
 		self.evaluate(s, Context::default(), CallLocation::native(), args, true)
 	}
 
-	pub fn is_identity(&self) -> bool {
+	pub const fn is_identity(&self) -> bool {
 		matches!(self, Self::Id)
 	}
-	pub fn identity() -> Self {
+	pub const fn identity() -> Self {
 		Self::Id
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -111,7 +111,7 @@
 
 		Ok(body_ctx
 			.extend(passed_args, None, None, None)
-			.extend_bound(defaults)
+			.extend(defaults, None, None, None)
 			.into_future(fctx))
 	} else {
 		let body_ctx = body_ctx.extend(passed_args, None, None, None);
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -10,7 +10,7 @@
 use rustc_hash::{FxHashMap, FxHashSet};
 
 /// Replacement for box, which assumes that the underlying type is [`Trace`]
-/// Used in places, where Cc<dyn Trait> should be used instead, but it can't, because CoerceUnsiced is not stable
+/// Used in places, where `Cc<dyn Trait>` should be used instead, but it can't, because `CoerceUnsiced` is not stable
 #[derive(Debug, Clone)]
 pub struct TraceBox<T: ?Sized>(pub Box<T>);
 #[macro_export]
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -61,17 +61,13 @@
 pub use val::{ManifestFormat, Thunk, Val};
 
 pub trait Bindable: Trace + 'static {
-	fn bind(
-		&self,
-		s: State,
-		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
-	) -> Result<Thunk<Val>>;
+	type Bound;
+	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
 }
 
 #[derive(Clone, Trace)]
 pub enum LazyBinding {
-	Bindable(Cc<TraceBox<dyn Bindable>>),
+	Bindable(Cc<TraceBox<dyn Bindable<Bound = Thunk<Val>>>>),
 	Bound(Thunk<Val>),
 }
 
@@ -84,11 +80,11 @@
 	pub fn evaluate(
 		&self,
 		s: State,
+		sup: Option<ObjValue>,
 		this: Option<ObjValue>,
-		super_obj: Option<ObjValue>,
 	) -> Result<Thunk<Val>> {
 		match self {
-			Self::Bindable(v) => v.bind(s, this, super_obj),
+			Self::Bindable(v) => v.bind(s, sup, this),
 			Self::Bound(v) => Ok(v.clone()),
 		}
 	}
@@ -345,7 +341,7 @@
 		for (name, value) in globals.iter() {
 			new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));
 		}
-		Context::new().extend_bound(new_bindings)
+		Context::new().extend(new_bindings, None, None, None)
 	}
 
 	/// Executes code creating a new stack frame
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -106,7 +106,7 @@
 }
 
 pub trait ObjectAssertion: Trace {
-	fn run(&self, s: State, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;
+	fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;
 }
 
 // Field => This
@@ -124,10 +124,11 @@
 #[derive(Trace)]
 #[force_tracking]
 pub struct ObjValueInternals {
-	super_obj: Option<ObjValue>,
+	sup: Option<ObjValue>,
+	this: Option<ObjValue>,
+
 	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,
 	assertions_ran: RefCell<GcHashSet<ObjValue>>,
-	this_obj: Option<ObjValue>,
 	this_entries: Cc<GcHashMap<IStr, ObjMember>>,
 	value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,
 }
@@ -153,7 +154,7 @@
 pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);
 impl Debug for ObjValue {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		if let Some(super_obj) = self.0.super_obj.as_ref() {
+		if let Some(super_obj) = self.0.sup.as_ref() {
 			if f.alternate() {
 				write!(f, "{:#?}", super_obj)?;
 			} else {
@@ -171,15 +172,15 @@
 
 impl ObjValue {
 	pub fn new(
-		super_obj: Option<Self>,
+		sup: Option<Self>,
 		this_entries: Cc<GcHashMap<IStr, ObjMember>>,
 		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,
 	) -> Self {
 		Self(Cc::new(ObjValueInternals {
-			super_obj,
+			sup,
+			this: None,
 			assertions,
 			assertions_ran: RefCell::new(GcHashSet::new()),
-			this_obj: None,
 			this_entries,
 			value_cache: RefCell::new(GcHashMap::new()),
 		}))
@@ -188,15 +189,15 @@
 		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))
 	}
 	#[must_use]
-	pub fn extend_from(&self, super_obj: Self) -> Self {
-		match &self.0.super_obj {
+	pub fn extend_from(&self, sup: Self) -> Self {
+		match &self.0.sup {
 			None => Self::new(
-				Some(super_obj),
+				Some(sup),
 				self.0.this_entries.clone(),
 				self.0.assertions.clone(),
 			),
 			Some(v) => Self::new(
-				Some(v.extend_from(super_obj)),
+				Some(v.extend_from(sup)),
 				self.0.this_entries.clone(),
 				self.0.assertions.clone(),
 			),
@@ -212,12 +213,12 @@
 	}
 
 	#[must_use]
-	pub fn with_this(&self, this_obj: Self) -> Self {
+	pub fn with_this(&self, this: Self) -> Self {
 		Self(Cc::new(ObjValueInternals {
-			super_obj: self.0.super_obj.clone(),
+			sup: self.0.sup.clone(),
 			assertions: self.0.assertions.clone(),
 			assertions_ran: RefCell::new(GcHashSet::new()),
-			this_obj: Some(this_obj),
+			this: Some(this),
 			this_entries: self.0.this_entries.clone(),
 			value_cache: RefCell::new(GcHashMap::new()),
 		}))
@@ -234,7 +235,7 @@
 		if !self.0.this_entries.is_empty() {
 			return false;
 		}
-		self.0.super_obj.as_ref().map_or(true, Self::is_empty)
+		self.0.sup.as_ref().map_or(true, Self::is_empty)
 	}
 
 	/// Run callback for every field found in object
@@ -243,7 +244,7 @@
 		depth: SuperDepth,
 		handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,
 	) -> bool {
-		if let Some(s) = &self.0.super_obj {
+		if let Some(s) = &self.0.sup {
 			if s.enum_fields(depth.deeper(), handler) {
 				return true;
 			}
@@ -332,13 +333,13 @@
 			Some(match &m.visibility {
 				Visibility::Normal => self
 					.0
-					.super_obj
+					.sup
 					.as_ref()
 					.and_then(|super_obj| super_obj.field_visibility(name))
 					.unwrap_or(Visibility::Normal),
 				v => *v,
 			})
-		} else if let Some(super_obj) = &self.0.super_obj {
+		} else if let Some(super_obj) = &self.0.sup {
 			super_obj.field_visibility(name)
 		} else {
 			None
@@ -348,7 +349,7 @@
 	fn has_field_include_hidden(&self, name: IStr) -> bool {
 		if self.0.this_entries.contains_key(&name) {
 			true
-		} else if let Some(super_obj) = &self.0.super_obj {
+		} else if let Some(super_obj) = &self.0.sup {
 			super_obj.has_field_include_hidden(name)
 		} else {
 			false
@@ -369,13 +370,12 @@
 
 	pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {
 		self.run_assertions(s.clone())?;
-		self.get_raw(s, key, self.0.this_obj.as_ref())
+		self.get_raw(s, key, self.0.this.clone().unwrap_or_else(|| self.clone()))
 	}
 
 	// pub fn extend_with(self, key: )
 
-	fn get_raw(&self, s: State, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
-		let real_this = real_this.unwrap_or(self);
+	fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {
 		let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));
 
 		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -397,17 +397,17 @@
 				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));
 			e
 		};
-		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {
+		let value = match (self.0.this_entries.get(&key), &self.0.sup) {
 			(Some(k), None) => Ok(Some(
 				self.evaluate_this(s, k, real_this).map_err(fill_error)?,
 			)),
 			(Some(k), Some(super_obj)) => {
 				let our = self
-					.evaluate_this(s.clone(), k, real_this)
+					.evaluate_this(s.clone(), k, real_this.clone())
 					.map_err(fill_error)?;
 				if k.add {
 					super_obj
-						.get_raw(s.clone(), key, Some(real_this))
+						.get_raw(s.clone(), key, real_this)
 						.map_err(fill_error)?
 						.map_or(Ok(Some(our.clone())), |v| {
 							Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))
@@ -416,7 +416,7 @@
 					Ok(Some(our))
 				}
 			}
-			(None, Some(super_obj)) => super_obj.get_raw(s, key, Some(real_this)),
+			(None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),
 			(None, None) => Ok(None),
 		}
 		.map_err(fill_error)?;
@@ -429,9 +429,9 @@
 		);
 		Ok(value)
 	}
-	fn evaluate_this(&self, s: State, v: &ObjMember, real_this: &Self) -> Result<Val> {
+	fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {
 		v.invoke
-			.evaluate(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())?
+			.evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?
 			.evaluate(s)
 	}
 
@@ -439,13 +439,13 @@
 		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {
 			for assertion in self.0.assertions.iter() {
 				if let Err(e) =
-					assertion.run(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())
+					assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))
 				{
 					self.0.assertions_ran.borrow_mut().remove(real_this);
 					return Err(e);
 				}
 			}
-			if let Some(super_obj) = &self.0.super_obj {
+			if let Some(super_obj) = &self.0.sup {
 				super_obj.run_assertions_raw(s, real_this)?;
 			}
 		}
@@ -458,6 +458,9 @@
 	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
 		cc_ptr_eq(&a.0, &b.0)
 	}
+	pub fn downgrade(self) -> WeakObjValue {
+		WeakObjValue(self.0.downgrade())
+	}
 }
 
 impl PartialEq for ObjValue {
@@ -475,7 +478,7 @@
 
 #[allow(clippy::module_name_repetitions)]
 pub struct ObjValueBuilder {
-	super_obj: Option<ObjValue>,
+	sup: Option<ObjValue>,
 	map: GcHashMap<IStr, ObjMember>,
 	assertions: Vec<TraceBox<dyn ObjectAssertion>>,
 	next_field_index: FieldIndex,
@@ -486,7 +489,7 @@
 	}
 	pub fn with_capacity(capacity: usize) -> Self {
 		Self {
-			super_obj: None,
+			sup: None,
 			map: GcHashMap::with_capacity(capacity),
 			assertions: Vec::new(),
 			next_field_index: FieldIndex::default(),
@@ -497,7 +500,7 @@
 		self
 	}
 	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {
-		self.super_obj = Some(super_obj);
+		self.sup = Some(super_obj);
 		self
 	}
 
@@ -512,7 +515,7 @@
 	}
 
 	pub fn build(self) -> ObjValue {
-		ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))
+		ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))
 	}
 }
 impl Default for ObjValueBuilder {
@@ -583,7 +586,11 @@
 	pub fn value(self, s: State, value: Val) -> Result<()> {
 		self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
 	}
-	pub fn bindable(self, s: State, bindable: TraceBox<dyn Bindable>) -> Result<()> {
+	pub fn bindable(
+		self,
+		s: State,
+		bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>,
+	) -> Result<()> {
 		self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
 	}
 	pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {
@@ -606,7 +613,7 @@
 	pub fn value(self, value: Val) {
 		self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
 	}
-	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
+	pub fn bindable(self, bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>) {
 		self.binding(LazyBinding::Bindable(Cc::new(bindable)));
 	}
 	pub fn binding(self, binding: LazyBinding) {
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -466,7 +466,7 @@
 	Ok(ArrValue::Eager(sort::sort(
 		s.clone(),
 		arr.evaluated(s)?,
-		keyF.unwrap_or(FuncVal::identity()),
+		keyF.unwrap_or_else(FuncVal::identity),
 	)?))
 }
 
modifiedcrates/jrsonnet-evaluator/src/stdlib/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/sort.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/sort.rs
@@ -68,7 +68,23 @@
 	if values.len() <= 1 {
 		return Ok(values);
 	}
-	if !key_getter.is_identity() {
+	if key_getter.is_identity() {
+		// Fast path, identity key getter
+		let mut values = (*values).clone();
+		let sort_type = get_sort_type(&mut values, |k| k)?;
+		match sort_type {
+			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
+				Val::Num(n) => NonNaNf64(*n),
+				_ => unreachable!(),
+			}),
+			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
+				Val::Str(s) => s.clone(),
+				_ => unreachable!(),
+			}),
+			SortKeyType::Unknown => unreachable!(),
+		};
+		Ok(Cc::new(values))
+	} else {
 		// Slow path, user provided key getter
 		let mut vk = Vec::with_capacity(values.len());
 		for value in values.iter() {
@@ -90,21 +106,5 @@
 			SortKeyType::Unknown => unreachable!(),
 		};
 		Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
-	} else {
-		// Fast path, identity key getter
-		let mut values = (*values).clone();
-		let sort_type = get_sort_type(&mut values, |k| k)?;
-		match sort_type {
-			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
-				Val::Num(n) => NonNaNf64(*n),
-				_ => unreachable!(),
-			}),
-			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
-				Val::Str(s) => s.clone(),
-				_ => unreachable!(),
-			}),
-			SortKeyType::Unknown => unreachable!(),
-		};
-		Ok(Cc::new(values))
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -8,11 +8,11 @@
 	cc_ptr_eq,
 	error::{Error::*, LocError},
 	function::FuncVal,
-	gc::TraceBox,
+	gc::{GcHashMap, TraceBox},
 	stdlib::manifest::{
 		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
 	},
-	throw, ObjValue, Result, State,
+	throw, Bindable, ObjValue, Result, State, WeakObjValue,
 };
 
 pub trait ThunkValue: Trace {
@@ -71,6 +71,47 @@
 	}
 }
 
+type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
+
+#[derive(Trace, Clone)]
+pub struct CachedBindable<I, T>
+where
+	I: Bindable<Bound = T>,
+{
+	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,
+	value: I,
+}
+impl<I: Bindable<Bound = T>, T: Trace> CachedBindable<I, T> {
+	pub fn new(value: I) -> Self {
+		Self {
+			cache: Cc::new(RefCell::new(GcHashMap::new())),
+			value,
+		}
+	}
+}
+impl<I: Bindable<Bound = T>, T: Clone + Trace> Bindable for CachedBindable<I, T> {
+	type Bound = T;
+	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {
+		let cache_key = (
+			sup.as_ref().map(|s| s.clone().downgrade()),
+			this.as_ref().map(|t| t.clone().downgrade()),
+		);
+		{
+			if let Some(t) = self.cache.borrow().get(&cache_key) {
+				return Ok(t.clone());
+			}
+		}
+		let bound = self.value.bind(s, sup, this)?;
+
+		{
+			let mut cache = self.cache.borrow_mut();
+			cache.insert(cache_key, bound.clone());
+		}
+
+		Ok(bound)
+	}
+}
+
 impl<T: Debug> Debug for Thunk<T> {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "Lazy")
modifiedcrates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ b/crates/jrsonnet-evaluator/tests/builtin.rs
@@ -6,7 +6,6 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::{builtin, builtin::Builtin, CallLocation, FuncVal},
-	gc::TraceBox,
 	tb,
 	typed::Typed,
 	State, Val,
modifiedcrates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -30,8 +30,18 @@
 		if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
 			::jrsonnet_evaluator::throw_runtime!(
 				"assertion failed: a != b\na={:#?}\nb={:#?}",
-				$a.to_json($s.clone(), 2)?,
-				$b.to_json($s.clone(), 2)?,
+				$a.to_json(
+					$s.clone(),
+					2,
+					#[cfg(feature = "exp-preserve-order")]
+					false
+				)?,
+				$b.to_json(
+					$s.clone(),
+					2,
+					#[cfg(feature = "exp-preserve-order")]
+					false
+				)?,
 			)
 		}
 	}};
modifiedcrates/jrsonnet-evaluator/tests/golden.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/golden.rs
+++ b/crates/jrsonnet-evaluator/tests/golden.rs
@@ -24,7 +24,12 @@
 		Ok(v) => v,
 		Err(e) => return s.stringify_err(&e),
 	};
-	match v.to_json(s.clone(), 3) {
+	match v.to_json(
+		s.clone(),
+		3,
+		#[cfg(feature = "exp-preserve-order")]
+		false,
+	) {
 		Ok(v) => v.to_string(),
 		Err(e) => s.stringify_err(&e),
 	}
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -165,7 +165,7 @@
 			/ string_block() } / expected!("<string>")
 
 		pub rule field_name(s: &ParserSettings) -> expr::FieldName
-			= name:id() {expr::FieldName::Fixed(name.into())}
+			= name:id() {expr::FieldName::Fixed(name)}
 			/ name:string() {expr::FieldName::Fixed(name.into())}
 			/ "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}
 		pub rule visibility() -> expr::Visibility