git.delta.rocks / jrsonnet / refs/commits / 284612bfbf1c

difftreelog

refactor! implement stack size limit using thread local

Yaroslav Bolyukin2022-10-25parent: #7b8b823.patch.diff
in: master

18 files changed

modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -85,8 +85,8 @@
 
 /// Set the maximum stack depth.
 #[no_mangle]
-pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {
-	vm.settings_mut().max_stack = v as usize;
+pub extern "C" fn jsonnet_max_stack(_vm: &State, _v: c_uint) {
+	todo!()
 }
 
 /// Set the number of objects required before a garbage collection cycle is allowed.
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,7 +5,7 @@
 
 use clap::{AppSettings, IntoApp, Parser};
 use clap_complete::Shell;
-use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, ManifestOpts, OutputOpts};
+use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts};
 use jrsonnet_evaluator::{error::LocError, State};
 
 #[cfg(feature = "mimalloc")]
@@ -60,8 +60,6 @@
 	output: OutputOpts,
 	#[clap(flatten)]
 	debug: DebugOpts,
-	#[clap(flatten)]
-	gc: GcOpts,
 }
 
 fn main() {
@@ -113,7 +111,6 @@
 }
 
 fn main_catch(opts: Opts) -> bool {
-	let _printer = opts.gc.stats_printer();
 	let s = State::default();
 	if let Err(e) = main_real(&s, opts) {
 		if let Error::Evaluation(e) = e {
@@ -127,7 +124,7 @@
 }
 
 fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
-	opts.general.configure(s)?;
+	let _guards = opts.general.configure(s)?;
 	opts.manifest.configure(s)?;
 
 	let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -3,10 +3,12 @@
 mod tla;
 mod trace;
 
-use std::{env, path::PathBuf};
+use std::{env, marker::PhantomData, path::PathBuf};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, FileImportResolver, State};
+use jrsonnet_evaluator::{
+	error::Result, stack::StackDepthLimitOverrideGuard, FileImportResolver, State,
+};
 use jrsonnet_gcmodule::with_thread_object_space;
 pub use manifest::*;
 pub use stdlib::*;
@@ -14,7 +16,9 @@
 pub use trace::*;
 
 pub trait ConfigureState {
-	fn configure(&self, s: &State) -> Result<()>;
+	type Guards;
+
+	fn configure(&self, s: &State) -> Result<Self::Guards>;
 }
 
 #[derive(Parser)]
@@ -44,7 +48,8 @@
 	jpath: Vec<PathBuf>,
 }
 impl ConfigureState for MiscOpts {
-	fn configure(&self, s: &State) -> Result<()> {
+	type Guards = StackDepthLimitOverrideGuard;
+	fn configure(&self, s: &State) -> Result<Self::Guards> {
 		let mut library_paths = self.jpath.clone();
 		library_paths.reverse();
 		if let Some(path) = env::var_os("JSONNET_PATH") {
@@ -53,8 +58,8 @@
 
 		s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));
 
-		s.set_max_stack(self.max_stack);
-		Ok(())
+		let _depth_limit = jrsonnet_evaluator::stack::limit_stack_depth(self.max_stack);
+		Ok(_depth_limit)
 	}
 }
 
@@ -72,16 +77,24 @@
 
 	#[clap(flatten)]
 	trace: TraceOpts,
+
+	#[clap(flatten)]
+	gc: GcOpts,
 }
 
 impl ConfigureState for GeneralOpts {
-	fn configure(&self, s: &State) -> Result<()> {
+	type Guards = (
+		<MiscOpts as ConfigureState>::Guards,
+		<GcOpts as ConfigureState>::Guards,
+	);
+	fn configure(&self, s: &State) -> Result<Self::Guards> {
 		// Configure trace first, because tla-code/ext-code can throw
 		self.trace.configure(s)?;
-		self.misc.configure(s)?;
+		let misc_guards = self.misc.configure(s)?;
 		self.tla.configure(s)?;
 		self.std.configure(s)?;
-		Ok(())
+		let gc_guards = self.gc.configure(s)?;
+		Ok((misc_guards, gc_guards))
 	}
 }
 
@@ -100,20 +113,22 @@
 	#[clap(long)]
 	gc_collect_before_printing_stats: bool,
 }
-impl GcOpts {
-	pub fn stats_printer(&self) -> (Option<GcStatsPrinter>, Option<LeakSpace>) {
+impl ConfigureState for GcOpts {
+	type Guards = (Option<GcStatsPrinter>, Option<LeakSpace>);
+
+	fn configure(&self, _s: &State) -> Result<Self::Guards> {
 		// Constructed structs have side-effects in Drop impl
 		#[allow(clippy::unnecessary_lazy_evaluations)]
-		(
+		Ok((
 			self.gc_print_stats.then(|| GcStatsPrinter {
 				collect_before_printing_stats: self.gc_collect_before_printing_stats,
 			}),
-			(!self.gc_collect_on_exit).then(|| LeakSpace {}),
-		)
+			(!self.gc_collect_on_exit).then(|| LeakSpace(PhantomData)),
+		))
 	}
 }
 
-pub struct LeakSpace {}
+pub struct LeakSpace(PhantomData<()>);
 
 impl Drop for LeakSpace {
 	fn drop(&mut self) {
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -47,6 +47,7 @@
 	exp_preserve_order: bool,
 }
 impl ConfigureState for ManifestOpts {
+	type Guards = ();
 	fn configure(&self, s: &State) -> Result<()> {
 		if self.string {
 			s.set_manifest_format(ManifestFormat::String);
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -106,6 +106,7 @@
 	ext_code_file: Vec<ExtFile>,
 }
 impl ConfigureState for StdOpts {
+	type Guards = ();
 	fn configure(&self, s: &State) -> Result<()> {
 		if self.no_stdlib {
 			return Ok(());
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -47,6 +47,7 @@
 	tla_code_file: Vec<ExtFile>,
 }
 impl ConfigureState for TLAOpts {
+	type Guards = ();
 	fn configure(&self, s: &State) -> Result<()> {
 		for tla in self.tla_str.iter() {
 			s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into());
modifiedcrates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -41,6 +41,7 @@
 	max_trace: usize,
 }
 impl ConfigureState for TraceOpts {
+	type Guards = ();
 	fn configure(&self, s: &State) -> Result<()> {
 		let resolver = PathResolver::new_cwd_fallback();
 		match self
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -20,8 +20,8 @@
 exp-preserve-order = []
 # Implements field destructuring
 exp-destruct = ["jrsonnet-parser/exp-destruct"]
-# Provide Typed for conversions to/from serde_json::Value type
-serde_json = ["dep:serde_json"]
+# Improves performance, and implements some useful things using nightly-only features
+nightly = []
 
 [dependencies]
 jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,11 +2,11 @@
 
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, SourcePath, UnaryOpType};
+use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};
 use jrsonnet_types::ValType;
 use thiserror::Error;
 
-use crate::{stdlib::format::FormatError, typed::TypeLocError};
+use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError};
 
 fn format_found(list: &[IStr], what: &str) -> String {
 	if list.is_empty() {
@@ -262,7 +262,72 @@
 	}
 }
 
+pub trait ErrorSource {
+	fn to_location(self) -> Option<ExprLocation>;
+}
+impl ErrorSource for &LocExpr {
+	fn to_location(self) -> Option<ExprLocation> {
+		Some(self.1.clone())
+	}
+}
+impl ErrorSource for &ExprLocation {
+	fn to_location(self) -> Option<ExprLocation> {
+		Some(self.clone())
+	}
+}
+impl ErrorSource for CallLocation<'_> {
+	fn to_location(self) -> Option<ExprLocation> {
+		self.0.cloned()
+	}
+}
+
 pub type Result<V, E = LocError> = std::result::Result<V, E>;
+pub trait ResultExt: Sized {
+	#[must_use]
+	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;
+	#[must_use]
+	fn description(self, msg: &str) -> Self {
+		self.with_description(|| msg)
+	}
+
+	#[must_use]
+	fn with_description_src<O: Into<String>>(
+		self,
+		src: impl ErrorSource,
+		msg: impl FnOnce() -> O,
+	) -> Self;
+	#[must_use]
+	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {
+		self.with_description_src(src, || msg)
+	}
+}
+impl<T> ResultExt for Result<T, LocError> {
+	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {
+		if let Err(e) = &mut self {
+			let trace = e.trace_mut();
+			trace.0.push(StackTraceElement {
+				location: None,
+				desc: msg().into(),
+			});
+		}
+		self
+	}
+
+	fn with_description_src<O: Into<String>>(
+		mut self,
+		src: impl ErrorSource,
+		msg: impl FnOnce() -> O,
+	) -> Self {
+		if let Err(e) = &mut self {
+			let trace = e.trace_mut();
+			trace.0.push(StackTraceElement {
+				location: src.to_location(),
+				desc: msg().into(),
+			});
+		}
+		self
+	}
+}
 
 #[macro_export]
 macro_rules! throw {
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	tb, throw,17	typed::Typed,18	val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,20	Unbound, Val,21};22pub mod destructure;23pub mod operator;2425pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {26	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {27		name,28		ctx,29		params,30		body,31	})))32}3334pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {35	Ok(match field_name {36		FieldName::Fixed(n) => Some(n.clone()),37		FieldName::Dyn(expr) => s.push(38			CallLocation::new(&expr.1),39			|| "evaluating field name".to_string(),40			|| {41				let value = evaluate(s.clone(), ctx, expr)?;42				if matches!(value, Val::Null) {43					Ok(None)44				} else {45					Ok(Some(IStr::from_untyped(value, s.clone())?))46				}47			},48		)?,49	})50}5152pub fn evaluate_comp(53	s: State,54	ctx: Context,55	specs: &[CompSpec],56	callback: &mut impl FnMut(Context) -> Result<()>,57) -> Result<()> {58	match specs.get(0) {59		None => callback(ctx)?,60		Some(CompSpec::IfSpec(IfSpecData(cond))) => {61			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {62				evaluate_comp(s, ctx, &specs[1..], callback)?;63			}64		}65		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {66			match evaluate(s.clone(), ctx.clone(), expr)? {67				Val::Arr(list) => {68					for item in list.iter(s.clone()) {69						evaluate_comp(70							s.clone(),71							ctx.clone().with_var(var.clone(), item?.clone()),72							&specs[1..],73							callback,74						)?;75					}76				}77				_ => throw!(InComprehensionCanOnlyIterateOverArray),78			}79		}80	}81	Ok(())82}8384trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8586fn evaluate_object_locals(87	fctx: Pending<Context>,88	locals: Rc<Vec<BindSpec>>,89) -> impl CloneableUnbound<Context> {90	#[derive(Trace, Clone)]91	struct UnboundLocals {92		fctx: Pending<Context>,93		locals: Rc<Vec<BindSpec>>,94	}95	impl CloneableUnbound<Context> for UnboundLocals {}96	impl Unbound for UnboundLocals {97		type Bound = Context;9899		fn bind(100			&self,101			_s: State,102			sup: Option<ObjValue>,103			this: Option<ObjValue>,104		) -> Result<Context> {105			let fctx = Context::new_future();106			let mut new_bindings = GcHashMap::new();107			for b in self.locals.iter() {108				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;109			}110111			let ctx = self.fctx.unwrap();112			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());113114			let ctx = ctx115				.extend(new_bindings, new_dollar, sup, this)116				.into_future(fctx);117118			Ok(ctx)119		}120	}121122	UnboundLocals { fctx, locals }123}124125#[allow(clippy::too_many_lines)]126pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {127	let mut builder = ObjValueBuilder::new();128	let locals = Rc::new(129		members130			.iter()131			.filter_map(|m| match m {132				Member::BindStmt(bind) => Some(bind.clone()),133				_ => None,134			})135			.collect::<Vec<_>>(),136	);137138	let fctx = Context::new_future();139140	// We have single context for all fields, so we can cache binds141	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));142143	for member in members.iter() {144		match member {145			Member::Field(FieldMember {146				name,147				plus,148				params: None,149				visibility,150				value,151			}) => {152				#[derive(Trace)]153				struct UnboundValue<B: Trace> {154					uctx: B,155					value: LocExpr,156					name: IStr,157				}158				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {159					type Bound = Thunk<Val>;160					fn bind(161						&self,162						s: State,163						sup: Option<ObjValue>,164						this: Option<ObjValue>,165					) -> Result<Thunk<Val>> {166						Ok(Thunk::evaluated(evaluate_named(167							s.clone(),168							self.uctx.bind(s, sup, this)?,169							&self.value,170							self.name.clone(),171						)?))172					}173				}174175				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;176				let name = if let Some(name) = name {177					name178				} else {179					continue;180				};181182				builder183					.member(name.clone())184					.with_add(*plus)185					.with_visibility(*visibility)186					.with_location(value.1.clone())187					.bindable(188						s.clone(),189						tb!(UnboundValue {190							uctx: uctx.clone(),191							value: value.clone(),192							name: name.clone()193						}),194					)?;195			}196			Member::Field(FieldMember {197				name,198				params: Some(params),199				value,200				..201			}) => {202				#[derive(Trace)]203				struct UnboundMethod<B: Trace> {204					uctx: B,205					value: LocExpr,206					params: ParamsDesc,207					name: IStr,208				}209				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {210					type Bound = Thunk<Val>;211					fn bind(212						&self,213						s: State,214						sup: Option<ObjValue>,215						this: Option<ObjValue>,216					) -> Result<Thunk<Val>> {217						Ok(Thunk::evaluated(evaluate_method(218							self.uctx.bind(s, sup, this)?,219							self.name.clone(),220							self.params.clone(),221							self.value.clone(),222						)))223					}224				}225226				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {227					name228				} else {229					continue;230				};231232				builder233					.member(name.clone())234					.hide()235					.with_location(value.1.clone())236					.bindable(237						s.clone(),238						tb!(UnboundMethod {239							uctx: uctx.clone(),240							value: value.clone(),241							params: params.clone(),242							name: name.clone()243						}),244					)?;245			}246			Member::BindStmt(_) => {}247			Member::AssertStmt(stmt) => {248				#[derive(Trace)]249				struct ObjectAssert<B: Trace> {250					uctx: B,251					assert: AssertStmt,252				}253				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {254					fn run(255						&self,256						s: State,257						sup: Option<ObjValue>,258						this: Option<ObjValue>,259					) -> Result<()> {260						let ctx = self.uctx.bind(s.clone(), sup, this)?;261						evaluate_assert(s, ctx, &self.assert)262					}263				}264				builder.assert(tb!(ObjectAssert {265					uctx: uctx.clone(),266					assert: stmt.clone(),267				}));268			}269		}270	}271	let this = builder.build();272	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));273	Ok(this)274}275276pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {277	Ok(match object {278		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,279		ObjBody::ObjComp(obj) => {280			let mut builder = ObjValueBuilder::new();281			let locals = Rc::new(282				obj.pre_locals283					.iter()284					.chain(obj.post_locals.iter())285					.cloned()286					.collect::<Vec<_>>(),287			);288			let mut ctxs = vec![];289			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {290				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;291				let fctx = Context::new_future();292				ctxs.push((ctx, fctx.clone()));293				let uctx = evaluate_object_locals(fctx, locals.clone());294295				match key {296					Val::Null => {}297					Val::Str(n) => {298						#[derive(Trace)]299						struct UnboundValue<B: Trace> {300							uctx: B,301							value: LocExpr,302						}303						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {304							type Bound = Thunk<Val>;305							fn bind(306								&self,307								s: State,308								sup: Option<ObjValue>,309								this: Option<ObjValue>,310							) -> Result<Thunk<Val>> {311								Ok(Thunk::evaluated(evaluate(312									s.clone(),313									self.uctx.bind(s, sup, this.clone())?.extend(314										GcHashMap::new(),315										None,316										None,317										this,318									),319									&self.value,320								)?))321							}322						}323						builder324							.member(n)325							.with_location(obj.value.1.clone())326							.with_add(obj.plus)327							.bindable(328								s.clone(),329								tb!(UnboundValue {330									uctx,331									value: obj.value.clone(),332								}),333							)?;334					}335					v => throw!(FieldMustBeStringGot(v.value_type())),336				}337338				Ok(())339			})?;340341			let this = builder.build();342			for (ctx, fctx) in ctxs {343				let _ctx = ctx344					.extend(GcHashMap::new(), None, None, Some(this.clone()))345					.into_future(fctx);346			}347			this348		}349	})350}351352pub fn evaluate_apply(353	s: State,354	ctx: Context,355	value: &LocExpr,356	args: &ArgsDesc,357	loc: CallLocation<'_>,358	tailstrict: bool,359) -> Result<Val> {360	let value = evaluate(s.clone(), ctx.clone(), value)?;361	Ok(match value {362		Val::Func(f) => {363			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);364			if tailstrict {365				body()?366			} else {367				s.push(loc, || format!("function <{}> call", f.name()), body)?368			}369		}370		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),371	})372}373374pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {375	let value = &assertion.0;376	let msg = &assertion.1;377	let assertion_result = s.push(378		CallLocation::new(&value.1),379		|| "assertion condition".to_owned(),380		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),381	)?;382	if !assertion_result {383		s.push(384			CallLocation::new(&value.1),385			|| "assertion failure".to_owned(),386			|| {387				if let Some(msg) = msg {388					throw!(AssertionFailed(389						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?390					));391				}392				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));393			},394		)?;395	}396	Ok(())397}398399pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {400	use Expr::*;401	let LocExpr(raw_expr, _loc) = expr;402	Ok(match &**raw_expr {403		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),404		_ => evaluate(s, ctx, expr)?,405	})406}407408#[allow(clippy::too_many_lines)]409pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {410	use Expr::*;411	let LocExpr(expr, loc) = expr;412	// let bp = with_state(|s| s.0.stop_at.borrow().clone());413	Ok(match &**expr {414		Literal(LiteralType::This) => {415			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)416		}417		Literal(LiteralType::Super) => Val::Obj(418			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(419				ctx.this()420					.clone()421					.expect("if super exists - then this should to"),422			),423		),424		Literal(LiteralType::Dollar) => {425			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)426		}427		Literal(LiteralType::True) => Val::Bool(true),428		Literal(LiteralType::False) => Val::Bool(false),429		Literal(LiteralType::Null) => Val::Null,430		Parened(e) => evaluate(s, ctx, e)?,431		Str(v) => Val::Str(v.clone()),432		Num(v) => Val::new_checked_num(*v)?,433		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,434		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,435		Var(name) => s.push(436			CallLocation::new(loc),437			|| format!("variable <{name}> access"),438			|| ctx.binding(name.clone())?.evaluate(s.clone()),439		)?,440		Index(value, index) => {441			match (442				evaluate(s.clone(), ctx.clone(), value)?,443				evaluate(s.clone(), ctx, index)?,444			) {445				(Val::Obj(v), Val::Str(key)) => s.push(446					CallLocation::new(loc),447					|| format!("field <{key}> access"),448					|| match v.get(s.clone(), key.clone()) {449						Ok(Some(v)) => Ok(v),450						#[cfg(not(feature = "friendly-errors"))]451						Ok(None) => throw!(NoSuchField(key.clone(), vec![])),452						#[cfg(feature = "friendly-errors")]453						Ok(None) => {454							let mut heap = Vec::new();455							for field in v.fields_ex(456								true,457								#[cfg(feature = "exp-preserve-order")]458								false,459							) {460								let conf = strsim::jaro_winkler(&field as &str, &key as &str);461								if conf < 0.8 {462									continue;463								}464								heap.push((conf, field));465							}466							heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));467468							throw!(NoSuchField(469								key.clone(),470								heap.into_iter().map(|(_, v)| v).collect()471							))472						}473						Err(e) => Err(e),474					},475				)?,476				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(477					ValType::Obj,478					ValType::Str,479					n.value_type(),480				)),481482				(Val::Arr(v), Val::Num(n)) => {483					if n.fract() > f64::EPSILON {484						throw!(FractionalIndex)485					}486					v.get(s, n as usize)?487						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?488				}489				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),490				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(491					ValType::Arr,492					ValType::Num,493					n.value_type(),494				)),495496				(Val::Str(s), Val::Num(n)) => Val::Str({497					let v: IStr = s498						.chars()499						.skip(n as usize)500						.take(1)501						.collect::<String>()502						.into();503					if v.is_empty() {504						let size = s.chars().count();505						throw!(StringBoundsError(n as usize, size))506					}507					v508				}),509				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(510					ValType::Str,511					ValType::Num,512					n.value_type(),513				)),514515				(v, _) => throw!(CantIndexInto(v.value_type())),516			}517		}518		LocalExpr(bindings, returned) => {519			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =520				GcHashMap::with_capacity(bindings.len());521			let fctx = Context::new_future();522			for b in bindings {523				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;524			}525			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);526			evaluate(s, ctx, &returned.clone())?527		}528		Arr(items) => {529			let mut out = Vec::with_capacity(items.len());530			for item in items {531				// TODO: Implement ArrValue::Lazy with same context for every element?532				#[derive(Trace)]533				struct ArrayElement {534					ctx: Context,535					item: LocExpr,536				}537				impl ThunkValue for ArrayElement {538					type Output = Val;539					fn get(self: Box<Self>, s: State) -> Result<Val> {540						evaluate(s, self.ctx, &self.item)541					}542				}543				out.push(Thunk::new(tb!(ArrayElement {544					ctx: ctx.clone(),545					item: item.clone(),546				})));547			}548			Val::Arr(out.into())549		}550		ArrComp(expr, comp_specs) => {551			let mut out = Vec::new();552			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {553				out.push(evaluate(s.clone(), ctx, expr)?);554				Ok(())555			})?;556			Val::Arr(ArrValue::Eager(Cc::new(out)))557		}558		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),559		ObjExtend(a, b) => evaluate_add_op(560			s.clone(),561			&evaluate(s.clone(), ctx.clone(), a)?,562			&Val::Obj(evaluate_object(s, ctx, b)?),563		)?,564		Apply(value, args, tailstrict) => {565			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?566		}567		Function(params, body) => {568			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())569		}570		AssertExpr(assert, returned) => {571			evaluate_assert(s.clone(), ctx.clone(), assert)?;572			evaluate(s, ctx, returned)?573		}574		ErrorStmt(e) => s.push(575			CallLocation::new(loc),576			|| "error statement".to_owned(),577			|| {578				throw!(RuntimeError(579					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,580				))581			},582		)?,583		IfElse {584			cond,585			cond_then,586			cond_else,587		} => {588			if s.push(589				CallLocation::new(loc),590				|| "if condition".to_owned(),591				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),592			)? {593				evaluate(s, ctx, cond_then)?594			} else {595				match cond_else {596					Some(v) => evaluate(s, ctx, v)?,597					None => Val::Null,598				}599			}600		}601		Slice(value, desc) => {602			fn parse_idx<T: Typed>(603				loc: CallLocation<'_>,604				s: State,605				ctx: &Context,606				expr: &Option<LocExpr>,607				desc: &'static str,608			) -> Result<Option<T>> {609				if let Some(value) = expr {610					Ok(Some(s.push(611						loc,612						|| format!("slice {desc}"),613						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),614					)?))615				} else {616					Ok(None)617				}618			}619620			let indexable = evaluate(s.clone(), ctx.clone(), value)?;621			let loc = CallLocation::new(loc);622623			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;624			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;625			let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;626627			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?628		}629		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {630			let tmp = loc.clone().0;631			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;632			match i {633				Import(_) => s.push(634					CallLocation::new(loc),635					|| format!("import {:?}", path.clone()),636					|| s.import_resolved(resolved_path),637				)?,638				ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),639				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),640				_ => unreachable!(),641			}642		}643	})644}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	tb, throw,17	typed::Typed,18	val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,20	Unbound, Val,21};22pub mod destructure;23pub mod operator;2425pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {26	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {27		name,28		ctx,29		params,30		body,31	})))32}3334pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {35	Ok(match field_name {36		FieldName::Fixed(n) => Some(n.clone()),37		FieldName::Dyn(expr) => State::push(38			CallLocation::new(&expr.1),39			|| "evaluating field name".to_string(),40			|| {41				let value = evaluate(s.clone(), ctx, expr)?;42				if matches!(value, Val::Null) {43					Ok(None)44				} else {45					Ok(Some(IStr::from_untyped(value, s.clone())?))46				}47			},48		)?,49	})50}5152pub fn evaluate_comp(53	s: State,54	ctx: Context,55	specs: &[CompSpec],56	callback: &mut impl FnMut(Context) -> Result<()>,57) -> Result<()> {58	match specs.get(0) {59		None => callback(ctx)?,60		Some(CompSpec::IfSpec(IfSpecData(cond))) => {61			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {62				evaluate_comp(s, ctx, &specs[1..], callback)?;63			}64		}65		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {66			match evaluate(s.clone(), ctx.clone(), expr)? {67				Val::Arr(list) => {68					for item in list.iter(s.clone()) {69						evaluate_comp(70							s.clone(),71							ctx.clone().with_var(var.clone(), item?.clone()),72							&specs[1..],73							callback,74						)?;75					}76				}77				_ => throw!(InComprehensionCanOnlyIterateOverArray),78			}79		}80	}81	Ok(())82}8384trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8586fn evaluate_object_locals(87	fctx: Pending<Context>,88	locals: Rc<Vec<BindSpec>>,89) -> impl CloneableUnbound<Context> {90	#[derive(Trace, Clone)]91	struct UnboundLocals {92		fctx: Pending<Context>,93		locals: Rc<Vec<BindSpec>>,94	}95	impl CloneableUnbound<Context> for UnboundLocals {}96	impl Unbound for UnboundLocals {97		type Bound = Context;9899		fn bind(100			&self,101			_s: State,102			sup: Option<ObjValue>,103			this: Option<ObjValue>,104		) -> Result<Context> {105			let fctx = Context::new_future();106			let mut new_bindings = GcHashMap::new();107			for b in self.locals.iter() {108				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;109			}110111			let ctx = self.fctx.unwrap();112			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());113114			let ctx = ctx115				.extend(new_bindings, new_dollar, sup, this)116				.into_future(fctx);117118			Ok(ctx)119		}120	}121122	UnboundLocals { fctx, locals }123}124125#[allow(clippy::too_many_lines)]126pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {127	let mut builder = ObjValueBuilder::new();128	let locals = Rc::new(129		members130			.iter()131			.filter_map(|m| match m {132				Member::BindStmt(bind) => Some(bind.clone()),133				_ => None,134			})135			.collect::<Vec<_>>(),136	);137138	let fctx = Context::new_future();139140	// We have single context for all fields, so we can cache binds141	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));142143	for member in members.iter() {144		match member {145			Member::Field(FieldMember {146				name,147				plus,148				params: None,149				visibility,150				value,151			}) => {152				#[derive(Trace)]153				struct UnboundValue<B: Trace> {154					uctx: B,155					value: LocExpr,156					name: IStr,157				}158				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {159					type Bound = Thunk<Val>;160					fn bind(161						&self,162						s: State,163						sup: Option<ObjValue>,164						this: Option<ObjValue>,165					) -> Result<Thunk<Val>> {166						Ok(Thunk::evaluated(evaluate_named(167							s.clone(),168							self.uctx.bind(s, sup, this)?,169							&self.value,170							self.name.clone(),171						)?))172					}173				}174175				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;176				let name = if let Some(name) = name {177					name178				} else {179					continue;180				};181182				builder183					.member(name.clone())184					.with_add(*plus)185					.with_visibility(*visibility)186					.with_location(value.1.clone())187					.bindable(tb!(UnboundValue {188						uctx: uctx.clone(),189						value: value.clone(),190						name: name.clone()191					}))?;192			}193			Member::Field(FieldMember {194				name,195				params: Some(params),196				value,197				..198			}) => {199				#[derive(Trace)]200				struct UnboundMethod<B: Trace> {201					uctx: B,202					value: LocExpr,203					params: ParamsDesc,204					name: IStr,205				}206				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {207					type Bound = Thunk<Val>;208					fn bind(209						&self,210						s: State,211						sup: Option<ObjValue>,212						this: Option<ObjValue>,213					) -> Result<Thunk<Val>> {214						Ok(Thunk::evaluated(evaluate_method(215							self.uctx.bind(s, sup, this)?,216							self.name.clone(),217							self.params.clone(),218							self.value.clone(),219						)))220					}221				}222223				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {224					name225				} else {226					continue;227				};228229				builder230					.member(name.clone())231					.hide()232					.with_location(value.1.clone())233					.bindable(tb!(UnboundMethod {234						uctx: uctx.clone(),235						value: value.clone(),236						params: params.clone(),237						name: name.clone()238					}))?;239			}240			Member::BindStmt(_) => {}241			Member::AssertStmt(stmt) => {242				#[derive(Trace)]243				struct ObjectAssert<B: Trace> {244					uctx: B,245					assert: AssertStmt,246				}247				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {248					fn run(249						&self,250						s: State,251						sup: Option<ObjValue>,252						this: Option<ObjValue>,253					) -> Result<()> {254						let ctx = self.uctx.bind(s.clone(), sup, this)?;255						evaluate_assert(s, ctx, &self.assert)256					}257				}258				builder.assert(tb!(ObjectAssert {259					uctx: uctx.clone(),260					assert: stmt.clone(),261				}));262			}263		}264	}265	let this = builder.build();266	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));267	Ok(this)268}269270pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {271	Ok(match object {272		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,273		ObjBody::ObjComp(obj) => {274			let mut builder = ObjValueBuilder::new();275			let locals = Rc::new(276				obj.pre_locals277					.iter()278					.chain(obj.post_locals.iter())279					.cloned()280					.collect::<Vec<_>>(),281			);282			let mut ctxs = vec![];283			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {284				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;285				let fctx = Context::new_future();286				ctxs.push((ctx, fctx.clone()));287				let uctx = evaluate_object_locals(fctx, locals.clone());288289				match key {290					Val::Null => {}291					Val::Str(n) => {292						#[derive(Trace)]293						struct UnboundValue<B: Trace> {294							uctx: B,295							value: LocExpr,296						}297						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {298							type Bound = Thunk<Val>;299							fn bind(300								&self,301								s: State,302								sup: Option<ObjValue>,303								this: Option<ObjValue>,304							) -> Result<Thunk<Val>> {305								Ok(Thunk::evaluated(evaluate(306									s.clone(),307									self.uctx.bind(s, sup, this.clone())?.extend(308										GcHashMap::new(),309										None,310										None,311										this,312									),313									&self.value,314								)?))315							}316						}317						builder318							.member(n)319							.with_location(obj.value.1.clone())320							.with_add(obj.plus)321							.bindable(tb!(UnboundValue {322								uctx,323								value: obj.value.clone(),324							}))?;325					}326					v => throw!(FieldMustBeStringGot(v.value_type())),327				}328329				Ok(())330			})?;331332			let this = builder.build();333			for (ctx, fctx) in ctxs {334				let _ctx = ctx335					.extend(GcHashMap::new(), None, None, Some(this.clone()))336					.into_future(fctx);337			}338			this339		}340	})341}342343pub fn evaluate_apply(344	s: State,345	ctx: Context,346	value: &LocExpr,347	args: &ArgsDesc,348	loc: CallLocation<'_>,349	tailstrict: bool,350) -> Result<Val> {351	let value = evaluate(s.clone(), ctx.clone(), value)?;352	Ok(match value {353		Val::Func(f) => {354			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);355			if tailstrict {356				body()?357			} else {358				State::push(loc, || format!("function <{}> call", f.name()), body)?359			}360		}361		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),362	})363}364365pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {366	let value = &assertion.0;367	let msg = &assertion.1;368	let assertion_result = State::push(369		CallLocation::new(&value.1),370		|| "assertion condition".to_owned(),371		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),372	)?;373	if !assertion_result {374		State::push(375			CallLocation::new(&value.1),376			|| "assertion failure".to_owned(),377			|| {378				if let Some(msg) = msg {379					throw!(AssertionFailed(380						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?381					));382				}383				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));384			},385		)?;386	}387	Ok(())388}389390pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {391	use Expr::*;392	let LocExpr(raw_expr, _loc) = expr;393	Ok(match &**raw_expr {394		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),395		_ => evaluate(s, ctx, expr)?,396	})397}398399#[allow(clippy::too_many_lines)]400pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {401	use Expr::*;402	let LocExpr(expr, loc) = expr;403	// let bp = with_state(|s| s.0.stop_at.borrow().clone());404	Ok(match &**expr {405		Literal(LiteralType::This) => {406			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)407		}408		Literal(LiteralType::Super) => Val::Obj(409			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(410				ctx.this()411					.clone()412					.expect("if super exists - then this should to"),413			),414		),415		Literal(LiteralType::Dollar) => {416			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)417		}418		Literal(LiteralType::True) => Val::Bool(true),419		Literal(LiteralType::False) => Val::Bool(false),420		Literal(LiteralType::Null) => Val::Null,421		Parened(e) => evaluate(s, ctx, e)?,422		Str(v) => Val::Str(v.clone()),423		Num(v) => Val::new_checked_num(*v)?,424		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,425		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,426		Var(name) => State::push(427			CallLocation::new(loc),428			|| format!("variable <{name}> access"),429			|| ctx.binding(name.clone())?.evaluate(s.clone()),430		)?,431		Index(value, index) => {432			match (433				evaluate(s.clone(), ctx.clone(), value)?,434				evaluate(s.clone(), ctx, index)?,435			) {436				(Val::Obj(v), Val::Str(key)) => State::push(437					CallLocation::new(loc),438					|| format!("field <{key}> access"),439					|| match v.get(s.clone(), key.clone()) {440						Ok(Some(v)) => Ok(v),441						#[cfg(not(feature = "friendly-errors"))]442						Ok(None) => throw!(NoSuchField(key.clone(), vec![])),443						#[cfg(feature = "friendly-errors")]444						Ok(None) => {445							let mut heap = Vec::new();446							for field in v.fields_ex(447								true,448								#[cfg(feature = "exp-preserve-order")]449								false,450							) {451								let conf = strsim::jaro_winkler(&field as &str, &key as &str);452								if conf < 0.8 {453									continue;454								}455								heap.push((conf, field));456							}457							heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));458459							throw!(NoSuchField(460								key.clone(),461								heap.into_iter().map(|(_, v)| v).collect()462							))463						}464						Err(e) => Err(e),465					},466				)?,467				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(468					ValType::Obj,469					ValType::Str,470					n.value_type(),471				)),472473				(Val::Arr(v), Val::Num(n)) => {474					if n.fract() > f64::EPSILON {475						throw!(FractionalIndex)476					}477					v.get(s, n as usize)?478						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?479				}480				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),481				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(482					ValType::Arr,483					ValType::Num,484					n.value_type(),485				)),486487				(Val::Str(s), Val::Num(n)) => Val::Str({488					let v: IStr = s489						.chars()490						.skip(n as usize)491						.take(1)492						.collect::<String>()493						.into();494					if v.is_empty() {495						let size = s.chars().count();496						throw!(StringBoundsError(n as usize, size))497					}498					v499				}),500				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(501					ValType::Str,502					ValType::Num,503					n.value_type(),504				)),505506				(v, _) => throw!(CantIndexInto(v.value_type())),507			}508		}509		LocalExpr(bindings, returned) => {510			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =511				GcHashMap::with_capacity(bindings.len());512			let fctx = Context::new_future();513			for b in bindings {514				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;515			}516			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);517			evaluate(s, ctx, &returned.clone())?518		}519		Arr(items) => {520			let mut out = Vec::with_capacity(items.len());521			for item in items {522				// TODO: Implement ArrValue::Lazy with same context for every element?523				#[derive(Trace)]524				struct ArrayElement {525					ctx: Context,526					item: LocExpr,527				}528				impl ThunkValue for ArrayElement {529					type Output = Val;530					fn get(self: Box<Self>, s: State) -> Result<Val> {531						evaluate(s, self.ctx, &self.item)532					}533				}534				out.push(Thunk::new(tb!(ArrayElement {535					ctx: ctx.clone(),536					item: item.clone(),537				})));538			}539			Val::Arr(out.into())540		}541		ArrComp(expr, comp_specs) => {542			let mut out = Vec::new();543			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {544				out.push(evaluate(s.clone(), ctx, expr)?);545				Ok(())546			})?;547			Val::Arr(ArrValue::Eager(Cc::new(out)))548		}549		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),550		ObjExtend(a, b) => evaluate_add_op(551			s.clone(),552			&evaluate(s.clone(), ctx.clone(), a)?,553			&Val::Obj(evaluate_object(s, ctx, b)?),554		)?,555		Apply(value, args, tailstrict) => {556			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?557		}558		Function(params, body) => {559			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())560		}561		AssertExpr(assert, returned) => {562			evaluate_assert(s.clone(), ctx.clone(), assert)?;563			evaluate(s, ctx, returned)?564		}565		ErrorStmt(e) => State::push(566			CallLocation::new(loc),567			|| "error statement".to_owned(),568			|| {569				throw!(RuntimeError(570					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,571				))572			},573		)?,574		IfElse {575			cond,576			cond_then,577			cond_else,578		} => {579			if State::push(580				CallLocation::new(loc),581				|| "if condition".to_owned(),582				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),583			)? {584				evaluate(s, ctx, cond_then)?585			} else {586				match cond_else {587					Some(v) => evaluate(s, ctx, v)?,588					None => Val::Null,589				}590			}591		}592		Slice(value, desc) => {593			fn parse_idx<T: Typed>(594				loc: CallLocation<'_>,595				s: State,596				ctx: &Context,597				expr: &Option<LocExpr>,598				desc: &'static str,599			) -> Result<Option<T>> {600				if let Some(value) = expr {601					Ok(Some(State::push(602						loc,603						|| format!("slice {desc}"),604						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),605					)?))606				} else {607					Ok(None)608				}609			}610611			let indexable = evaluate(s.clone(), ctx.clone(), value)?;612			let loc = CallLocation::new(loc);613614			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;615			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;616			let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;617618			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?619		}620		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {621			let tmp = loc.clone().0;622			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;623			match i {624				Import(_) => State::push(625					CallLocation::new(loc),626					|| format!("import {:?}", path.clone()),627					|| s.import_resolved(resolved_path),628				)?,629				ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),630				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),631				_ => unreachable!(),632			}633		}634	})635}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,5 @@
 //! jsonnet interpreter implementation
-
+#![cfg_attr(feature = "nightly", feature(thread_local))]
 #![deny(unsafe_op_in_unsafe_fn)]
 #![warn(
 	clippy::all,
@@ -51,6 +51,7 @@
 mod integrations;
 mod map;
 mod obj;
+pub mod stack;
 pub mod stdlib;
 pub mod trace;
 pub mod typed;
@@ -67,7 +68,7 @@
 
 pub use ctx::*;
 pub use dynamic::*;
-use error::{Error::*, LocError, Result, StackTraceElement};
+use error::{Error::*, LocError, Result, ResultExt};
 pub use evaluate::*;
 use function::{CallLocation, TlaArg};
 use gc::{GcHashMap, TraceBox};
@@ -78,6 +79,7 @@
 pub use jrsonnet_parser as parser;
 use jrsonnet_parser::*;
 pub use obj::*;
+use stack::check_depth;
 use trace::{CompactFormat, TraceFormat};
 pub use val::{ManifestFormat, Thunk, Val};
 
@@ -143,8 +145,6 @@
 
 /// Dynamically reconfigurable evaluation settings
 pub struct EvaluationSettings {
-	/// Limits recursion by limiting the number of stack frames
-	pub max_stack: usize,
 	/// Limits amount of stack trace items preserved
 	pub max_trace: usize,
 	/// TLA vars
@@ -162,7 +162,6 @@
 impl Default for EvaluationSettings {
 	fn default() -> Self {
 		Self {
-			max_stack: 200,
 			max_trace: 20,
 			context_initializer: Box::new(DummyContextInitializer),
 			tla_vars: HashMap::default(),
@@ -179,19 +178,7 @@
 		}
 	}
 }
-
-#[derive(Default)]
-struct EvaluationData {
-	/// Used for stack overflow detection, stacktrace is populated on unwind
-	stack_depth: usize,
-	/// Updated every time stack entry is popt
-	stack_generation: usize,
 
-	breakpoints: Breakpoints,
-
-	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
-	files: GcHashMap<SourcePath, FileData>,
-}
 struct FileData {
 	string: Option<IStr>,
 	bytes: Option<IBytes>,
@@ -217,46 +204,14 @@
 			parsed: None,
 			evaluated: None,
 			evaluating: false,
-		}
-	}
-}
-
-#[allow(clippy::type_complexity)]
-pub struct Breakpoint {
-	loc: ExprLocation,
-	collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,
-}
-#[derive(Default)]
-struct Breakpoints(Vec<Rc<Breakpoint>>);
-impl Breakpoints {
-	fn insert(
-		&self,
-		stack_depth: usize,
-		stack_generation: usize,
-		loc: &ExprLocation,
-		result: Result<Val>,
-	) -> Result<Val> {
-		if self.0.is_empty() {
-			return result;
-		}
-		for item in &self.0 {
-			if item.loc.belongs_to(loc) {
-				let mut collected = item.collected.borrow_mut();
-				let (depth, vals) = collected.entry(stack_generation).or_default();
-				if stack_depth > *depth {
-					vals.clear();
-				}
-				vals.push(result.clone());
-			}
 		}
-		result
 	}
 }
 
 #[derive(Default)]
 pub struct EvaluationStateInternals {
 	/// Internal state
-	data: RefCell<EvaluationData>,
+	file_cache: RefCell<GcHashMap<SourcePath, FileData>>,
 	/// Settings, safe to change at runtime
 	settings: RefCell<EvaluationSettings>,
 }
@@ -268,8 +223,8 @@
 impl State {
 	/// 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 data = self.data_mut();
-		let mut file = data.files.raw_entry_mut().from_key(&path);
+		let mut file_cache = self.file_cache();
+		let mut file = file_cache.raw_entry_mut().from_key(&path);
 
 		let file = match file {
 			RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -303,8 +258,8 @@
 	}
 	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
 	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {
-		let mut data = self.data_mut();
-		let mut file = data.files.raw_entry_mut().from_key(&path);
+		let mut file_cache = self.file_cache();
+		let mut file = file_cache.raw_entry_mut().from_key(&path);
 
 		let file = match file {
 			RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -330,8 +285,8 @@
 	}
 	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
 	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {
-		let mut data = self.data_mut();
-		let mut file = data.files.raw_entry_mut().from_key(&path);
+		let mut file_cache = self.file_cache();
+		let mut file = file_cache.raw_entry_mut().from_key(&path);
 
 		let file = match file {
 			RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -383,16 +338,16 @@
 			throw!(InfiniteRecursionDetected)
 		}
 		file.evaluating = true;
-		// Dropping file here, as it borrows data, which may be used in evaluation
-		drop(data);
+		// Dropping file cache guard here, as evaluation may use this map too
+		drop(file_cache);
 		let res = evaluate(
 			self.clone(),
 			self.create_default_context(file_name),
 			&parsed,
 		);
 
-		let mut data = self.data_mut();
-		let mut file = data.files.raw_entry_mut().from_key(&path);
+		let mut file_cache = self.file_cache();
+		let mut file = file_cache.raw_entry_mut().from_key(&path);
 
 		let file = match file {
 			RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -426,35 +381,13 @@
 
 	/// Executes code creating a new stack frame
 	pub fn push<T>(
-		&self,
 		e: CallLocation<'_>,
 		frame_desc: impl FnOnce() -> String,
 		f: impl FnOnce() -> Result<T>,
 	) -> Result<T> {
-		{
-			let mut data = self.data_mut();
-			let stack_depth = &mut data.stack_depth;
-			if *stack_depth > self.max_stack() {
-				// Error creation uses data, so i drop guard here
-				drop(data);
-				throw!(StackOverflow);
-			}
-			*stack_depth += 1;
-		}
-		let result = f();
-		{
-			let mut data = self.data_mut();
-			data.stack_depth -= 1;
-			data.stack_generation += 1;
-		}
-		if let Err(mut err) = result {
-			err.trace_mut().0.push(StackTraceElement {
-				location: e.0.cloned(),
-				desc: frame_desc(),
-			});
-			return Err(err);
-		}
-		result
+		let _guard = check_depth()?;
+
+		f().with_description_src(e, frame_desc)
 	}
 
 	/// Executes code creating a new stack frame
@@ -464,64 +397,18 @@
 		frame_desc: impl FnOnce() -> String,
 		f: impl FnOnce() -> Result<Val>,
 	) -> Result<Val> {
-		{
-			let mut data = self.data_mut();
-			let stack_depth = &mut data.stack_depth;
-			if *stack_depth > self.max_stack() {
-				// Error creation uses data, so i drop guard here
-				drop(data);
-				throw!(StackOverflow);
-			}
-			*stack_depth += 1;
-		}
-		let mut result = f();
-		{
-			let mut data = self.data_mut();
-			data.stack_depth -= 1;
-			data.stack_generation += 1;
-			result = data
-				.breakpoints
-				.insert(data.stack_depth, data.stack_generation, e, result);
-		}
-		if let Err(mut err) = result {
-			err.trace_mut().0.push(StackTraceElement {
-				location: Some(e.clone()),
-				desc: frame_desc(),
-			});
-			return Err(err);
-		}
-		result
+		let _guard = check_depth()?;
+
+		f().with_description_src(e, frame_desc)
 	}
 	/// Executes code creating a new stack frame
 	pub fn push_description<T>(
-		&self,
 		frame_desc: impl FnOnce() -> String,
 		f: impl FnOnce() -> Result<T>,
 	) -> Result<T> {
-		{
-			let mut data = self.data_mut();
-			let stack_depth = &mut data.stack_depth;
-			if *stack_depth > self.max_stack() {
-				// Error creation uses data, so i drop guard here
-				drop(data);
-				throw!(StackOverflow);
-			}
-			*stack_depth += 1;
-		}
-		let result = f();
-		{
-			let mut data = self.data_mut();
-			data.stack_depth -= 1;
-			data.stack_generation += 1;
-		}
-		if let Err(mut err) = result {
-			err.trace_mut().0.push(StackTraceElement {
-				location: None,
-				desc: frame_desc(),
-			});
-			return Err(err);
-		}
-		result
+		let _guard = check_depth()?;
+
+		f().with_description(frame_desc)
 	}
 
 	/// # Panics
@@ -536,7 +423,7 @@
 	}
 
 	pub fn manifest(&self, val: Val) -> Result<IStr> {
-		self.push_description(
+		Self::push_description(
 			|| "manifestification".to_string(),
 			|| val.manifest(self.clone(), &self.manifest_format()),
 		)
@@ -551,7 +438,7 @@
 	/// If passed value is function then call with set TLA
 	pub fn with_tla(&self, val: Val) -> Result<Val> {
 		Ok(match val {
-			Val::Func(func) => self.push_description(
+			Val::Func(func) => State::push_description(
 				|| "during TLA call".to_owned(),
 				|| {
 					func.evaluate(
@@ -573,8 +460,8 @@
 
 /// Internals
 impl State {
-	fn data_mut(&self) -> RefMut<'_, EvaluationData> {
-		self.0.data.borrow_mut()
+	fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {
+		self.0.file_cache.borrow_mut()
 	}
 	pub fn settings(&self) -> Ref<'_, EvaluationSettings> {
 		self.0.settings.borrow()
@@ -675,12 +562,5 @@
 	}
 	pub fn set_max_trace(&self, trace: usize) {
 		self.settings_mut().max_trace = trace;
-	}
-
-	pub fn max_stack(&self) -> usize {
-		self.settings().max_stack
-	}
-	pub fn set_max_stack(&self, trace: usize) {
-		self.settings_mut().max_stack = trace;
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -577,22 +577,29 @@
 
 pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
 impl ObjMemberBuilder<ValueBuilder<'_>> {
-	pub fn value(self, s: State, value: Val) -> Result<()> {
-		self.binding(s, MaybeUnbound::Bound(Thunk::evaluated(value)))
+	/// Inserts value, replacing if it is already defined
+	pub fn value_unchecked(self, value: Val) {
+		let (receiver, name, member) =
+			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));
+		let entry = receiver.0.map.entry(name);
+		entry.insert(member);
 	}
-	pub fn bindable(
-		self,
-		s: State,
-		bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
-	) -> Result<()> {
-		self.binding(s, MaybeUnbound::Unbound(Cc::new(bindable)))
+
+	pub fn value(self, value: Val) -> Result<()> {
+		self.thunk(Thunk::evaluated(value))
+	}
+	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
+		self.binding(MaybeUnbound::Bound(value))
+	}
+	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) -> Result<()> {
+		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)))
 	}
-	pub fn binding(self, s: State, binding: MaybeUnbound) -> Result<()> {
+	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
 		let (receiver, name, member) = self.build_member(binding);
 		let location = member.location.clone();
 		let old = receiver.0.map.insert(name.clone(), member);
 		if old.is_some() {
-			s.push(
+			State::push(
 				CallLocation(location.as_ref()),
 				|| format!("field <{}> initializtion", name.clone()),
 				|| throw!(DuplicateFieldName(name.clone())),
addedcrates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -0,0 +1,109 @@
+use std::{cell::Cell, marker::PhantomData};
+
+use crate::error::{Error, LocError};
+
+struct StackLimit {
+	max_stack_size: Cell<usize>,
+	current_depth: Cell<usize>,
+}
+
+#[cfg(feature = "nightly")]
+#[thread_local]
+static STACK_LIMIT: StackLimit = StackLimit {
+	max_stack_size: Cell::new(200),
+	current_depth: Cell::new(0),
+};
+#[cfg(not(feature = "nightly"))]
+thread_local! {
+	static STACK_LIMIT: StackLimit = StackLimit {
+		max_stack_size: Cell::new(200),
+		current_depth: Cell::new(0),
+	};
+}
+
+pub struct StackOverflowError;
+impl From<StackOverflowError> for Error {
+	fn from(_: StackOverflowError) -> Self {
+		Error::StackOverflow
+	}
+}
+impl From<StackOverflowError> for LocError {
+	fn from(_: StackOverflowError) -> Self {
+		Error::StackOverflow.into()
+	}
+}
+
+/// Used to implement stack depth limitation
+pub struct StackDepthGuard(PhantomData<()>);
+impl Drop for StackDepthGuard {
+	#[cfg(feature = "nightly")]
+	fn drop(&mut self) {
+		STACK_LIMIT
+			.current_depth
+			.set(STACK_LIMIT.current_depth.get() - 1)
+	}
+	#[cfg(not(feature = "nightly"))]
+	fn drop(&mut self) {
+		STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1));
+	}
+}
+
+// #[cfg(feature = "nightly")]
+pub fn check_depth() -> Result<StackDepthGuard, StackOverflowError> {
+	fn internal(limit: &StackLimit) -> Result<StackDepthGuard, StackOverflowError> {
+		let current = limit.current_depth.get();
+		if current < limit.max_stack_size.get() {
+			limit.current_depth.set(current + 1);
+			Ok(StackDepthGuard(PhantomData))
+		} else {
+			Err(StackOverflowError)
+		}
+	}
+	#[cfg(feature = "nightly")]
+	{
+		internal(&STACK_LIMIT)
+	}
+	#[cfg(not(feature = "nightly"))]
+	{
+		STACK_LIMIT.with(internal)
+	}
+}
+
+pub struct StackDepthLimitOverrideGuard {
+	old_limit: usize,
+}
+impl Drop for StackDepthLimitOverrideGuard {
+	#[cfg(feature = "nightly")]
+	fn drop(&mut self) {
+		STACK_LIMIT.max_stack_size.set(self.old_limit)
+	}
+	#[cfg(not(feature = "nightly"))]
+	fn drop(&mut self) {
+		STACK_LIMIT.with(|limit| limit.max_stack_size.set(self.old_limit));
+	}
+}
+
+pub fn limit_stack_depth(depth_limit: usize) -> StackDepthLimitOverrideGuard {
+	fn internal(limit: &StackLimit, depth_limit: usize) -> StackDepthLimitOverrideGuard {
+		let old_limit = limit.max_stack_size.get();
+		let current_depth = limit.current_depth.get();
+
+		limit.max_stack_size.set(current_depth + depth_limit);
+		StackDepthLimitOverrideGuard { old_limit }
+	}
+	#[cfg(feature = "nightly")]
+	{
+		internal(&STACK_LIMIT, depth_limit)
+	}
+	#[cfg(not(feature = "nightly"))]
+	{
+		STACK_LIMIT.with(|limit| internal(limit, depth_limit))
+	}
+}
+
+/// Like [`limit_stack_depth`], but set depth is not guarded, and will be kept
+///
+/// Used to implement `set_max_stack` in C api, prefer to use [`limit_stack_depth`] instead
+pub fn set_stack_depth_limit(depth_limit: usize) {
+	std::mem::forget(limit_stack_depth(depth_limit));
+}
modifiedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -111,7 +111,7 @@
 					buf.push_str(cur_padding);
 					escape_string_json_buf(&field, buf);
 					buf.push_str(options.key_val_sep);
-					s.push_description(
+					State::push_description(
 						|| format!("field <{}> manifestification", field.clone()),
 						|| {
 							let value = obj.get(s.clone(), field.clone())?.unwrap();
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -10,7 +10,7 @@
 pub mod manifest;
 
 pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {
-	s.push(
+	State::push(
 		CallLocation::native(),
 		|| format!("std.format of {str}"),
 		|| {
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -85,12 +85,11 @@
 }
 
 fn push_type_description(
-	s: State,
 	error_reason: impl Fn() -> String,
 	path: impl Fn() -> ValuePathItem,
 	item: impl Fn() -> Result<()>,
 ) -> Result<()> {
-	s.push_description(error_reason, || match item() {
+	State::push_description(error_reason, || match item() {
 		Ok(_) => Ok(()),
 		Err(mut e) => {
 			if let Error::TypeError(e) = &mut e.error_mut() {
@@ -170,7 +169,6 @@
 				Val::Arr(a) => {
 					for (i, item) in a.iter(s.clone()).enumerate() {
 						push_type_description(
-							s.clone(),
 							|| format!("array index {i}"),
 							|| ValuePathItem::Index(i as u64),
 							|| elem_type.check(s.clone(), &item.clone()?),
@@ -184,7 +182,6 @@
 				Val::Arr(a) => {
 					for (i, item) in a.iter(s.clone()).enumerate() {
 						push_type_description(
-							s.clone(),
 							|| format!("array index {i}"),
 							|| ValuePathItem::Index(i as u64),
 							|| elem_type.check(s.clone(), &item.clone()?),
@@ -199,7 +196,6 @@
 					for (k, v) in elems.iter() {
 						if let Some(got_v) = obj.get(s.clone(), (*k).into())? {
 							push_type_description(
-								s.clone(),
 								|| format!("property {k}"),
 								|| ValuePathItem::Field((*k).into()),
 								|| v.check(s.clone(), &got_v),
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -299,7 +299,7 @@
 				cfg_attrs,
 			} => {
 				let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");
-				let eval = quote! {s.push_description(
+				let eval = quote! {jrsonnet_evaluator::State::push_description(
 					|| format!("argument <{}> evaluation", #name),
 					|| <#ty>::from_untyped(value.evaluate(s.clone())?, s.clone()),
 				)?};
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -137,43 +137,36 @@
 		builder
 			.member(name.into())
 			.hide()
-			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
+			.value(Val::Func(FuncVal::StaticBuiltin(builtin)))
 			.expect("no conflict");
 	}
 
 	builder
 		.member("extVar".into())
 		.hide()
-		.value(
-			s.clone(),
-			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
-				settings: settings.clone()
-			})))),
-		)
+		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
+			settings: settings.clone()
+		})))))
 		.expect("no conflict");
 	builder
 		.member("native".into())
 		.hide()
-		.value(
-			s.clone(),
-			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
-				settings: settings.clone()
-			})))),
-		)
+		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
+			settings: settings.clone()
+		})))))
 		.expect("no conflict");
 	builder
 		.member("trace".into())
 		.hide()
-		.value(
-			s.clone(),
-			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),
-		)
+		.value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace {
+			settings
+		})))))
 		.expect("no conflict");
 
 	builder
 		.member("id".into())
 		.hide()
-		.value(s, Val::Func(FuncVal::Id))
+		.value(Val::Func(FuncVal::Id))
 		.expect("no conflict");
 
 	builder.build()