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

difftreelog

refactor greately simplify object self/super implementation

xvonlxkpYaroslav Bolyukin2026-02-08parent: #1c69f1a.patch.diff
in: master

18 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -310,6 +310,18 @@
 checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1"
 
 [[package]]
+name = "educe"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417"
+dependencies = [
+ "enum-ordinalize",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
 name = "either"
 version = "1.15.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -340,6 +352,26 @@
 ]
 
 [[package]]
+name = "enum-ordinalize"
+version = "4.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0"
+dependencies = [
+ "enum-ordinalize-derive",
+]
+
+[[package]]
+name = "enum-ordinalize-derive"
+version = "4.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
 name = "equivalent"
 version = "1.0.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -576,6 +608,7 @@
 dependencies = [
  "annotate-snippets",
  "anyhow",
+ "educe",
  "hi-doc",
  "jrsonnet-gcmodule",
  "jrsonnet-interner",
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -57,6 +57,7 @@
 num-bigint = { workspace = true, features = ["serde"], optional = true }
 
 stacker = "0.1.23"
+educe = { version = "0.6.0", default-features = false, features = ["Clone", "Debug", "Eq", "Hash", "PartialEq"] }
 
 [build-dependencies]
 rustversion = "1.0.22"
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,32 +1,27 @@
 use std::fmt::Debug;
 
+use educe::Educe;
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use rustc_hash::FxHashMap;
 
 use crate::{
 	error::ErrorKind::*, gc::WithCapacityExt as _, map::LayeredHashMap, ObjValue, Pending, Result,
-	Thunk, Val,
+	SupThis, Thunk, Val,
 };
+/// Context keeps information about current lexical code location
+///
+/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
+#[derive(Debug, Trace, Clone, Educe)]
+#[educe(PartialEq)]
+pub struct Context(#[educe(PartialEq(method = Cc::ptr_eq))] Cc<ContextInternal>);
 
-#[derive(Trace)]
-struct ContextInternals {
+#[derive(Debug, Trace)]
+struct ContextInternal {
 	dollar: Option<ObjValue>,
-	sup: Option<ObjValue>,
-	this: Option<ObjValue>,
+	sup_this: Option<SupThis>,
 	bindings: LayeredHashMap,
-}
-impl Debug for ContextInternals {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		f.debug_struct("Context").finish()
-	}
 }
-
-/// Context keeps information about current lexical code location
-///
-/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
-#[derive(Debug, Clone, Trace)]
-pub struct Context(Cc<ContextInternals>);
 impl Context {
 	pub fn new_future() -> Pending<Self> {
 		Pending::new()
@@ -36,12 +31,35 @@
 		self.0.dollar.as_ref()
 	}
 
+	pub fn try_dollar(&self) -> Result<ObjValue> {
+		self.0
+			.dollar
+			.clone()
+			.ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
+	}
+
 	pub fn this(&self) -> Option<&ObjValue> {
-		self.0.this.as_ref()
+		self.0.sup_this.as_ref().map(SupThis::this)
+	}
+
+	pub fn try_this(&self) -> Result<ObjValue> {
+		self.0
+			.sup_this
+			.as_ref()
+			.ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
+			.map(SupThis::this)
+			.cloned()
+	}
+
+	pub fn sup_this(&self) -> Option<&SupThis> {
+		self.0.sup_this.as_ref()
 	}
 
-	pub fn super_obj(&self) -> Option<&ObjValue> {
-		self.0.sup.as_ref()
+	pub fn try_sup_this(&self) -> Result<SupThis> {
+		self.0
+			.sup_this
+			.clone()
+			.ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
 	}
 
 	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
@@ -83,41 +101,52 @@
 	pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
 		let mut new_bindings = FxHashMap::with_capacity(1);
 		new_bindings.insert(name.into(), Thunk::evaluated(value));
-		self.extend(new_bindings, None, None, None)
+		self.extend_bindings(new_bindings)
 	}
 
 	#[must_use]
-	pub fn extend(
+	pub fn extend_bindings_sup_this(
 		self,
 		new_bindings: FxHashMap<IStr, Thunk<Val>>,
-		new_dollar: Option<ObjValue>,
-		new_sup: Option<ObjValue>,
-		new_this: Option<ObjValue>,
+		sup_this: SupThis,
 	) -> Self {
-		let ctx = &self.0;
-		let dollar = new_dollar.or_else(|| ctx.dollar.clone());
-		let this = new_this.or_else(|| ctx.this.clone());
-		let sup = new_sup.or_else(|| ctx.sup.clone());
+		let ctx = &self;
+		let dollar = ctx
+			.0
+			.dollar
+			.clone()
+			.or_else(|| Some(sup_this.this().clone()));
 		let bindings = if new_bindings.is_empty() {
-			ctx.bindings.clone()
+			ctx.0.bindings.clone()
 		} else {
-			ctx.bindings.clone().extend(new_bindings)
+			ctx.0.bindings.clone().extend(new_bindings)
 		};
-		Self(Cc::new(ContextInternals {
+		Self(Cc::new(ContextInternal {
 			dollar,
-			sup,
-			this,
+			sup_this: Some(sup_this),
 			bindings,
 		}))
 	}
-}
-
-impl PartialEq for Context {
-	fn eq(&self, other: &Self) -> bool {
-		Cc::ptr_eq(&self.0, &other.0)
+	#[must_use]
+	pub fn extend_bindings(self, new_bindings: FxHashMap<IStr, Thunk<Val>>) -> Self {
+		if new_bindings.is_empty() {
+			return self;
+		}
+		let ctx = &self;
+		let bindings = if new_bindings.is_empty() {
+			ctx.0.bindings.clone()
+		} else {
+			ctx.0.bindings.clone().extend(new_bindings)
+		};
+		Self(Cc::new(ContextInternal {
+			dollar: ctx.0.dollar.clone(),
+			sup_this: ctx.0.sup_this.clone(),
+			bindings,
+		}))
 	}
 }
 
+#[derive(Default)]
 pub struct ContextBuilder {
 	bindings: FxHashMap<IStr, Thunk<Val>>,
 	extend: Option<Context>,
@@ -127,20 +156,25 @@
 	pub fn new() -> Self {
 		Self::with_capacity(0)
 	}
+
 	pub fn with_capacity(capacity: usize) -> Self {
 		Self {
 			bindings: FxHashMap::with_capacity(capacity),
 			extend: None,
 		}
 	}
+
 	pub fn extend(parent: Context) -> Self {
 		Self {
 			bindings: FxHashMap::new(),
 			extend: Some(parent),
 		}
 	}
+
 	/// # Panics
-	/// If `name` is already bound
+	///
+	/// If `name` is already bound. Makes no sense to bind same local multiple times,
+	/// unless it is separate context layers.
 	pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
 		let old = self.bindings.insert(name.into(), value);
 		assert!(old.is_none(), "variable bound twice in single context call");
@@ -148,14 +182,12 @@
 	}
 	pub fn build(self) -> Context {
 		if let Some(parent) = self.extend {
-			// TODO: replace self.extend with Result<Context, State>, and remove `state` field
-			parent.extend(self.bindings, None, None, None)
+			parent.extend_bindings(self.bindings)
 		} else {
-			Context(Cc::new(ContextInternals {
+			Context(Cc::new(ContextInternal {
 				bindings: LayeredHashMap::new(self.bindings),
 				dollar: None,
-				sup: None,
-				this: None,
+				sup_this: None,
 			}))
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,11 +1,13 @@
-use std::cell::OnceCell;
+use std::ptr::addr_of;
+use std::{cell::OnceCell, hash::Hasher};
 
+use educe::Educe;
 use jrsonnet_gcmodule::{Cc, Trace};
 
 use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};
 
-// TODO: Replace with OnceCell once in std
-#[derive(Clone, Trace)]
+#[derive(Trace, Educe)]
+#[educe(Clone)]
 pub struct Pending<V: Trace + 'static>(pub Cc<OnceCell<V>>);
 impl<T: Trace + 'static> Pending<T> {
 	pub fn new() -> Self {
@@ -25,7 +27,7 @@
 			.expect("wrapper is filled already");
 	}
 }
-impl<T: Clone + Trace + 'static> Pending<T> {
+impl<T: Trace + 'static + Clone> Pending<T> {
 	/// # Panics
 	/// If wrapper is not yet filled
 	pub fn unwrap(&self) -> T {
@@ -52,3 +54,7 @@
 		Self::new()
 	}
 }
+
+pub fn identity_hash<T, H: Hasher>(v: &Cc<T>, hasher: &mut H) {
+	hasher.write_usize(addr_of!(**v) as usize);
+}
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -119,10 +119,8 @@
 	#[error("binary operation {1} {0} {2} is not implemented")]
 	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),
 
-	#[error("no top level object in this context")]
-	NoTopLevelObjectFound,
-	#[error("self is only usable inside objects")]
-	CantUseSelfOutsideOfObject,
+	#[error("self/super/$ are only usable inside objects")]
+	CantUseSelfSupOutsideOfObject,
 	#[error("no super found")]
 	NoSuperFound,
 
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,18 +11,7 @@
 
 use self::destructure::destruct;
 use crate::{
-	arr::ArrValue,
-	bail,
-	destructure::evaluate_dest,
-	error::{suggest_object_fields, ErrorKind::*},
-	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
-	function::{CallLocation, FuncDesc, FuncVal},
-	gc::WithCapacityExt as _,
-	in_frame,
-	typed::Typed,
-	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
-	Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
-	Unbound, Val,
+	Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt, SupThis, Unbound, Val, arr::ArrValue, bail, destructure::evaluate_dest, error::{ErrorKind::*, suggest_object_fields}, evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op}, function::{CallLocation, FuncDesc, FuncVal}, gc::WithCapacityExt as _, in_frame, typed::Typed, val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk}, with_state
 };
 pub mod destructure;
 pub mod operator;
@@ -126,10 +115,7 @@
 					let fctx = Pending::new();
 					let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());
 					destruct(var, item, fctx.clone(), &mut new_bindings)?;
-					let ctx = ctx
-						.clone()
-						.extend(new_bindings, None, None, None)
-						.into_future(fctx);
+					let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
 
 					evaluate_comp(ctx, &specs[1..], callback)?;
 				}
@@ -169,18 +155,18 @@
 impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}
 
 fn evaluate_object_locals(
-	fctx: Pending<Context>,
+	fctx: Context,
 	locals: Rc<Vec<BindSpec>>,
 ) -> impl CloneableUnbound<Context> {
 	#[derive(Trace, Clone)]
 	struct UnboundLocals {
-		fctx: Pending<Context>,
+		fctx: Context,
 		locals: Rc<Vec<BindSpec>>,
 	}
 	impl Unbound for UnboundLocals {
 		type Bound = Context;
 
-		fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {
+		fn bind(&self, sup_this: SupThis) -> Result<Context> {
 			let fctx = Context::new_future();
 			let mut new_bindings =
 				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());
@@ -188,11 +174,10 @@
 				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
 			}
 
-			let ctx = self.fctx.unwrap();
-			let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());
+			let ctx = self.fctx.clone();
 
 			let ctx = ctx
-				.extend(new_bindings, new_dollar, sup, this)
+				.extend_bindings_sup_this(new_bindings, sup_this)
 				.into_future(fctx);
 
 			Ok(ctx)
@@ -229,8 +214,8 @@
 			}
 			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
 				type Bound = Val;
-				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
-					evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())
+				fn bind(&self, sup_this: SupThis) -> Result<Val> {
+					evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())
 				}
 			}
 
@@ -260,9 +245,9 @@
 			}
 			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {
 				type Bound = Val;
-				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
+				fn bind(&self, sup_this: SupThis) -> Result<Val> {
 					Ok(evaluate_method(
-						self.uctx.bind(sup, this)?,
+						self.uctx.bind(sup_this)?,
 						self.name.clone(),
 						self.params.clone(),
 						self.value.clone(),
@@ -298,10 +283,8 @@
 			.collect::<Vec<_>>(),
 	);
 
-	let fctx = Context::new_future();
-
 	// We have single context for all fields, so we can cache binds
-	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));
+	let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));
 
 	for member in members {
 		match member {
@@ -315,8 +298,8 @@
 					assert: AssertStmt,
 				}
 				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {
-					fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {
-						let ctx = self.uctx.bind(sup, this)?;
+					fn run(&self, sup_this: SupThis) -> Result<()> {
+						let ctx = self.uctx.bind(sup_this)?;
 						evaluate_assert(ctx, &self.assert)
 					}
 				}
@@ -330,9 +313,7 @@
 			}
 		}
 	}
-	let this = builder.build();
-	fctx.fill(ctx.extend(FxHashMap::new(), None, None, Some(this.clone())));
-	Ok(this)
+	Ok(builder.build())
 }
 
 pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {
@@ -347,22 +328,13 @@
 					.cloned()
 					.collect::<Vec<_>>(),
 			);
-			let mut ctxs = vec![];
 			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {
-				let fctx = Context::new_future();
-				ctxs.push((ctx.clone(), fctx.clone()));
-				let uctx = evaluate_object_locals(fctx, locals.clone());
+				let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
 
 				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
 			})?;
 
-			let this = builder.build();
-			for (ctx, fctx) in ctxs {
-				let _ctx = ctx
-					.extend(FxHashMap::new(), None, None, Some(this.clone()))
-					.into_future(fctx);
-			}
-			this
+			builder.build()
 		}
 	})
 }
@@ -428,19 +400,9 @@
 	}
 	let loc = expr.span();
 	Ok(match expr.expr() {
-		Literal(LiteralType::This) => {
-			Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
-		}
-		Literal(LiteralType::Super) => Val::Obj(
-			ctx.super_obj().ok_or(NoSuperFound)?.with_this(
-				ctx.this()
-					.expect("if super exists - then this should too")
-					.clone(),
-			),
-		),
-		Literal(LiteralType::Dollar) => {
-			Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())
-		}
+		Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),
+		Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),
+		Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),
 		Literal(LiteralType::True) => Val::Bool(true),
 		Literal(LiteralType::False) => Val::Bool(false),
 		Literal(LiteralType::Null) => Val::Null,
@@ -452,15 +414,18 @@
 		//
 		// Note that other jsonnet implementations will fail on `if value in (super)` expression,
 		// because the standalone super literal is not supported, that is because in other
-		// implementations `in super` treated differently from in `smth_else`.
+		// implementations `in super` treated differently from `in smth_else`.
 		BinaryOp(field, BinaryOpType::In, e)
 			if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
 		{
-			let Some(super_obj) = ctx.super_obj() else {
+			let sup_this = ctx.try_sup_this()?;
+			// In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.
+			// In jrsonnet, however, this wasn't true, this was kept here for compatibility.
+			if !sup_this.has_super() {
 				return Ok(Val::Bool(false));
-			};
-			let field = evaluate(ctx.clone(), field)?;
-			Val::Bool(super_obj.has_field_ex(field.to_string()?, true))
+			}
+			let field = evaluate(ctx, field)?;
+			Val::Bool(sup_this.field_in_super(field.to_string()?))
 		}
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -473,13 +438,16 @@
 			let mut parts = parts.iter();
 			let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
 				let part = parts.next().expect("at least part should exist");
-				let Some(super_obj) = ctx.super_obj() else {
+				// sup_this existence check might also be skipped here for null-coalesce...
+				// But I believe this might cause errors.
+				let sup_this = ctx.try_sup_this()?;
+				if !sup_this.has_super() {
 					#[cfg(feature = "exp-null-coaelse")]
 					if part.null_coaelse {
 						return Ok(Val::Null);
 					}
 					bail!(NoSuperFound)
-				};
+				}
 				let name = evaluate(ctx.clone(), &part.value)?;
 
 				let Val::Str(name) = name else {
@@ -490,19 +458,19 @@
 					))
 				};
 
-				let this = ctx
-					.this()
-					.expect("no this found, while super present, should not happen");
 				let name = name.into_flat();
-				match super_obj
-					.get_for(name.clone(), this.clone())
+				match sup_this
+					.get_super(name.clone())
 					.with_description_src(&part.value, || format!("field <{name}> access"))?
 				{
 					Some(v) => v,
 					#[cfg(feature = "exp-null-coaelse")]
 					None if part.null_coaelse => return Ok(Val::Null),
 					None => {
-						let suggestions = suggest_object_fields(super_obj, name.clone());
+						let suggestions = suggest_object_fields(
+							&sup_this.standalone_super().expect("super exists"),
+							name.clone(),
+						);
 
 						bail!(NoSuchField(name, suggestions))
 					}
@@ -589,7 +557,7 @@
 			for b in bindings {
 				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
 			}
-			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);
+			let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
 			evaluate(ctx, &returned.clone())?
 		}
 		Arr(items) => {
@@ -652,7 +620,7 @@
 		Slice(value, desc) => {
 			fn parse_idx<T: Typed>(
 				loc: CallLocation<'_>,
-				ctx: &Context,
+				ctx: Context,
 				expr: Option<&LocExpr>,
 				desc: &'static str,
 			) -> Result<Option<T>> {
@@ -660,7 +628,7 @@
 					Ok(in_frame(
 						loc,
 						|| format!("slice {desc}"),
-						|| <Option<T>>::from_untyped(evaluate(ctx.clone(), value)?),
+						|| <Option<T>>::from_untyped(evaluate(ctx, value)?),
 					)?)
 				} else {
 					Ok(None)
@@ -670,9 +638,9 @@
 			let indexable = evaluate(ctx.clone(), value)?;
 			let loc = CallLocation::new(&loc);
 
-			let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;
-			let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;
-			let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;
+			let start = parse_idx(loc, ctx.clone(), desc.start.as_ref(), "start")?;
+			let end = parse_idx(loc, ctx.clone(), desc.end.as_ref(), "end")?;
+			let step = parse_idx(loc, ctx, desc.step.as_ref(), "step")?;
 
 			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
 		}
@@ -681,18 +649,21 @@
 				bail!("computed imports are not supported")
 			};
 			let tmp = loc.clone().0;
-			let s = ctx.state();
-			let resolved_path = s.resolve_from(tmp.source_path(), path)?;
-			match i {
-				Import(_) => in_frame(
-					CallLocation::new(&loc),
-					|| format!("import {:?}", path.clone()),
-					|| s.import_resolved(resolved_path),
-				)?,
-				ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
-				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
-				_ => unreachable!(),
-			}
+			with_state(|s| {
+				let resolved_path = s.resolve_from(tmp.source_path(), path)?;
+				Ok(match i {
+					Import(_) => in_frame(
+						CallLocation::new(&loc),
+						|| format!("import {:?}", path.clone()),
+						|| s.import_resolved(resolved_path),
+					)?,
+					ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
+					ImportBin(_) => {
+						Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))
+					}
+					_ => unreachable!(),
+				}) as Result<Val>
+			})?
 		}
 	})
 }
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -40,7 +40,7 @@
 }
 
 /// Represents Jsonnet function defined in code.
-#[derive(Debug, PartialEq, Trace)]
+#[derive(Debug, Trace, PartialEq)]
 pub struct FuncDesc {
 	/// # Example
 	///
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -129,11 +129,11 @@
 		}
 
 		Ok(body_ctx
-			.extend(passed_args, None, None, None)
-			.extend(defaults, None, None, None)
+			.extend_bindings(passed_args)
+			.extend_bindings(defaults)
 			.into_future(fctx))
 	} else {
-		let body_ctx = body_ctx.extend(passed_args, None, None, None);
+		let body_ctx = body_ctx.extend_bindings(passed_args);
 		Ok(body_ctx)
 	}
 }
@@ -257,7 +257,5 @@
 		}
 	}
 
-	Ok(body_ctx
-		.extend(bindings, None, None, None)
-		.into_future(fctx))
+	Ok(body_ctx.extend_bindings(bindings).into_future(fctx))
 }
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -28,8 +28,10 @@
 	any::Any,
 	cell::{RefCell, RefMut},
 	collections::hash_map::Entry,
+	clone::Clone,
 	fmt::{self, Debug},
 	rc::Rc,
+	marker::PhantomData,
 };
 
 pub use ctx::*;
@@ -65,7 +67,7 @@
 	/// Type of value after object context is bound
 	type Bound;
 	/// Create value bound to specified object context
-	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
+	fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;
 }
 
 /// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
@@ -85,9 +87,9 @@
 }
 impl MaybeUnbound {
 	/// Attach object context to value, if required
-	pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
+	pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {
 		match self {
-			Self::Unbound(v) => v.0.bind(sup, this),
+			Self::Unbound(v) => v.0.bind(sup_this),
 			Self::Bound(v) => Ok(v.evaluate()?),
 		}
 	}
@@ -105,8 +107,8 @@
 	/// Initialize default file context.
 	/// Has default implementation, which calls `populate`.
 	/// Prefer to always implement `populate` instead.
-	fn initialize(&self, state: State, for_file: Source) -> Context {
-		let mut builder = ContextBuilder::with_capacity(state, self.reserve_vars());
+	fn initialize(&self, for_file: Source) -> Context {
+		let mut builder = ContextBuilder::with_capacity(self.reserve_vars());
 		self.populate(for_file, &mut builder);
 		builder.build()
 	}
@@ -130,11 +132,11 @@
 where
 	T: ContextInitializer,
 {
-	fn initialize(&self, state: State, for_file: Source) -> Context {
+	fn initialize(&self, for_file: Source) -> Context {
 		if let Some(ctx) = self {
-			ctx.initialize(state, for_file)
+			ctx.initialize(for_file)
 		} else {
-			().initialize(state, for_file)
+			().initialize(for_file)
 		}
 	}
 
@@ -237,7 +239,40 @@
 #[derive(Clone, Trace)]
 pub struct State(Cc<EvaluationStateInternals>);
 
+thread_local! {
+	pub static DEFAULT_STATE: State = State::builder().build();
+	pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};
+}
+pub struct StateEnterGuard(PhantomData<()>);
+impl Drop for StateEnterGuard {
+	fn drop(&mut self) {
+		STATE.with_borrow_mut(|v| *v = None);
+	}
+}
+
+pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {
+	if let Some(state) = STATE.with_borrow(Clone::clone) {
+		v(state)
+	} else {
+		let s = DEFAULT_STATE.with(Clone::clone);
+		v(s)
+	}
+}
+
 impl State {
+	pub fn enter(&self) -> StateEnterGuard {
+		self.try_enter().expect("entered state already exists")
+	}
+	pub fn try_enter(&self) -> Option<StateEnterGuard> {
+		STATE.with_borrow_mut(|v| {
+			if v.is_none() {
+				*v = Some(self.clone());
+				Some(StateEnterGuard(PhantomData))
+			} else {
+				None
+			}
+		})
+	}
 	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
 	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {
 		let mut file_cache = self.file_cache();
@@ -359,7 +394,7 @@
 
 	/// Creates context with all passed global variables
 	pub fn create_default_context(&self, source: Source) -> Context {
-		self.context_initializer().initialize(self.clone(), source)
+		self.context_initializer().initialize(source)
 	}
 
 	/// Creates context with all passed global variables, calling custom modifier
@@ -370,7 +405,6 @@
 	) -> Context {
 		let default_initializer = self.context_initializer();
 		let mut builder = ContextBuilder::with_capacity(
-			self.clone(),
 			default_initializer.reserve_vars() + context_initializer.reserve_vars(),
 		);
 		default_initializer.populate(source.clone(), &mut builder);
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -4,14 +4,14 @@
 
 use crate::{gc::WithCapacityExt as _, Thunk, Val};
 
-#[derive(Trace)]
+#[derive(Trace, Debug)]
 #[trace(tracking(force))]
 pub struct LayeredHashMapInternals {
 	parent: Option<LayeredHashMap>,
 	current: FxHashMap<IStr, Thunk<Val>>,
 }
 
-#[derive(Trace)]
+#[derive(Trace, Debug)]
 pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
 
 impl LayeredHashMap {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{Span, Visibility};12use rustc_hash::{FxHashMap, FxHashSet};1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	bail,17	error::{suggest_object_fields, Error, ErrorKind::*},18	function::{CallLocation, FuncVal},19	gc::WithCapacityExt as _,20	in_frame,21	operator::evaluate_add_op,22	val::ArrValue,23	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28	#![allow(29		// This module works as stub for preserve-order feature30		clippy::unused_self,31	)]3233	use jrsonnet_gcmodule::Trace;3435	#[derive(Clone, Copy, Default, Debug, Trace)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub const fn next(self) -> Self {39			Self(())40		}41	}4243	#[derive(Clone, Copy, Default, Debug, Trace)]44	pub struct SuperDepth(());45	impl SuperDepth {46		pub const fn deeper(self) -> Self {47			Self(())48		}49	}5051	#[derive(Clone, Copy)]52	pub struct FieldSortKey(());53	impl FieldSortKey {54		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55			Self(())56		}57	}58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62	use std::cmp::Reverse;6364	use jrsonnet_gcmodule::Trace;6566	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67	pub struct FieldIndex(u32);68	impl FieldIndex {69		pub fn next(self) -> Self {70			Self(self.0 + 1)71		}72	}7374	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75	pub struct SuperDepth(u32);76	impl SuperDepth {77		pub fn deeper(self) -> Self {78			Self(self.0 + 1)79		}80	}8182	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84	impl FieldSortKey {85		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86			Self(Reverse(depth), index)87		}88	}89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};9293// 0 - add94//  12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98	fn new(add: bool, visibility: Visibility) -> Self {99		let mut v = 0;100		if add {101			v |= 1;102		}103		v |= match visibility {104			Visibility::Normal => 0b000,105			Visibility::Hidden => 0b010,106			Visibility::Unhide => 0b100,107		};108		Self(v)109	}110	pub fn add(&self) -> bool {111		self.0 & 1 != 0112	}113	pub fn visibility(&self) -> Visibility {114		match (self.0 & 0b110) >> 1 {115			0b00 => Visibility::Normal,116			0b01 => Visibility::Hidden,117			0b10 => Visibility::Unhide,118			_ => unreachable!(),119		}120	}121}122impl Debug for ObjFieldFlags {123	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124		f.debug_struct("ObjFieldFlags")125			.field("add", &self.add())126			.field("visibility", &self.visibility())127			.finish()128	}129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134	#[trace(skip)]135	flags: ObjFieldFlags,136	original_index: FieldIndex,137	pub invoke: MaybeUnbound,138	pub location: Option<Span>,139}140141cc_dyn!(CcObjectAssertion, ObjectAssertion);142pub trait ObjectAssertion: Trace {143	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;144}145146// Field => This147148#[derive(Trace)]149enum CacheValue {150	Cached(Val),151	NotFound,152	Pending,153	Errored(Error),154}155156#[allow(clippy::module_name_repetitions)]157#[derive(Trace)]158#[trace(tracking(force))]159pub struct OopObject {160	sup: Option<ObjValue>,161	// this: Option<ObjValue>,162	assertions: Cc<Vec<CcObjectAssertion>>,163	assertions_ran: RefCell<FxHashSet<ObjValue>>,164	this_entries: Cc<FxHashMap<IStr, ObjMember>>,165	value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,166}167impl Debug for OopObject {168	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {169		f.debug_struct("OopObject")170			.field("sup", &self.sup)171			// .field("assertions", &self.assertions)172			// .field("assertions_ran", &self.assertions_ran)173			.field("this_entries", &self.this_entries)174			// .field("value_cache", &self.value_cache)175			.finish_non_exhaustive()176	}177}178179type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;180181pub trait ObjectLike: Trace + Any + Debug {182	fn extend_from(&self, sup: ObjValue) -> ObjValue;183	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed184	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {185		ObjValue::new(ThisOverride { inner: me, this })186	}187	fn this(&self) -> Option<ObjValue> {188		None189	}190	fn len(&self) -> usize;191	fn is_empty(&self) -> bool;192	// If callback returns false, iteration stops193	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;194195	fn has_field_include_hidden(&self, name: IStr) -> bool;196	fn has_field(&self, name: IStr) -> bool;197198	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;200	fn field_visibility(&self, field: IStr) -> Option<Visibility>;201202	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;203}204205#[derive(Clone, Trace)]206pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<dyn ObjectLike>);207208impl PartialEq for WeakObjValue {209	fn eq(&self, other: &Self) -> bool {210		Weak::ptr_eq(&self.0, &other.0)211	}212}213214impl Eq for WeakObjValue {}215impl Hash for WeakObjValue {216	fn hash<H: Hasher>(&self, hasher: &mut H) {217		// Safety: usize is POD218		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };219		hasher.write_usize(addr);220	}221}222223cc_dyn!(224	#[derive(Clone, Debug)]225	ObjValue, ObjectLike,226	pub fn new() {...}227);228229#[derive(Debug, Trace)]230struct EmptyObject;231impl ObjectLike for EmptyObject {232	fn extend_from(&self, sup: ObjValue) -> ObjValue {233		// obj + {} == obj234		sup235	}236237	fn this(&self) -> Option<ObjValue> {238		None239	}240241	fn len(&self) -> usize {242		0243	}244245	fn is_empty(&self) -> bool {246		true247	}248249	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {250		false251	}252253	fn has_field_include_hidden(&self, _name: IStr) -> bool {254		false255	}256257	fn has_field(&self, _name: IStr) -> bool {258		false259	}260261	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262		Ok(None)263	}264	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {265		Ok(None)266	}267268	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {269		Ok(())270	}271272	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {273		None274	}275}276277#[derive(Trace, Debug)]278struct ThisOverride {279	inner: ObjValue,280	this: ObjValue,281}282impl ObjectLike for ThisOverride {283	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {284		ObjValue::new(Self {285			inner: self.inner.clone(),286			this,287		})288	}289290	fn extend_from(&self, sup: ObjValue) -> ObjValue {291		self.inner.extend_from(sup).with_this(self.this.clone())292	}293294	fn this(&self) -> Option<ObjValue> {295		Some(self.this.clone())296	}297298	fn len(&self) -> usize {299		self.inner.len()300	}301302	fn is_empty(&self) -> bool {303		self.inner.is_empty()304	}305306	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {307		self.inner.enum_fields(depth, handler)308	}309310	fn has_field_include_hidden(&self, name: IStr) -> bool {311		self.inner.has_field_include_hidden(name)312	}313314	fn has_field(&self, name: IStr) -> bool {315		self.inner.has_field(name)316	}317318	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {319		self.inner.get_for(key, this)320	}321322	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {323		self.inner.get_raw(key, this)324	}325326	fn field_visibility(&self, field: IStr) -> Option<Visibility> {327		self.inner.field_visibility(field)328	}329330	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {331		self.inner.run_assertions_raw(this)332	}333}334335impl ObjValue {336	pub fn new_empty() -> Self {337		Self::new(EmptyObject)338	}339	pub fn builder() -> ObjValueBuilder {340		ObjValueBuilder::new()341	}342	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343		ObjValueBuilder::with_capacity(capacity)344	}345	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346		let mut out = ObjValueBuilder::with_capacity(1);347		out.with_super(self);348		let mut member = out.field(key);349		if value.flags.add() {350			member = member.add();351		}352		if let Some(loc) = value.location {353			member = member.with_location(loc);354		}355		let _ = member356			.with_visibility(value.flags.visibility())357			.binding(value.invoke);358		out.build()359	}360	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362	}363364	#[must_use]365	pub fn extend_from(&self, sup: Self) -> Self {366		self.0.extend_from(sup)367	}368	#[must_use]369	pub fn with_this(&self, this: Self) -> Self {370		self.0.with_this(self.clone(), this)371	}372	pub fn len(&self) -> usize {373		self.0.len()374	}375	pub fn is_empty(&self) -> bool {376		self.0.is_empty()377	}378	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379		self.0.enum_fields(depth, handler)380	}381382	pub fn has_field_include_hidden(&self, name: IStr) -> bool {383		self.0.has_field_include_hidden(name)384	}385	pub fn has_field(&self, name: IStr) -> bool {386		self.0.has_field(name)387	}388	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389		if include_hidden {390			self.has_field_include_hidden(name)391		} else {392			self.has_field(name)393		}394	}395396	pub fn get(&self, key: IStr) -> Result<Option<Val>> {397		self.run_assertions()?;398		self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399	}400401	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402		self.0.get_for(key, this)403	}404405	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406		let Some(value) = self.get(key.clone())? else {407			let suggestions = suggest_object_fields(self, key.clone());408			bail!(NoSuchField(key, suggestions))409		};410		Ok(value)411	}412413	fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414		self.0.get_for_uncached(key, this)415	}416417	fn field_visibility(&self, field: IStr) -> Option<Visibility> {418		self.0.field_visibility(field)419	}420421	pub fn run_assertions(&self) -> Result<()> {422		// FIXME: Should it use `self.0.this()` in case of standalone super?423		self.run_assertions_raw(self.clone())424	}425	fn run_assertions_raw(&self, this: Self) -> Result<()> {426		self.0.run_assertions_raw(this)427	}428429	pub fn iter(430		&self,431		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,432	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433		let fields = self.fields(434			#[cfg(feature = "exp-preserve-order")]435			preserve_order,436		);437		fields.into_iter().map(|field| {438			(439				field.clone(),440				self.get(field)441					.map(|opt| opt.expect("iterating over keys, field exists")),442			)443		})444	}445	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446		if !self.has_field_ex(key.clone(), true) {447			return None;448		}449		let obj = self.clone();450451		Some(Thunk!(move || Ok(obj.get(key)?.expect("field exists"))))452	}453	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {454		let obj = self.clone();455		Thunk!(move || obj.get_or_bail(key))456	}457	pub fn ptr_eq(a: &Self, b: &Self) -> bool {458		Cc::ptr_eq(&a.0, &b.0)459	}460	pub fn downgrade(self) -> WeakObjValue {461		WeakObjValue(self.0.downgrade())462	}463	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {464		let mut out = FxHashMap::default();465		self.enum_fields(466			SuperDepth::default(),467			&mut |depth, index, name, visibility| {468				let new_sort_key = FieldSortKey::new(depth, index);469				let entry = out.entry(name);470				let (visible, _) = entry.or_insert((true, new_sort_key));471				match visibility {472					Visibility::Normal => {}473					Visibility::Hidden => {474						*visible = false;475					}476					Visibility::Unhide => {477						*visible = true;478					}479				};480				false481			},482		);483		out484	}485	pub fn fields_ex(486		&self,487		include_hidden: bool,488		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,489	) -> Vec<IStr> {490		#[cfg(feature = "exp-preserve-order")]491		if preserve_order {492			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self493				.fields_visibility()494				.into_iter()495				.filter(|(_, (visible, _))| include_hidden || *visible)496				.enumerate()497				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))498				.unzip();499			keys.sort_unstable_by_key(|v| v.0);500			// Reorder in-place by resulting indexes501			for i in 0..fields.len() {502				let x = fields[i].clone();503				let mut j = i;504				loop {505					let k = keys[j].1;506					keys[j].1 = j;507					if k == i {508						break;509					}510					fields[j] = fields[k].clone();511					j = k;512				}513				fields[j] = x;514			}515			return fields;516		}517518		let mut fields: Vec<_> = self519			.fields_visibility()520			.into_iter()521			.filter(|(_, (visible, _))| include_hidden || *visible)522			.map(|(k, _)| k)523			.collect();524		fields.sort_unstable();525		fields526	}527	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {528		self.fields_ex(529			false,530			#[cfg(feature = "exp-preserve-order")]531			preserve_order,532		)533	}534	pub fn values_ex(535		&self,536		include_hidden: bool,537		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,538	) -> ArrValue {539		ArrValue::new(PickObjectValues::new(540			self.clone(),541			self.fields_ex(542				include_hidden,543				#[cfg(feature = "exp-preserve-order")]544				preserve_order,545			),546		))547	}548	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {549		self.values_ex(550			false,551			#[cfg(feature = "exp-preserve-order")]552			preserve_order,553		)554	}555	pub fn key_values_ex(556		&self,557		include_hidden: bool,558		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,559	) -> ArrValue {560		ArrValue::new(PickObjectKeyValues::new(561			self.clone(),562			self.fields_ex(563				include_hidden,564				#[cfg(feature = "exp-preserve-order")]565				preserve_order,566			),567		))568	}569	pub fn key_values(570		&self,571		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,572	) -> ArrValue {573		self.key_values_ex(574			false,575			#[cfg(feature = "exp-preserve-order")]576			preserve_order,577		)578	}579}580581impl OopObject {582	pub fn new(583		sup: Option<ObjValue>,584		this_entries: Cc<FxHashMap<IStr, ObjMember>>,585		assertions: Cc<Vec<CcObjectAssertion>>,586	) -> Self {587		Self {588			sup,589			// this: None,590			assertions,591			assertions_ran: RefCell::new(FxHashSet::new()),592			this_entries,593			value_cache: RefCell::new(FxHashMap::new()),594		}595	}596597	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {598		v.invoke.evaluate(self.sup.clone(), Some(real_this))599	}600601	// FIXME: Duplication between ObjValue and OopObject602	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {603		let mut out = FxHashMap::default();604		self.enum_fields(605			SuperDepth::default(),606			&mut |depth, index, name, visibility| {607				let new_sort_key = FieldSortKey::new(depth, index);608				let entry = out.entry(name);609				let (visible, _) = entry.or_insert((true, new_sort_key));610				match visibility {611					Visibility::Normal => {}612					Visibility::Hidden => {613						*visible = false;614					}615					Visibility::Unhide => {616						*visible = true;617					}618				};619				false620			},621		);622		out623	}624}625626impl ObjectLike for OopObject {627	fn extend_from(&self, sup: ObjValue) -> ObjValue {628		ObjValue::new(match &self.sup {629			None => Self::new(630				Some(sup),631				self.this_entries.clone(),632				self.assertions.clone(),633			),634			Some(v) => Self::new(635				Some(v.extend_from(sup)),636				self.this_entries.clone(),637				self.assertions.clone(),638			),639		})640	}641642	fn len(&self) -> usize {643		// Maybe it will be better to not compute sort key here?644		self.fields_visibility()645			.into_iter()646			.filter(|(_, (visible, _))| *visible)647			.count()648	}649650	/// Returns false only if there is any visible entry.651	///652	/// Note that object with hidden fields `{a:: 1}` will be reported as empty here.653	fn is_empty(&self) -> bool {654		self.len() == 0655	}656657	/// Run callback for every field found in object658	///659	/// Returns true if ended prematurely660	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {661		if let Some(s) = &self.sup {662			if s.enum_fields(depth.deeper(), handler) {663				return true;664			}665		}666		for (name, member) in self.this_entries.iter() {667			if handler(668				depth,669				member.original_index,670				name.clone(),671				member.flags.visibility(),672			) {673				return true;674			}675		}676		false677	}678679	fn has_field_include_hidden(&self, name: IStr) -> bool {680		if self.this_entries.contains_key(&name) {681			true682		} else if let Some(super_obj) = &self.sup {683			super_obj.has_field_include_hidden(name)684		} else {685			false686		}687	}688	fn has_field(&self, name: IStr) -> bool {689		self.field_visibility(name)690			.map_or(false, |v| v.is_visible())691	}692693	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {694		let cache_key = (key.clone(), Some(this.clone().downgrade()));695		if let Some(v) = self.value_cache.borrow().get(&cache_key) {696			return Ok(match v {697				CacheValue::Cached(v) => Some(v.clone()),698				CacheValue::NotFound => None,699				CacheValue::Pending => bail!(InfiniteRecursionDetected),700				CacheValue::Errored(e) => return Err(e.clone()),701			});702		}703		self.value_cache704			.borrow_mut()705			.insert(cache_key.clone(), CacheValue::Pending);706		let value = self.get_for_uncached(key, this).inspect_err(|e| {707			self.value_cache708				.borrow_mut()709				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));710		})?;711		self.value_cache.borrow_mut().insert(712			cache_key,713			value714				.as_ref()715				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),716		);717		Ok(value)718	}719	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {720		match (self.this_entries.get(&key), &self.sup) {721			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),722			(Some(k), Some(super_obj)) => {723				let our = self.evaluate_this(k, real_this.clone())?;724				if k.flags.add() {725					super_obj726						.get_raw(key, real_this)?727						.map_or(Ok(Some(our.clone())), |v| {728							Ok(Some(evaluate_add_op(&v, &our)?))729						})730				} else {731					Ok(Some(our))732				}733			}734			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),735			(None, None) => Ok(None),736		}737	}738	fn field_visibility(&self, name: IStr) -> Option<Visibility> {739		if let Some(m) = self.this_entries.get(&name) {740			Some(match &m.flags.visibility() {741				Visibility::Normal => self742					.sup743					.as_ref()744					.and_then(|super_obj| super_obj.field_visibility(name))745					.unwrap_or(Visibility::Normal),746				v => *v,747			})748		} else if let Some(super_obj) = &self.sup {749			super_obj.field_visibility(name)750		} else {751			None752		}753	}754755	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {756		if self.assertions.is_empty() {757			if let Some(super_obj) = &self.sup {758				super_obj.run_assertions_raw(real_this)?;759			}760			return Ok(());761		}762		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {763			for assertion in self.assertions.iter() {764				if let Err(e) = assertion.0.run(self.sup.clone(), Some(real_this.clone())) {765					self.assertions_ran.borrow_mut().remove(&real_this);766					return Err(e);767				}768			}769			if let Some(super_obj) = &self.sup {770				super_obj.run_assertions_raw(real_this)?;771			}772		}773		Ok(())774	}775}776777impl PartialEq for ObjValue {778	fn eq(&self, other: &Self) -> bool {779		Cc::ptr_eq(&self.0, &other.0)780	}781}782783impl Eq for ObjValue {}784impl Hash for ObjValue {785	fn hash<H: Hasher>(&self, hasher: &mut H) {786		hasher.write_usize(addr_of!(*self.0).expose_provenance() as usize);787	}788}789790#[allow(clippy::module_name_repetitions)]791pub struct ObjValueBuilder {792	sup: Option<ObjValue>,793	map: FxHashMap<IStr, ObjMember>,794	assertions: Vec<CcObjectAssertion>,795	next_field_index: FieldIndex,796}797impl ObjValueBuilder {798	pub fn new() -> Self {799		Self::with_capacity(0)800	}801	pub fn with_capacity(capacity: usize) -> Self {802		Self {803			sup: None,804			map: FxHashMap::with_capacity(capacity),805			assertions: Vec::new(),806			next_field_index: FieldIndex::default(),807		}808	}809	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {810		self.assertions.reserve_exact(capacity);811		self812	}813	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {814		self.sup = Some(super_obj);815		self816	}817818	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {819		self.assertions.push(CcObjectAssertion::new(assertion));820		self821	}822	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {823		let field_index = self.next_field_index;824		self.next_field_index = self.next_field_index.next();825		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)826	}827	/// Preset for common method definiton pattern:828	/// Create a hidden field with the function value.829	///830	/// `.field(name).hide().value(Val::function(value))`831	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {832		self.field(name).hide().value(Val::Func(value.into()));833		self834	}835	pub fn try_method(836		&mut self,837		name: impl Into<IStr>,838		value: impl Into<FuncVal>,839	) -> Result<&mut Self> {840		self.field(name).hide().try_value(Val::Func(value.into()))?;841		Ok(self)842	}843844	pub fn build(self) -> ObjValue {845		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {846			return ObjValue::new_empty();847		}848		ObjValue::new(OopObject::new(849			self.sup,850			Cc::new(self.map),851			Cc::new(self.assertions),852		))853	}854}855impl Default for ObjValueBuilder {856	fn default() -> Self {857		Self::with_capacity(0)858	}859}860861#[allow(clippy::module_name_repetitions)]862#[must_use = "value not added unless binding() was called"]863pub struct ObjMemberBuilder<Kind> {864	kind: Kind,865	name: IStr,866	add: bool,867	visibility: Visibility,868	original_index: FieldIndex,869	location: Option<Span>,870}871872#[allow(clippy::missing_const_for_fn)]873impl<Kind> ObjMemberBuilder<Kind> {874	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {875		Self {876			kind,877			name,878			original_index,879			add: false,880			visibility: Visibility::Normal,881			location: None,882		}883	}884885	pub const fn with_add(mut self, add: bool) -> Self {886		self.add = add;887		self888	}889	pub fn add(self) -> Self {890		self.with_add(true)891	}892	pub fn with_visibility(mut self, visibility: Visibility) -> Self {893		self.visibility = visibility;894		self895	}896	pub fn hide(self) -> Self {897		self.with_visibility(Visibility::Hidden)898	}899	pub fn with_location(mut self, location: Span) -> Self {900		self.location = Some(location);901		self902	}903	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {904		(905			self.kind,906			self.name,907			ObjMember {908				flags: ObjFieldFlags::new(self.add, self.visibility),909				original_index: self.original_index,910				invoke: binding,911				location: self.location,912			},913		)914	}915}916917pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);918impl ObjMemberBuilder<ValueBuilder<'_>> {919	/// Inserts value, replacing if it is already defined920	pub fn value(self, value: impl Into<Val>) {921		let (receiver, name, member) =922			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));923		let entry = receiver.0.map.entry(name);924		entry.insert_entry(member);925	}926927	/// Tries to insert value, returns an error if it was already defined928	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {929		self.try_thunk(Thunk::evaluated(value.into()))930	}931	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {932		self.binding(MaybeUnbound::Bound(value.into()))933	}934	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {935		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))936	}937	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {938		let (receiver, name, member) = self.build_member(binding);939		let location = member.location.clone();940		let old = receiver.0.map.insert(name.clone(), member);941		if old.is_some() {942			in_frame(943				CallLocation(location.as_ref()),944				|| format!("field <{}> initializtion", name.clone()),945				|| bail!(DuplicateFieldName(name.clone())),946			)?;947		}948		Ok(())949	}950}951952pub struct ExtendBuilder<'v>(&'v mut ObjValue);953impl ObjMemberBuilder<ExtendBuilder<'_>> {954	pub fn value(self, value: impl Into<Val>) {955		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));956	}957	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {958		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));959	}960	pub fn binding(self, binding: MaybeUnbound) {961		let (receiver, name, member) = self.build_member(binding);962		let new = receiver.0.clone();963		*receiver.0 = new.extend_with_raw_member(name, member);964	}965}
after · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any, cell::{Cell, RefCell}, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}3};45use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};6use educe::Educe;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{Span, Visibility};9use rustc_hash::{FxHashMap, FxHashSet};1011use crate::{12	arr::{PickObjectKeyValues, PickObjectValues},13	bail,14	error::{suggest_object_fields, ErrorKind::*},15	function::{CallLocation, FuncVal},16	gc::WithCapacityExt as _,17	in_frame,18	identity_hash, 19	operator::evaluate_add_op,20	val::ArrValue,21	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,22};2324#[cfg(not(feature = "exp-preserve-order"))]25mod ordering {26	#![allow(27		// This module works as stub for preserve-order feature28		clippy::unused_self,29	)]3031	use jrsonnet_gcmodule::Trace;3233	#[derive(Clone, Copy, Default, Debug, Trace)]34	pub struct FieldIndex(());35	impl FieldIndex {36		pub const fn next(self) -> Self {37			Self(())38		}39	}4041	#[derive(Clone, Copy, Default, Debug, Trace)]42	pub struct SuperDepth(());43	impl SuperDepth {44		pub(super) fn deepen(self) {}45	}4647	#[derive(Clone, Copy, Debug)]48	pub struct FieldSortKey(());49	impl FieldSortKey {50		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {51			Self(())52		}53	}54}5556#[cfg(feature = "exp-preserve-order")]57mod ordering {58	use std::cmp::Reverse;5960	use jrsonnet_gcmodule::Trace;6162	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]63	pub struct FieldIndex(u32);64	impl FieldIndex {65		pub fn next(self) -> Self {66			Self(self.0 + 1)67		}68	}6970	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]71	pub struct SuperDepth(u32);72	impl SuperDepth {73		pub(super) fn deepen(&mut self) {74			*self.0 += 175		}76	}7778	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]79	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);80	impl FieldSortKey {81		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {82			Self(Reverse(depth), index)83		}84	}85}8687use ordering::{FieldIndex, FieldSortKey, SuperDepth};8889// 0 - add90//  12 - visibility91#[derive(Clone, Copy)]92pub struct ObjFieldFlags(u8);93impl ObjFieldFlags {94	fn new(add: bool, visibility: Visibility) -> Self {95		let mut v = 0;96		if add {97			v |= 1;98		}99		v |= match visibility {100			Visibility::Normal => 0b000,101			Visibility::Hidden => 0b010,102			Visibility::Unhide => 0b100,103		};104		Self(v)105	}106	pub fn add(&self) -> bool {107		self.0 & 1 != 0108	}109	pub fn visibility(&self) -> Visibility {110		match (self.0 & 0b110) >> 1 {111			0b00 => Visibility::Normal,112			0b01 => Visibility::Hidden,113			0b10 => Visibility::Unhide,114			_ => unreachable!(),115		}116	}117}118impl Debug for ObjFieldFlags {119	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120		f.debug_struct("ObjFieldFlags")121			.field("add", &self.add())122			.field("visibility", &self.visibility())123			.finish()124	}125}126127#[allow(clippy::module_name_repetitions)]128#[derive(Debug, Trace)]129pub struct ObjMember {130	#[trace(skip)]131	flags: ObjFieldFlags,132	original_index: FieldIndex,133	pub invoke: MaybeUnbound,134	pub location: Option<Span>,135}136137cc_dyn!(CcObjectAssertion, ObjectAssertion);138pub trait ObjectAssertion: Trace {139	fn run(&self, sup_this: SupThis) -> Result<()>;140}141142// Field => This143144#[derive(Trace, Debug)]145enum CacheValue {146	Cached(Result<Option<Val>>),147	Pending,148}149150#[allow(clippy::module_name_repetitions)]151#[derive(Trace)]152#[trace(tracking(force))]153pub struct OopObject {154	// this: Option<ObjValue>,155	assertions: Cc<Vec<CcObjectAssertion>>,156	this_entries: Cc<FxHashMap<IStr, ObjMember>>,157	value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,158}159impl Debug for OopObject {160	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {161		f.debug_struct("OopObject")162			// .field("assertions", &self.assertions)163			// .field("assertions_ran", &self.assertions_ran)164			.field("this_entries", &self.this_entries)165			// .field("value_cache", &self.value_cache)166			.finish_non_exhaustive()167	}168}169170type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;171172#[derive(Trace, Clone)]173pub enum ValueProcess {174	None,175	SuperPlus,176}177178pub trait ObjectCore: Trace + Any + Debug {179	// If callback returns false, iteration stops, and this call returns false.180	fn enum_fields_core(181		&self,182		super_depth: &mut SuperDepth,183		handler: &mut EnumFieldsHandler<'_>,184	) -> bool;185186	fn has_field_include_hidden(&self, name: IStr) -> bool;187188	fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>>;189	// fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<(Val, ValueProcess)>>;190	fn field_visibility(&self, field: IStr) -> Option<Visibility>;191192	fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()>;193}194195#[derive(Clone, Trace)]196pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);197impl Debug for WeakObjValue {198	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {199		f.debug_tuple("WeakObjValue").finish()200	}201}202203impl PartialEq for WeakObjValue {204	fn eq(&self, other: &Self) -> bool {205		Weak::ptr_eq(&self.0, &other.0)206	}207}208209impl Eq for WeakObjValue {}210impl Hash for WeakObjValue {211	fn hash<H: Hasher>(&self, hasher: &mut H) {212		// Safety: usize is POD213		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };214		hasher.write_usize(addr);215	}216}217218cc_dyn!(219	#[derive(Clone, Debug)]220	ObjCore, ObjectCore,221	pub fn new() {...}222);223#[derive(Trace, Educe)]224#[educe(Debug)]225struct ObjValueInner {226	cores: Vec<ObjCore>,227	assertions_ran: Cell<bool>,228	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,229}230231thread_local! {232	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();233}234fn is_asserting(obj: &ObjValue) -> bool {235	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))236}237/// Returns false if already asserting238fn start_asserting(obj: &ObjValue) -> bool {239	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))240}241fn finish_asserting(obj: &ObjValue) {242	RUNNING_ASSERTIONS.with_borrow_mut(|v| {243		let r = v.remove(obj);244		debug_assert!(245			r,246			"finish_asserting was called before start_asserting or twice"247		);248	});249}250251#[allow(clippy::module_name_repetitions)]252#[derive(Clone, Trace, Debug, Educe)]253#[educe(PartialEq, Hash, Eq)]254pub struct ObjValue(255	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,256);257258#[derive(Trace, Debug)]259struct StandaloneSuperCore {260	sup: CoreIdx,261	this: ObjValue,262}263impl ObjectCore for StandaloneSuperCore {264	fn enum_fields_core(265		&self,266		super_depth: &mut SuperDepth,267		handler: &mut EnumFieldsHandler<'_>,268	) -> bool {269		self.this270			.enum_fields_internal(super_depth, handler, self.sup)271	}272273	fn has_field_include_hidden(&self, name: IStr) -> bool {274		self.this.has_field_include_hidden_idx(name, self.sup)275	}276277	fn get_for(&self, key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {278		let v = self.this.get_idx(key, self.sup)?;279		Ok(v.map(|v| (v, ValueProcess::None)))280	}281282	fn field_visibility(&self, field: IStr) -> Option<Visibility> {283		self.this.field_visibility_idx(field, self.sup)284	}285286	fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {287		self.this.run_assertions()288	}289}290291#[derive(Debug, Trace)]292struct EmptyObject;293impl ObjectCore for EmptyObject {294	fn enum_fields_core(295		&self,296		_super_depth: &mut SuperDepth,297		_handler: &mut EnumFieldsHandler<'_>,298	) -> bool {299		true300	}301302	fn has_field_include_hidden(&self, _name: IStr) -> bool {303		false304	}305306	fn get_for(&self, _key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {307		Ok(None)308	}309310	fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {311		Ok(())312	}313314	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {315		None316	}317}318319#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]320struct CoreIdx {321	idx: usize,322}323impl CoreIdx {324	fn super_exists(self) -> bool {325		self.idx != 0326	}327}328#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]329pub struct SupThis {330	sup: CoreIdx,331	this: ObjValue,332}333impl SupThis {334	pub fn has_super(&self) -> bool {335		self.sup.super_exists()336	}337	/// Implementation of `"field" in super` operation,338	/// works faster than standalone super path.339	///340	/// In case of no `super` existence, returns false.341	pub fn field_in_super(&self, field: IStr) -> bool {342		self.this.has_field_include_hidden_idx(field, self.sup)343	}344	/// Implementation of `super.field` operation,345	/// works faster than standalone super path.346	///347	/// In case of no `super` existence, returns `NoSuperFound`348	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {349		if !self.sup.super_exists() {350			bail!(NoSuperFound);351		}352		self.this.get_idx(field, self.sup)353	}354	/// `super` with `self` overriden for top-level lookups.355	/// Exists when super appears outside of `super.field`/`"field" in super` expressions356	/// Exclusive to jrsonnet.357	///358	/// Might return `NoSuperFound` error.359	pub fn standalone_super(&self) -> Result<ObjValue> {360		if !self.sup.super_exists() {361			bail!(NoSuperFound)362		}363		Ok(ObjValue::new(StandaloneSuperCore {364			sup: self.sup,365			this: self.this.clone(),366		}))367	}368	pub fn this(&self) -> &ObjValue {369		&self.this370	}371	pub fn downgrade(self) -> WeakSupThis {372		WeakSupThis {373			sup: self.sup,374			this: self.this.downgrade(),375		}376	}377}378#[derive(Trace, PartialEq, Eq, Hash, Debug)]379pub struct WeakSupThis {380	sup: CoreIdx,381	this: WeakObjValue,382}383384impl ObjValue {385	pub fn new(v: impl ObjectCore) -> Self {386		Self(Cc::new(ObjValueInner {387			cores: vec![ObjCore::new(v)],388			assertions_ran: Cell::new(false),389			value_cache: RefCell::new(FxHashMap::new()),390		}))391	}392	pub fn new_empty() -> Self {393		Self::new(EmptyObject)394	}395	pub fn builder() -> ObjValueBuilder {396		ObjValueBuilder::new()397	}398	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {399		ObjValueBuilder::with_capacity(capacity)400	}401	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {402		let mut out = ObjValueBuilder::with_capacity(1);403		out.with_super(self);404		let mut member = out.field(key);405		if value.flags.add() {406			member = member.add();407		}408		if let Some(loc) = value.location {409			member = member.with_location(loc);410		}411		let _ = member412			.with_visibility(value.flags.visibility())413			.binding(value.invoke);414		out.build()415	}416	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {417		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())418	}419420	#[must_use]421	pub fn extend_from(&self, sup: Self) -> Self {422		let mut cores = sup.0.cores.clone();423		cores.extend(self.0.cores.iter().cloned());424		ObjValue(Cc::new(ObjValueInner {425			cores,426			value_cache: RefCell::default(),427			assertions_ran: Cell::new(false),428		}))429	}430	// #[must_use]431	// pub fn with_this(&self, this: Self) -> Self {432	// 	self.0.with_this(self.clone(), this)433	// }434	/// Returns amount of visible object fields435	/// If object only contains hidden fields - may return zero.436	pub fn len(&self) -> usize {437		self.fields_visibility()438			.iter()439			.filter(|(_, (visible, _))| *visible)440			.count()441	}442	pub fn is_empty(&self) -> bool {443		self.len() == 0444	}445	/// For each field, calls callback.446	/// If callback returns false - ends iteration prematurely.447	///448	/// Returns false if ended prematurely449	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {450		let mut super_depth = SuperDepth::default();451		self.enum_fields_internal(452			&mut super_depth,453			handler,454			CoreIdx {455				idx: self.0.cores.len(),456			},457		)458	}459	fn enum_fields_internal(460		&self,461		super_depth: &mut SuperDepth,462		handler: &mut EnumFieldsHandler<'_>,463		idx: CoreIdx,464	) -> bool {465		for core in self.0.cores[..idx.idx].iter() {466			if !core.0.enum_fields_core(super_depth, handler) {467				return false;468			}469			super_depth.deepen();470		}471		true472	}473474	pub fn has_field_include_hidden(&self, name: IStr) -> bool {475		self.has_field_include_hidden_idx(476			name,477			CoreIdx {478				idx: self.0.cores.len(),479			},480		)481	}482	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {483		self.0.cores[..core.idx]484			.iter()485			.rev()486			.any(|v| v.0.has_field_include_hidden(name.clone()))487	}488	pub fn has_field(&self, name: IStr) -> bool {489		match self.field_visibility(name) {490			Some(Visibility::Unhide | Visibility::Normal) => true,491			Some(Visibility::Hidden) | None => false,492		}493	}494	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {495		if include_hidden {496			self.has_field_include_hidden(name)497		} else {498			self.has_field(name)499		}500	}501	pub fn get(&self, key: IStr) -> Result<Option<Val>> {502		self.get_idx(503			key,504			CoreIdx {505				idx: self.0.cores.len(),506			},507		)508	}509510	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {511		let cache_key = (key.clone(), core);512		{513			let mut cache = self.0.value_cache.borrow_mut();514			// entry_ref candidate?515			match cache.entry(cache_key.clone()) {516				Entry::Occupied(v) => match v.get() {517					CacheValue::Cached(v) => return v.clone(),518					CacheValue::Pending => {519						if !is_asserting(self) {520							bail!(InfiniteRecursionDetected);521						}522					}523				},524				Entry::Vacant(v) => {525					v.insert(CacheValue::Pending);526				}527			};528		}529		let result = self.get_idx_uncached(key, core);530		{531			let mut cache = self.0.value_cache.borrow_mut();532			cache.insert(cache_key, CacheValue::Cached(result.clone()));533		}534		result535	}536	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {537		self.run_assertions()?;538		let mut add_stack = Vec::with_capacity(2);539		for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {540			let sup_this = SupThis {541				sup: CoreIdx { idx: sup },542				this: self.clone(),543			};544			if let Some((val, proc)) = core.0.get_for(key.clone(), sup_this)? {545				match proc {546					ValueProcess::None if add_stack.is_empty() => return Ok(Some(val)),547					ValueProcess::None => {548						add_stack.push(val);549						break;550					}551					ValueProcess::SuperPlus => {552						add_stack.push(val);553					}554				}555			}556		}557		if add_stack.is_empty() {558			// None of layers had this field559			return Ok(None);560		} else if add_stack.len() == 1 {561			// A layer had this field, but it wanted this field to be added with super.562			// However, no super had this field, fail-safe563			return Ok(Some(add_stack.pop().expect("single element on stack")));564		}565		let mut values = add_stack.into_iter().rev();566		let init = values.next().expect("at least 2 elements");567568		values569			.try_fold(init, |a, b| evaluate_add_op(&a, &b))570			.map(Some)571572		// self.0.get_raw(key, this)573	}574575	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {576		let Some(value) = self.get(key.clone())? else {577			let suggestions = suggest_object_fields(self, key.clone());578			bail!(NoSuchField(key, suggestions))579		};580		Ok(value)581	}582583	fn field_visibility(&self, field: IStr) -> Option<Visibility> {584		self.field_visibility_idx(585			field,586			CoreIdx {587				idx: self.0.cores.len(),588			},589		)590	}591	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {592		let mut exists = false;593		for ele in self.0.cores[..core.idx].iter().rev() {594			let vis = ele.0.field_visibility(field.clone());595			match vis {596				Some(Visibility::Unhide | Visibility::Hidden) => return vis,597				Some(Visibility::Normal) => exists = true,598				None => {}599			}600		}601		exists.then_some(Visibility::Normal)602	}603604	pub fn run_assertions(&self) -> Result<()> {605		if self.0.assertions_ran.get() {606			return Ok(());607		}608		if !start_asserting(self) {609			return Ok(());610		}611		for (idx, ele) in self.0.cores.iter().enumerate() {612			let sup_this = SupThis {613				sup: CoreIdx { idx },614				this: self.clone(),615			};616			ele.0.run_assertions_raw(sup_this).inspect_err(|_e| {617				finish_asserting(self);618			})?;619		}620		finish_asserting(self);621		self.0.assertions_ran.set(true);622		Ok(())623	}624625	pub fn iter(626		&self,627		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,628	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {629		let fields = self.fields(630			#[cfg(feature = "exp-preserve-order")]631			preserve_order,632		);633		fields.into_iter().map(|field| {634			(635				field.clone(),636				self.get(field)637					.map(|opt| opt.expect("iterating over keys, field exists")),638			)639		})640	}641	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {642		if !self.has_field_ex(key.clone(), true) {643			return None;644		}645		let obj = self.clone();646647		Some(Thunk!(move || Ok(obj.get(key)?.expect("field exists"))))648	}649	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {650		let obj = self.clone();651		Thunk!(move || obj.get_or_bail(key))652	}653	pub fn ptr_eq(a: &Self, b: &Self) -> bool {654		Cc::ptr_eq(&a.0, &b.0)655	}656	pub fn downgrade(self) -> WeakObjValue {657		WeakObjValue(self.0.downgrade())658	}659	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {660		let mut out = FxHashMap::default();661		self.enum_fields(&mut |depth, index, name, visibility| {662			dbg!(&name, visibility);663			let new_sort_key = FieldSortKey::new(depth, index);664			let entry = out.entry(name);665			let (visible, _) = entry.or_insert((true, new_sort_key));666			match visibility {667				Visibility::Normal => {}668				Visibility::Hidden => {669					*visible = false;670				}671				Visibility::Unhide => {672					*visible = true;673				}674			};675			false676		});677		out678	}679	pub fn fields_ex(680		&self,681		include_hidden: bool,682		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,683	) -> Vec<IStr> {684		#[cfg(feature = "exp-preserve-order")]685		if preserve_order {686			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self687				.fields_visibility()688				.into_iter()689				.filter(|(_, (visible, _))| include_hidden || *visible)690				.enumerate()691				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))692				.unzip();693			keys.sort_unstable_by_key(|v| v.0);694			// Reorder in-place by resulting indexes695			for i in 0..fields.len() {696				let x = fields[i].clone();697				let mut j = i;698				loop {699					let k = keys[j].1;700					keys[j].1 = j;701					if k == i {702						break;703					}704					fields[j] = fields[k].clone();705					j = k;706				}707				fields[j] = x;708			}709			return fields;710		}711712		let mut fields: Vec<_> = dbg!(self713			.fields_visibility())714			.into_iter()715			.filter(|(_, (visible, _))| include_hidden || *visible)716			.map(|(k, _)| k)717			.collect();718		fields.sort_unstable();719		fields720	}721	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {722		self.fields_ex(723			false,724			#[cfg(feature = "exp-preserve-order")]725			preserve_order,726		)727	}728	pub fn values_ex(729		&self,730		include_hidden: bool,731		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,732	) -> ArrValue {733		ArrValue::new(PickObjectValues::new(734			self.clone(),735			self.fields_ex(736				include_hidden,737				#[cfg(feature = "exp-preserve-order")]738				preserve_order,739			),740		))741	}742	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {743		self.values_ex(744			false,745			#[cfg(feature = "exp-preserve-order")]746			preserve_order,747		)748	}749	pub fn key_values_ex(750		&self,751		include_hidden: bool,752		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,753	) -> ArrValue {754		ArrValue::new(PickObjectKeyValues::new(755			self.clone(),756			self.fields_ex(757				include_hidden,758				#[cfg(feature = "exp-preserve-order")]759				preserve_order,760			),761		))762	}763	pub fn key_values(764		&self,765		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,766	) -> ArrValue {767		self.key_values_ex(768			false,769			#[cfg(feature = "exp-preserve-order")]770			preserve_order,771		)772	}773}774775impl OopObject {776	pub fn new(777		this_entries: Cc<FxHashMap<IStr, ObjMember>>,778		assertions: Cc<Vec<CcObjectAssertion>>,779	) -> Self {780		Self {781			this_entries,782			value_cache: RefCell::new(FxHashMap::new()),783			assertions,784		}785	}786}787788impl ObjectCore for OopObject {789	fn enum_fields_core(790		&self,791		super_depth: &mut SuperDepth,792		handler: &mut EnumFieldsHandler<'_>,793	) -> bool {794		for (name, member) in self.this_entries.iter() {795			if handler(796				*super_depth,797				member.original_index,798				name.clone(),799				member.flags.visibility(),800			) {801				return false;802			}803		}804		true805	}806807	fn has_field_include_hidden(&self, name: IStr) -> bool {808		self.this_entries.contains_key(&name)809	}810811	fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {812		match self.this_entries.get(&key) {813			Some(k) => Ok(Some((814				k.invoke.evaluate(sup_this)?,815				if k.flags.add() {816					ValueProcess::SuperPlus817				} else {818					ValueProcess::None819				},820			))),821			None => Ok(None),822		}823	}824	fn field_visibility(&self, name: IStr) -> Option<Visibility> {825		Some(self.this_entries.get(&name)?.flags.visibility())826	}827828	fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()> {829		if self.assertions.is_empty() {830			return Ok(());831		}832		for assertion in self.assertions.iter() {833			assertion.0.run(sup_this.clone())?;834		}835		Ok(())836	}837}838839#[allow(clippy::module_name_repetitions)]840pub struct ObjValueBuilder {841	sup: Option<ObjValue>,842	map: FxHashMap<IStr, ObjMember>,843	assertions: Vec<CcObjectAssertion>,844	next_field_index: FieldIndex,845}846impl ObjValueBuilder {847	pub fn new() -> Self {848		Self::with_capacity(0)849	}850	pub fn with_capacity(capacity: usize) -> Self {851		Self {852			sup: None,853			map: FxHashMap::with_capacity(capacity),854			assertions: Vec::new(),855			next_field_index: FieldIndex::default(),856		}857	}858	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {859		self.assertions.reserve_exact(capacity);860		self861	}862	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {863		self.sup = Some(super_obj);864		self865	}866867	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {868		self.assertions.push(CcObjectAssertion::new(assertion));869		self870	}871	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {872		let field_index = self.next_field_index;873		self.next_field_index = self.next_field_index.next();874		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)875	}876	/// Preset for common method definiton pattern:877	/// Create a hidden field with the function value.878	///879	/// `.field(name).hide().value(Val::function(value))`880	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {881		self.field(name).hide().value(Val::Func(value.into()));882		self883	}884	pub fn try_method(885		&mut self,886		name: impl Into<IStr>,887		value: impl Into<FuncVal>,888	) -> Result<&mut Self> {889		self.field(name).hide().try_value(Val::Func(value.into()))?;890		Ok(self)891	}892893	pub fn build(self) -> ObjValue {894		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {895			return ObjValue::new_empty();896		}897		let res = ObjValue::new(OopObject::new(Cc::new(self.map), Cc::new(self.assertions)));898		self.sup.map(|sup| res.extend_from(sup)).unwrap_or(res)899	}900}901impl Default for ObjValueBuilder {902	fn default() -> Self {903		Self::with_capacity(0)904	}905}906907#[allow(clippy::module_name_repetitions)]908#[must_use = "value not added unless binding() was called"]909pub struct ObjMemberBuilder<Kind> {910	kind: Kind,911	name: IStr,912	add: bool,913	visibility: Visibility,914	original_index: FieldIndex,915	location: Option<Span>,916}917918#[allow(clippy::missing_const_for_fn)]919impl<Kind> ObjMemberBuilder<Kind> {920	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {921		Self {922			kind,923			name,924			original_index,925			add: false,926			visibility: Visibility::Normal,927			location: None,928		}929	}930931	pub const fn with_add(mut self, add: bool) -> Self {932		self.add = add;933		self934	}935	pub fn add(self) -> Self {936		self.with_add(true)937	}938	pub fn with_visibility(mut self, visibility: Visibility) -> Self {939		self.visibility = visibility;940		self941	}942	pub fn hide(self) -> Self {943		self.with_visibility(Visibility::Hidden)944	}945	pub fn with_location(mut self, location: Span) -> Self {946		self.location = Some(location);947		self948	}949	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {950		(951			self.kind,952			self.name,953			ObjMember {954				flags: ObjFieldFlags::new(self.add, self.visibility),955				original_index: self.original_index,956				invoke: binding,957				location: self.location,958			},959		)960	}961}962963pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);964impl ObjMemberBuilder<ValueBuilder<'_>> {965	/// Inserts value, replacing if it is already defined966	pub fn value(self, value: impl Into<Val>) {967		let (receiver, name, member) =968			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));969		let entry = receiver.0.map.entry(name);970		entry.insert_entry(member);971	}972973	/// Tries to insert value, returns an error if it was already defined974	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {975		self.try_thunk(Thunk::evaluated(value.into()))976	}977	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {978		self.binding(MaybeUnbound::Bound(value.into()))979	}980	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {981		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))982	}983	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {984		let (receiver, name, member) = self.build_member(binding);985		let location = member.location.clone();986		let old = receiver.0.map.insert(name.clone(), member);987		if old.is_some() {988			in_frame(989				CallLocation(location.as_ref()),990				|| format!("field <{}> initializtion", name.clone()),991				|| bail!(DuplicateFieldName(name.clone())),992			)?;993		}994		Ok(())995	}996}997998pub struct ExtendBuilder<'v>(&'v mut ObjValue);999impl ObjMemberBuilder<ExtendBuilder<'_>> {1000	pub fn value(self, value: impl Into<Val>) {1001		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1002	}1003	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1004		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1005	}1006	pub fn binding(self, binding: MaybeUnbound) {1007		let (receiver, name, member) = self.build_member(binding);1008		let new = receiver.0.clone();1009		*receiver.0 = new.extend_with_raw_member(name, member);1010	}1011}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -23,7 +23,7 @@
 	gc::WithCapacityExt as _,
 	manifest::{ManifestFormat, ToStringFormat},
 	typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},
-	ObjValue, Result, Unbound, WeakObjValue,
+	ObjValue, Result, SupThis, Unbound, WeakSupThis,
 };
 
 pub trait ThunkValue: Trace {
@@ -167,8 +167,6 @@
 		Self::evaluated(T::default())
 	}
 }
-
-type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
 
 #[derive(Trace, Clone)]
 pub struct CachedUnbound<I, T>
@@ -176,7 +174,7 @@
 	I: Unbound<Bound = T>,
 	T: Trace,
 {
-	cache: Cc<RefCell<FxHashMap<CacheKey, T>>>,
+	cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,
 	value: I,
 }
 impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {
@@ -189,17 +187,14 @@
 }
 impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {
 	type Bound = T;
-	fn bind(&self, 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()),
-		);
+	fn bind(&self, sup_this: SupThis) -> Result<T> {
+		let cache_key = sup_this.clone().downgrade();
 		{
 			if let Some(t) = self.cache.borrow().get(&cache_key) {
 				return Ok(t.clone());
 			}
 		}
-		let bound = self.value.bind(sup, this)?;
+		let bound = self.value.bind(sup_this)?;
 
 		{
 			let mut cache = self.cache.borrow_mut();
modifiedtests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.goldendiffbeforeafterboth
--- a/tests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.golden
+++ b/tests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.golden
@@ -1,2 +1,2 @@
-self is only usable inside objects
+self/super/$ are only usable inside objects
     elem <0> evaluation
\ No newline at end of file
modifiedtests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.goldendiffbeforeafterboth
--- a/tests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.golden
+++ b/tests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.golden
@@ -1,2 +1,2 @@
-no super found
+self/super/$ are only usable inside objects
     elem <0> evaluation
\ No newline at end of file
addedtests/golden/issue195.jsonnetdiffbeforeafterboth
--- /dev/null
+++ b/tests/golden/issue195.jsonnet
@@ -0,0 +1 @@
+{ x: 42 } { y: { "false": "x" in super } }
addedtests/golden/issue195.jsonnet.goldendiffbeforeafterboth
--- /dev/null
+++ b/tests/golden/issue195.jsonnet.golden
@@ -0,0 +1,6 @@
+{
+    "x": 42,
+    "y": {
+        "false": false
+    }
+}
\ No newline at end of file
modifiedtests/tests/cpp_test_suite.rsdiffbeforeafterboth
--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -30,6 +30,8 @@
 		.import_resolver(FileImportResolver::default());
 	let s = s.build();
 
+	let _entered = s.enter();
+
 	let trace_format = CompactFormat {
 		resolver: PathResolver::FileName,
 		max_trace: 20,
@@ -61,7 +63,7 @@
 				Val::Obj(o.build())
 			}),
 		);
-		v = apply_tla(s, &args, v).expect("failed to apply tla");
+		v = apply_tla(&args, v).expect("failed to apply tla");
 	}
 
 	match v.manifest(JsonFormat::default()) {
modifiedtests/tests/golden.rsdiffbeforeafterboth
--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -21,6 +21,8 @@
 	.import_resolver(FileImportResolver::default());
 	let s = s.build();
 
+	let _entered = s.enter();
+
 	let trace_format = CompactFormat {
 		resolver: PathResolver::FileName,
 		max_trace: 20,