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
1use std::{1use std::{
2 any::Any,2 any::Any, cell::{Cell, RefCell}, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}
3 cell::RefCell,
4 fmt::Debug,
5 hash::{Hash, Hasher},
6 ptr::addr_of,
7};3};
84
9use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};5use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};
6use educe::Educe;
10use jrsonnet_interner::IStr;7use jrsonnet_interner::IStr;
11use jrsonnet_parser::{Span, Visibility};8use jrsonnet_parser::{Span, Visibility};
12use rustc_hash::{FxHashMap, FxHashSet};9use rustc_hash::{FxHashMap, FxHashSet};
1310
14use crate::{11use crate::{
15 arr::{PickObjectKeyValues, PickObjectValues},12 arr::{PickObjectKeyValues, PickObjectValues},
16 bail,13 bail,
17 error::{suggest_object_fields, Error, ErrorKind::*},14 error::{suggest_object_fields, ErrorKind::*},
18 function::{CallLocation, FuncVal},15 function::{CallLocation, FuncVal},
19 gc::WithCapacityExt as _,16 gc::WithCapacityExt as _,
20 in_frame,17 in_frame,
18 identity_hash,
21 operator::evaluate_add_op,19 operator::evaluate_add_op,
22 val::ArrValue,20 val::ArrValue,
23 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,21 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
43 #[derive(Clone, Copy, Default, Debug, Trace)]41 #[derive(Clone, Copy, Default, Debug, Trace)]
44 pub struct SuperDepth(());42 pub struct SuperDepth(());
45 impl SuperDepth {43 impl SuperDepth {
46 pub const fn deeper(self) -> Self {44 pub(super) fn deepen(self) {}
47 Self(())
48 }
49 }45 }
5046
51 #[derive(Clone, Copy)]47 #[derive(Clone, Copy, Debug)]
52 pub struct FieldSortKey(());48 pub struct FieldSortKey(());
53 impl FieldSortKey {49 impl FieldSortKey {
54 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {
74 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
75 pub struct SuperDepth(u32);71 pub struct SuperDepth(u32);
76 impl SuperDepth {72 impl SuperDepth {
77 pub fn deeper(self) -> Self {73 pub(super) fn deepen(&mut self) {
78 Self(self.0 + 1)74 *self.0 += 1
79 }75 }
80 }76 }
8177
120 }116 }
121}117}
122impl Debug for ObjFieldFlags {118impl Debug for ObjFieldFlags {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_struct("ObjFieldFlags")120 f.debug_struct("ObjFieldFlags")
125 .field("add", &self.add())121 .field("add", &self.add())
126 .field("visibility", &self.visibility())122 .field("visibility", &self.visibility())
140136
141cc_dyn!(CcObjectAssertion, ObjectAssertion);137cc_dyn!(CcObjectAssertion, ObjectAssertion);
142pub trait ObjectAssertion: Trace {138pub trait ObjectAssertion: Trace {
143 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;139 fn run(&self, sup_this: SupThis) -> Result<()>;
144}140}
145141
146// Field => This142// Field => This
147143
148#[derive(Trace)]144#[derive(Trace, Debug)]
149enum CacheValue {145enum CacheValue {
150 Cached(Val),146 Cached(Result<Option<Val>>),
151 NotFound,
152 Pending,147 Pending,
153 Errored(Error),
154}148}
155149
156#[allow(clippy::module_name_repetitions)]150#[allow(clippy::module_name_repetitions)]
157#[derive(Trace)]151#[derive(Trace)]
158#[trace(tracking(force))]152#[trace(tracking(force))]
159pub struct OopObject {153pub struct OopObject {
160 sup: Option<ObjValue>,
161 // this: Option<ObjValue>,154 // this: Option<ObjValue>,
162 assertions: Cc<Vec<CcObjectAssertion>>,155 assertions: Cc<Vec<CcObjectAssertion>>,
163 assertions_ran: RefCell<FxHashSet<ObjValue>>,
164 this_entries: Cc<FxHashMap<IStr, ObjMember>>,156 this_entries: Cc<FxHashMap<IStr, ObjMember>>,
165 value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,157 value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,
166}158}
167impl Debug for OopObject {159impl Debug for OopObject {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 f.debug_struct("OopObject")161 f.debug_struct("OopObject")
170 .field("sup", &self.sup)
171 // .field("assertions", &self.assertions)162 // .field("assertions", &self.assertions)
172 // .field("assertions_ran", &self.assertions_ran)163 // .field("assertions_ran", &self.assertions_ran)
173 .field("this_entries", &self.this_entries)164 .field("this_entries", &self.this_entries)
178169
179type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;170type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;
180171
181pub trait ObjectLike: Trace + Any + Debug {
182 fn extend_from(&self, sup: ObjValue) -> ObjValue;172#[derive(Trace, Clone)]
183 /// When using standalone super in object, `this.super_obj.with_this(this)` is executed173pub enum ValueProcess {
184 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {
185 ObjValue::new(ThisOverride { inner: me, this })174 None,
186 }
187 fn this(&self) -> Option<ObjValue> {
188 None
189 }
190 fn len(&self) -> usize;
191 fn is_empty(&self) -> bool;
192 // If callback returns false, iteration stops
193 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;175 SuperPlus,
176}
194177
178pub 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;
185
195 fn has_field_include_hidden(&self, name: IStr) -> bool;186 fn has_field_include_hidden(&self, name: IStr) -> bool;
196 fn has_field(&self, name: IStr) -> bool;
197187
198 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;188 fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>>;
199 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;189 // fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<(Val, ValueProcess)>>;
200 fn field_visibility(&self, field: IStr) -> Option<Visibility>;190 fn field_visibility(&self, field: IStr) -> Option<Visibility>;
201191
202 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;192 fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()>;
203}193}
204194
205#[derive(Clone, Trace)]195#[derive(Clone, Trace)]
206pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<dyn ObjectLike>);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}
207202
208impl PartialEq for WeakObjValue {203impl PartialEq for WeakObjValue {
209 fn eq(&self, other: &Self) -> bool {204 fn eq(&self, other: &Self) -> bool {
222217
223cc_dyn!(218cc_dyn!(
224 #[derive(Clone, Debug)]219 #[derive(Clone, Debug)]
225 ObjValue, ObjectLike,220 ObjCore, ObjectCore,
226 pub fn new() {...}221 pub fn new() {...}
227);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}
228230
231thread_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 asserting
238fn 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}
250
229#[derive(Debug, Trace)]251#[allow(clippy::module_name_repetitions)]
252#[derive(Clone, Trace, Debug, Educe)]
253#[educe(PartialEq, Hash, Eq)]
230struct EmptyObject;254pub struct ObjValue(
255 #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,
256);
257
258#[derive(Trace, Debug)]
259struct StandaloneSuperCore {
260 sup: CoreIdx,
261 this: ObjValue,
262}
231impl ObjectLike for EmptyObject {263impl ObjectCore for StandaloneSuperCore {
232 fn extend_from(&self, sup: ObjValue) -> ObjValue {264 fn enum_fields_core(
265 &self,
266 super_depth: &mut SuperDepth,
267 handler: &mut EnumFieldsHandler<'_>,
268 ) -> bool {
233 // obj + {} == obj269 self.this
234 sup270 .enum_fields_internal(super_depth, handler, self.sup)
235 }271 }
236272
237 fn this(&self) -> Option<ObjValue> {273 fn has_field_include_hidden(&self, name: IStr) -> bool {
238 None274 self.this.has_field_include_hidden_idx(name, self.sup)
239 }275 }
240276
241 fn len(&self) -> usize {277 fn get_for(&self, key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
242 0278 let v = self.this.get_idx(key, self.sup)?;
279 Ok(v.map(|v| (v, ValueProcess::None)))
243 }280 }
244281
245 fn is_empty(&self) -> bool {282 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
246 true283 self.this.field_visibility_idx(field, self.sup)
247 }284 }
248285
249 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {286 fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
250 false287 self.this.run_assertions()
251 }288 }
289}
252290
291#[derive(Debug, Trace)]
292struct EmptyObject;
293impl ObjectCore for EmptyObject {
253 fn has_field_include_hidden(&self, _name: IStr) -> bool {294 fn enum_fields_core(
295 &self,
296 _super_depth: &mut SuperDepth,
297 _handler: &mut EnumFieldsHandler<'_>,
298 ) -> bool {
254 false299 true
255 }300 }
256301
257 fn has_field(&self, _name: IStr) -> bool {302 fn has_field_include_hidden(&self, _name: IStr) -> bool {
258 false303 false
259 }304 }
260305
261 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {306 fn get_for(&self, _key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
262 Ok(None)307 Ok(None)
263 }308 }
264 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {
265 Ok(None)
266 }
267309
268 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {310 fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
269 Ok(())311 Ok(())
270 }312 }
271313
274 }316 }
275}317}
276318
277#[derive(Trace, Debug)]319#[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 != 0
326 }
327}
328#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]
278struct ThisOverride {329pub struct SupThis {
279 inner: ObjValue,330 sup: CoreIdx,
280 this: ObjValue,331 this: ObjValue,
281}332}
282impl ObjectLike for ThisOverride {333impl SupThis {
283 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {334 pub fn has_super(&self) -> bool {
284 ObjValue::new(Self {335 self.sup.super_exists()
285 inner: self.inner.clone(),
286 this,
287 })
288 }336 }
289337 /// Implementation of `"field" in super` operation,
290 fn extend_from(&self, sup: ObjValue) -> ObjValue {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 {
291 self.inner.extend_from(sup).with_this(self.this.clone())342 self.this.has_field_include_hidden_idx(field, self.sup)
292 }343 }
293344 /// Implementation of `super.field` operation,
294 fn this(&self) -> Option<ObjValue> {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>> {
295 Some(self.this.clone())349 if !self.sup.super_exists() {
350 bail!(NoSuperFound);
351 }
352 self.this.get_idx(field, self.sup)
296 }353 }
297354 /// `super` with `self` overriden for top-level lookups.
298 fn len(&self) -> usize {355 /// Exists when super appears outside of `super.field`/`"field" in super` expressions
356 /// Exclusive to jrsonnet.
357 ///
358 /// Might return `NoSuperFound` error.
359 pub fn standalone_super(&self) -> Result<ObjValue> {
299 self.inner.len()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 }))
300 }367 }
301
302 fn is_empty(&self) -> bool {368 pub fn this(&self) -> &ObjValue {
303 self.inner.is_empty()369 &self.this
304 }370 }
305
306 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {371 pub fn downgrade(self) -> WeakSupThis {
307 self.inner.enum_fields(depth, handler)372 WeakSupThis {
373 sup: self.sup,
374 this: self.this.downgrade(),
375 }
308 }376 }
309
310 fn has_field_include_hidden(&self, name: IStr) -> bool {
311 self.inner.has_field_include_hidden(name)
312 }
313
314 fn has_field(&self, name: IStr) -> bool {
315 self.inner.has_field(name)
316 }
317
318 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
319 self.inner.get_for(key, this)
320 }
321
322 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
323 self.inner.get_raw(key, this)
324 }
325
326 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
327 self.inner.field_visibility(field)
328 }
329
330 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {
331 self.inner.run_assertions_raw(this)
332 }
333}377}
378#[derive(Trace, PartialEq, Eq, Hash, Debug)]
379pub struct WeakSupThis {
380 sup: CoreIdx,
381 this: WeakObjValue,
382}
334383
335impl ObjValue {384impl 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 }
336 pub fn new_empty() -> Self {392 pub fn new_empty() -> Self {
337 Self::new(EmptyObject)393 Self::new(EmptyObject)
338 }394 }
363419
364 #[must_use]420 #[must_use]
365 pub fn extend_from(&self, sup: Self) -> Self {421 pub fn extend_from(&self, sup: Self) -> Self {
366 self.0.extend_from(sup)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 }))
367 }429 }
368 #[must_use]430 // #[must_use]
369 pub fn with_this(&self, this: Self) -> Self {431 // pub fn with_this(&self, this: Self) -> Self {
370 self.0.with_this(self.clone(), this)432 // self.0.with_this(self.clone(), this)
371 }433 // }
434 /// Returns amount of visible object fields
435 /// If object only contains hidden fields - may return zero.
372 pub fn len(&self) -> usize {436 pub fn len(&self) -> usize {
373 self.0.len()437 self.fields_visibility()
438 .iter()
439 .filter(|(_, (visible, _))| *visible)
440 .count()
374 }441 }
375 pub fn is_empty(&self) -> bool {442 pub fn is_empty(&self) -> bool {
376 self.0.is_empty()443 self.len() == 0
377 }444 }
378 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {445 /// For each field, calls callback.
446 /// If callback returns false - ends iteration prematurely.
447 ///
448 /// Returns false if ended prematurely
449 pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {
379 self.0.enum_fields(depth, handler)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 )
380 }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 true
472 }
381473
382 pub fn has_field_include_hidden(&self, name: IStr) -> bool {474 pub fn has_field_include_hidden(&self, name: IStr) -> bool {
383 self.0.has_field_include_hidden(name)475 self.has_field_include_hidden_idx(
476 name,
477 CoreIdx {
478 idx: self.0.cores.len(),
479 },
480 )
384 }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 }
385 pub fn has_field(&self, name: IStr) -> bool {488 pub fn has_field(&self, name: IStr) -> bool {
386 self.0.has_field(name)489 match self.field_visibility(name) {
490 Some(Visibility::Unhide | Visibility::Normal) => true,
491 Some(Visibility::Hidden) | None => false,
492 }
387 }493 }
388 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {494 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {
389 if include_hidden {495 if include_hidden {
392 self.has_field(name)498 self.has_field(name)
393 }499 }
394 }500 }
395
396 pub fn get(&self, key: IStr) -> Result<Option<Val>> {501 pub fn get(&self, key: IStr) -> Result<Option<Val>> {
397 self.run_assertions()?;502 self.get_idx(
398 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))503 key,
504 CoreIdx {
505 idx: self.0.cores.len(),
506 },
507 )
399 }508 }
400509
401 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {510 fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
402 self.0.get_for(key, this)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 result
403 }535 }
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 field
559 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-safe
563 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");
404567
568 values
569 .try_fold(init, |a, b| evaluate_add_op(&a, &b))
570 .map(Some)
571
572 // self.0.get_raw(key, this)
573 }
574
405 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {575 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
406 let Some(value) = self.get(key.clone())? else {576 let Some(value) = self.get(key.clone())? else {
407 let suggestions = suggest_object_fields(self, key.clone());577 let suggestions = suggest_object_fields(self, key.clone());
410 Ok(value)580 Ok(value)
411 }581 }
412582
413 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {
414 self.0.get_for_uncached(key, this)
415 }
416
417 fn field_visibility(&self, field: IStr) -> Option<Visibility> {583 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
418 self.0.field_visibility(field)584 self.field_visibility_idx(
585 field,
586 CoreIdx {
587 idx: self.0.cores.len(),
588 },
589 )
419 }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 }
420603
421 pub fn run_assertions(&self) -> Result<()> {604 pub fn run_assertions(&self) -> Result<()> {
422 // FIXME: Should it use `self.0.this()` in case of standalone super?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 {
423 self.run_assertions_raw(self.clone())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(())
424 }623 }
425 fn run_assertions_raw(&self, this: Self) -> Result<()> {
426 self.0.run_assertions_raw(this)
427 }
428624
429 pub fn iter(625 pub fn iter(
430 &self,626 &self,
462 }658 }
463 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {659 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
464 let mut out = FxHashMap::default();660 let mut out = FxHashMap::default();
465 self.enum_fields(661 self.enum_fields(&mut |depth, index, name, visibility| {
466 SuperDepth::default(),
467 &mut |depth, index, name, visibility| {
468 let new_sort_key = FieldSortKey::new(depth, index);662 dbg!(&name, visibility);
663 let new_sort_key = FieldSortKey::new(depth, index);
469 let entry = out.entry(name);664 let entry = out.entry(name);
470 let (visible, _) = entry.or_insert((true, new_sort_key));665 let (visible, _) = entry.or_insert((true, new_sort_key));
471 match visibility {666 match visibility {
472 Visibility::Normal => {}667 Visibility::Normal => {}
473 Visibility::Hidden => {668 Visibility::Hidden => {
474 *visible = false;669 *visible = false;
475 }670 }
476 Visibility::Unhide => {671 Visibility::Unhide => {
477 *visible = true;672 *visible = true;
478 }673 }
479 };674 };
480 false675 false
481 },676 });
482 );
483 out677 out
484 }678 }
485 pub fn fields_ex(679 pub fn fields_ex(
515 return fields;709 return fields;
516 }710 }
517711
518 let mut fields: Vec<_> = self712 let mut fields: Vec<_> = dbg!(self
519 .fields_visibility()713 .fields_visibility())
520 .into_iter()714 .into_iter()
521 .filter(|(_, (visible, _))| include_hidden || *visible)715 .filter(|(_, (visible, _))| include_hidden || *visible)
522 .map(|(k, _)| k)716 .map(|(k, _)| k)
580774
581impl OopObject {775impl OopObject {
582 pub fn new(776 pub fn new(
583 sup: Option<ObjValue>,
584 this_entries: Cc<FxHashMap<IStr, ObjMember>>,777 this_entries: Cc<FxHashMap<IStr, ObjMember>>,
585 assertions: Cc<Vec<CcObjectAssertion>>,778 assertions: Cc<Vec<CcObjectAssertion>>,
586 ) -> Self {779 ) -> Self {
587 Self {780 Self {
588 sup,
589 // this: None,
590 assertions,
591 assertions_ran: RefCell::new(FxHashSet::new()),
592 this_entries,781 this_entries,
593 value_cache: RefCell::new(FxHashMap::new()),782 value_cache: RefCell::new(FxHashMap::new()),
783 assertions,
594 }784 }
595 }785 }
596
597 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {
598 v.invoke.evaluate(self.sup.clone(), Some(real_this))
599 }
600
601 // FIXME: Duplication between ObjValue and OopObject
602 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 false
620 },
621 );
622 out
623 }
624}786}
625787
626impl ObjectLike for OopObject {788impl ObjectCore for OopObject {
627 fn extend_from(&self, sup: ObjValue) -> ObjValue {789 fn enum_fields_core(
628 ObjValue::new(match &self.sup {790 &self,
629 None => Self::new(
630 Some(sup),
631 self.this_entries.clone(),791 super_depth: &mut SuperDepth,
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 }
641
642 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()792 handler: &mut EnumFieldsHandler<'_>,
648 }
649
650 /// 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() == 0
655 }
656
657 /// Run callback for every field found in object
658 ///
659 /// Returns true if ended prematurely
660 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {793 ) -> 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() {794 for (name, member) in self.this_entries.iter() {
667 if handler(795 if handler(
668 depth,796 *super_depth,
669 member.original_index,797 member.original_index,
670 name.clone(),798 name.clone(),
671 member.flags.visibility(),799 member.flags.visibility(),
672 ) {800 ) {
673 return true;801 return false;
674 }802 }
675 }803 }
676 false804 true
677 }805 }
678806
679 fn has_field_include_hidden(&self, name: IStr) -> bool {807 fn has_field_include_hidden(&self, name: IStr) -> bool {
680 if self.this_entries.contains_key(&name) {808 self.this_entries.contains_key(&name)
681 true
682 } else if let Some(super_obj) = &self.sup {
683 super_obj.has_field_include_hidden(name)
684 } else {
685 false
686 }
687 }809 }
688 fn has_field(&self, name: IStr) -> bool {
689 self.field_visibility(name)
690 .map_or(false, |v| v.is_visible())
691 }
692810
693 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {811 fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
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_cache
704 .borrow_mut()
705 .insert(cache_key.clone(), CacheValue::Pending);
706 let value = self.get_for_uncached(key, this).inspect_err(|e| {
707 self.value_cache812 match self.this_entries.get(&key) {
708 .borrow_mut()
709 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));
710 })?;
711 self.value_cache.borrow_mut().insert(
712 cache_key,
713 value
714 .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)?)),813 Some(k) => Ok(Some((
722 (Some(k), Some(super_obj)) => {814 k.invoke.evaluate(sup_this)?,
723 let our = self.evaluate_this(k, real_this.clone())?;
724 if k.flags.add() {815 if k.flags.add() {
725 super_obj816 ValueProcess::SuperPlus
726 .get_raw(key, real_this)?
727 .map_or(Ok(Some(our.clone())), |v| {
728 Ok(Some(evaluate_add_op(&v, &our)?))
729 })
730 } else {817 } else {
731 Ok(Some(our))818 ValueProcess::None
732 }819 },
733 }820 ))),
734 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),
735 (None, None) => Ok(None),821 None => Ok(None),
736 }822 }
737 }823 }
738 fn field_visibility(&self, name: IStr) -> Option<Visibility> {824 fn field_visibility(&self, name: IStr) -> Option<Visibility> {
739 if let Some(m) = self.this_entries.get(&name) {825 Some(self.this_entries.get(&name)?.flags.visibility())
740 Some(match &m.flags.visibility() {
741 Visibility::Normal => self
742 .sup
743 .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 None
752 }
753 }826 }
754827
755 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {828 fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()> {
756 if self.assertions.is_empty() {829 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(());830 return Ok(());
761 }831 }
762 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {832 for assertion in self.assertions.iter() {
763 for assertion in self.assertions.iter() {
764 if let Err(e) = assertion.0.run(self.sup.clone(), Some(real_this.clone())) {833 assertion.0.run(sup_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 }834 }
773 Ok(())835 Ok(())
774 }836 }
775}837}
776838
777impl PartialEq for ObjValue {
778 fn eq(&self, other: &Self) -> bool {
779 Cc::ptr_eq(&self.0, &other.0)
780 }
781}
782
783impl 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}
789
790#[allow(clippy::module_name_repetitions)]839#[allow(clippy::module_name_repetitions)]
791pub struct ObjValueBuilder {840pub struct ObjValueBuilder {
792 sup: Option<ObjValue>,841 sup: Option<ObjValue>,
845 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {894 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
846 return ObjValue::new_empty();895 return ObjValue::new_empty();
847 }896 }
848 ObjValue::new(OopObject::new(897 let res = ObjValue::new(OopObject::new(Cc::new(self.map), Cc::new(self.assertions)));
849 self.sup,
850 Cc::new(self.map),
851 Cc::new(self.assertions),
852 ))898 self.sup.map(|sup| res.extend_from(sup)).unwrap_or(res)
853 }899 }
854}900}
855impl Default for ObjValueBuilder {901impl Default for ObjValueBuilder {
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,