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

difftreelog

refactor unified ContextBuilder

lzpkwkksYaroslav Bolyukin2026-04-05parent: #edb8e7e.patch.diff
in: master

17 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -699,6 +699,7 @@
  "bitmaps",
  "rand_core 0.6.4",
  "rand_xoshiro",
+ "refpool",
  "sized-chunks",
  "typenum",
  "version_check",
@@ -861,9 +862,9 @@
 
 [[package]]
 name = "jrsonnet-gcmodule"
-version = "0.4.3"
+version = "0.4.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a6a63a6e55ba82764e483d7f8a181f25db95a8f25da8ae6520e95a5fe39c6a6"
+checksum = "21dd97b40cbfb2043094219f95d96519858ba1aee4e8260eb048a1774832a517"
 dependencies = [
  "im-rc",
  "jrsonnet-gcmodule-derive",
@@ -871,9 +872,9 @@
 
 [[package]]
 name = "jrsonnet-gcmodule-derive"
-version = "0.4.3"
+version = "0.4.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "095fe3c4c0acf32de80205a8a479ef63c216b9efb0024dec9eb7fe1c5ef1f1a1"
+checksum = "ede3d0445c2a7d7adab0a3cc33bdb33df78ffebebc21a2848c221526cb1795d4"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -1420,6 +1421,12 @@
 ]
 
 [[package]]
+name = "refpool"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "369e86b80fa7dc8c561dd9613a5bf25c59d2d3073cd66c47fd9e39802f0ecb58"
+
+[[package]]
 name = "regex"
 version = "1.12.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1633,6 +1640,7 @@
 checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e"
 dependencies = [
  "bitmaps",
+ "refpool",
  "typenum",
 ]
 
@@ -1738,6 +1746,7 @@
  "jrsonnet-evaluator",
  "jrsonnet-gcmodule",
  "jrsonnet-stdlib",
+ "mimallocator",
  "serde",
  "serde_json",
 ]
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,7 +22,7 @@
 jrsonnet-cli = { path = "./crates/jrsonnet-cli", version = "0.5.0-pre98" }
 jrsonnet-types = { path = "./crates/jrsonnet-types", version = "0.5.0-pre98" }
 jrsonnet-formatter = { path = "./crates/jrsonnet-formatter", version = "0.5.0-pre98" }
-jrsonnet-gcmodule = { version = "0.4.3", features = ["im-rc"] }
+jrsonnet-gcmodule = { version = "0.4.4", features = ["im-rc"] }
 # Diagnostics.
 # hi-doc is my library, which handles text formatting very well, but isn't polished enough yet
 # Previous implementation was based on annotate-snippets, which I don't like for many reasons.
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -200,7 +200,7 @@
 		val = s.evaluate_snippet_with(
 			"<exp_apply>".to_owned(),
 			&apply,
-			InitialUnderscore(Thunk::evaluated(val)),
+			&InitialUnderscore(Thunk::evaluated(val)),
 		)?;
 	}
 
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -76,7 +76,7 @@
   "Hash",
   "PartialEq",
 ] }
-im-rc = "15.1.0"
+im-rc = { version = "15.1.0", features = ["pool"] }
 
 [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
@@ -3,11 +3,11 @@
 use educe::Educe;
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
-use rustc_hash::FxHashMap;
+use rustc_hash::{FxHashMap, FxHashSet};
 
 use crate::{
-	ObjValue, Pending, Result, SupThis, Thunk, Val, error::ErrorKind::*, gc::WithCapacityExt as _,
-	map::LayeredHashMap,
+	ObjValue, Pending, Result, SupThis, Thunk, Val, bail, error::ErrorKind::*,
+	gc::WithCapacityExt as _,
 };
 /// Context keeps information about current lexical code location
 ///
@@ -20,7 +20,9 @@
 struct ContextInternal {
 	dollar: Option<ObjValue>,
 	sup_this: Option<SupThis>,
-	bindings: LayeredHashMap,
+	bindings: FxHashMap<IStr, Thunk<Val>>,
+
+	branch_point: Option<Context>,
 }
 impl Context {
 	pub fn new_future() -> Pending<Self> {
@@ -71,14 +73,18 @@
 			return Ok(val);
 		}
 
+		if let Some(branch_point) = &self.0.branch_point {
+			return branch_point.binding(name);
+		}
+
 		let mut heap = Vec::new();
-		self.0.bindings.clone().iter_keys(|k| {
-			let conf = strsim::jaro_winkler(&k as &str, &name as &str);
+		for k in self.0.bindings.keys() {
+			let conf = strsim::jaro_winkler(k as &str, &name as &str);
 			if conf < 0.8 {
-				return;
+				continue;
 			}
-			heap.push((conf, k));
-		});
+			heap.push((conf, k.clone()));
+		}
 		heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
 
 		bail!(VariableIsNotDefined(
@@ -98,103 +104,91 @@
 	}
 
 	#[must_use]
-	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_bindings(new_bindings)
-	}
-
-	#[must_use]
-	pub fn extend_bindings_sup_this(
-		self,
-		new_bindings: FxHashMap<IStr, Thunk<Val>>,
-		sup_this: SupThis,
-	) -> Self {
-		let ctx = &self;
-		let dollar = ctx
-			.0
-			.dollar
-			.clone()
-			.or_else(|| Some(sup_this.this().clone()));
-		let bindings = if new_bindings.is_empty() {
-			ctx.0.bindings.clone()
+	pub fn branch_point(self) -> Self {
+		if self.0.bindings.is_empty() {
+			self
 		} else {
-			ctx.0.bindings.clone().extend(new_bindings)
-		};
-		Self(Cc::new(ContextInternal {
-			dollar,
-			sup_this: Some(sup_this),
-			bindings,
-		}))
-	}
-	#[must_use]
-	pub fn extend_bindings(self, new_bindings: FxHashMap<IStr, Thunk<Val>>) -> Self {
-		if new_bindings.is_empty() {
-			return self;
+			ContextBuilder::extend(self).build()
 		}
-		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)]
+#[derive(Clone)]
 pub struct ContextBuilder {
+	dollar: Option<ObjValue>,
+	sup_this: Option<SupThis>,
 	bindings: FxHashMap<IStr, Thunk<Val>>,
-	extend: Option<Context>,
+	filled: FxHashSet<IStr>,
+	branch_point: Option<Context>,
 }
 
 impl ContextBuilder {
 	pub fn new() -> Self {
-		Self::with_capacity(0)
+		Self {
+			dollar: None,
+			sup_this: None,
+			bindings: FxHashMap::new(),
+			filled: FxHashSet::new(),
+			branch_point: None,
+		}
 	}
 
-	pub fn with_capacity(capacity: usize) -> Self {
+	pub fn extend_fast(parent: Context) -> Self {
 		Self {
-			bindings: FxHashMap::with_capacity(capacity),
-			extend: None,
+			dollar: parent.0.dollar.clone(),
+			sup_this: parent.0.sup_this.clone(),
+			bindings: parent.0.bindings.clone(),
+			filled: FxHashSet::new(),
+			branch_point: parent.0.branch_point.clone(),
 		}
 	}
 
 	pub fn extend(parent: Context) -> Self {
 		Self {
+			dollar: parent.0.dollar.clone(),
+			sup_this: parent.0.sup_this.clone(),
 			bindings: FxHashMap::new(),
-			extend: Some(parent),
+			filled: FxHashSet::new(),
+			branch_point: Some(parent.clone()),
 		}
 	}
 
-	/// # Panics
-	///
-	/// 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");
+	pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) {
+		let _ = self.bindings.insert(name.into(), value);
+	}
+	/// After commit, binds would shadow the previous declarations
+	#[must_use]
+	pub fn commit(mut self) -> Self {
+		self.filled.clear();
 		self
 	}
-	pub fn binds(&mut self, bindings: FxHashMap<IStr, Thunk<Val>>) -> &mut Self {
-		for (k, v) in bindings {
-			self.bind(k, v);
+	pub fn try_bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> Result<()> {
+		let name = name.into();
+		if !self.filled.insert(name.clone()) {
+			bail!(DuplicateLocalVar(name))
 		}
-		self
+		self.bind(name, value);
+		Ok(())
 	}
 	pub fn build(self) -> Context {
-		if let Some(parent) = self.extend {
-			parent.extend_bindings(self.bindings)
-		} else {
-			Context(Cc::new(ContextInternal {
-				bindings: LayeredHashMap::new(self.bindings),
-				dollar: None,
-				sup_this: None,
-			}))
+		Context(Cc::new(ContextInternal {
+			dollar: self.dollar,
+			sup_this: self.sup_this,
+			bindings: self.bindings,
+			branch_point: self.branch_point,
+		}))
+	}
+	pub fn build_sup_this(mut self, st: SupThis) -> Context {
+		if self.dollar.is_none() {
+			self.dollar = Some(st.this().clone());
 		}
+		self.sup_this = Some(st);
+		self.build()
+	}
+}
+
+impl Default for ContextBuilder {
+	fn default() -> Self {
+		Self::new()
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -249,6 +249,10 @@
 
 #[derive(Clone, Trace)]
 pub struct Error(Box<(ErrorKind, StackTrace)>);
+
+#[cfg(target_pointer_width = "64")]
+static_assertions::assert_eq_size!(Error, usize);
+
 impl Error {
 	pub fn new(e: ErrorKind) -> Self {
 		Self(Box::new((e, StackTrace(vec![]))))
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -1,30 +1,23 @@
-use std::{collections::HashMap, hash::BuildHasher};
-
-use jrsonnet_interner::IStr;
 use jrsonnet_ir::{BindSpec, Destruct};
 
 #[cfg(feature = "exp-preserve-order")]
 use crate::evaluate;
 use crate::{
-	Context, Pending, Thunk, Val, bail,
-	error::{ErrorKind::*, Result},
-	evaluate_method, evaluate_named_param,
+	Context, ContextBuilder, Pending, Thunk, Val, error::Result, evaluate_method,
+	evaluate_named_param,
 };
 
 #[allow(clippy::too_many_lines)]
 #[allow(unused_variables)]
-pub fn destruct<H: BuildHasher>(
+pub fn destruct(
 	d: &Destruct,
 	parent: Thunk<Val>,
 	fctx: Pending<Context>,
-	new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
+	new_bindings: &mut ContextBuilder,
 ) -> Result<()> {
 	match d {
 		Destruct::Full(v) => {
-			let old = new_bindings.insert(v.clone(), parent);
-			if old.is_some() {
-				bail!(DuplicateLocalVar(v.clone()))
-			}
+			new_bindings.try_bind(v.clone(), parent)?;
 		}
 		#[cfg(feature = "exp-destruct")]
 		Destruct::Skip => {}
@@ -187,10 +180,10 @@
 	Ok(())
 }
 
-pub fn evaluate_dest<H: BuildHasher>(
+pub fn evaluate_dest(
 	d: &BindSpec,
 	fctx: Pending<Context>,
-	new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
+	new_bindings: &mut ContextBuilder,
 ) -> Result<()> {
 	match d {
 		BindSpec::Field { into, value } => {
@@ -210,13 +203,10 @@
 			let params = params.clone();
 			let name = name.clone();
 			let value = value.clone();
-			let old = new_bindings.insert(name.clone(), {
-				let name = name.clone();
-				Thunk!(move || Ok(evaluate_method(fctx.unwrap(), name, params, value)))
-			});
-			if old.is_some() {
-				bail!(DuplicateLocalVar(name))
-			}
+			new_bindings.try_bind(
+				name.clone(),
+				Thunk!(move || Ok(evaluate_method(fctx.unwrap(), name, params, value))),
+			)?;
 		}
 	}
 	Ok(())
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -8,19 +8,17 @@
 	function::ParamName,
 };
 use jrsonnet_types::ValType;
-use rustc_hash::FxHashMap;
 
 use self::destructure::destruct;
 use crate::{
-	Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
-	SupThis, Unbound, Val,
+	Context, ContextBuilder, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+	ResultExt, SupThis, Unbound, Val,
 	arr::ArrValue,
 	bail,
 	destructure::evaluate_dest,
 	error::{ErrorKind::*, suggest_object_fields},
 	evaluate::operator::{evaluate_binary_op_special, evaluate_unary_op},
 	function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
-	gc::WithCapacityExt as _,
 	in_frame,
 	typed::{FromUntyped, IntoUntyped as _, Typed},
 	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
@@ -130,9 +128,9 @@
 					guaranteed_reserve = guaranteed_reserve.max(1) * list.len();
 					for (i, item) in list.iter_lazy().enumerate() {
 						let fctx = Pending::new();
-						let mut new_bindings = FxHashMap::with_capacity(into.binds_len());
-						destruct(into, item, fctx.clone(), &mut new_bindings)?;
-						let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
+						let mut ctx = ContextBuilder::extend_fast(ctx.clone());
+						destruct(into, item, fctx.clone(), &mut ctx)?;
+						let ctx = ctx.build().into_future(fctx);
 
 						let specs = &specs[1..];
 						evaluate_comp(
@@ -179,6 +177,7 @@
 }
 
 fn evaluate_arr_comp(ctx: Context, expr: &Rc<Expr>, comp_specs: &[CompSpec]) -> Result<ArrValue> {
+	let ctx = ctx.branch_point();
 	'eager: {
 		let mut out = Vec::new();
 
@@ -225,17 +224,13 @@
 
 		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::binds_len).sum());
+			let ctx = self.fctx.clone();
+			let mut ctx = ContextBuilder::extend(ctx);
 			for b in self.locals.iter() {
-				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+				evaluate_dest(b, fctx.clone(), &mut ctx)?;
 			}
 
-			let ctx = self.fctx.clone();
-
-			let ctx = ctx
-				.extend_bindings_sup_this(new_bindings, sup_this)
-				.into_future(fctx);
+			let ctx = ctx.build_sup_this(sup_this).into_future(fctx);
 
 			Ok(ctx)
 		}
@@ -332,10 +327,7 @@
 impl Unbound for DirectUnbound {
 	type Bound = Context;
 	fn bind(&self, sup_this: SupThis) -> Result<Context> {
-		Ok(self
-			.0
-			.clone()
-			.extend_bindings_sup_this(FxHashMap::new(), sup_this))
+		Ok(ContextBuilder::extend(self.0.clone()).build_sup_this(sup_this))
 	}
 }
 
@@ -408,12 +400,17 @@
 				builder.with_super(super_obj);
 			}
 			let locals = obj.locals.clone();
-			evaluate_comp(ctx, &obj.compspecs, 0, &mut |ctx, reserve| {
-				let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
-				builder.reserve_fields(reserve);
+			evaluate_comp(
+				ctx.branch_point(),
+				&obj.compspecs,
+				0,
+				&mut |ctx, reserve| {
+					let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
+					builder.reserve_fields(reserve);
 
-				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
-			})?;
+					evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
+				},
+			)?;
 
 			builder.build()
 		}
@@ -684,13 +681,12 @@
 			Ok(indexable)
 		})?,
 		LocalExpr(bindings, returned) => {
-			let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =
-				FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());
 			let fctx = Context::new_future();
+			let mut ctx = ContextBuilder::extend(ctx);
 			for b in bindings {
-				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+				evaluate_dest(b, fctx.clone(), &mut ctx)?;
 			}
-			let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
+			let ctx = ctx.build().into_future(fctx);
 			evaluate(ctx, returned)?
 		}
 		Arr(items) => {
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,12 +1,10 @@
 use jrsonnet_ir::ExprParams;
-use rustc_hash::FxHashMap;
 
 use crate::{
-	Context, Thunk,
+	Context, ContextBuilder, Thunk,
 	destructure::destruct,
 	error::{ErrorKind::*, Result},
 	evaluate_named_param,
-	gc::WithCapacityExt as _,
 };
 
 /// Creates Context, which has all argument default values applied
@@ -14,7 +12,7 @@
 pub fn parse_default_function_call(body_ctx: Context, params: &ExprParams) -> Result<Context> {
 	let fctx = Context::new_future();
 
-	let mut bindings = FxHashMap::with_capacity(params.binds_len());
+	let mut ctx = ContextBuilder::extend(body_ctx);
 
 	for param in params.exprs.iter() {
 		if let Some(v) = &param.default {
@@ -27,7 +25,7 @@
 					Thunk!(move || evaluate_named_param(ctx.unwrap(), &value, name))
 				},
 				fctx.clone(),
-				&mut bindings,
+				&mut ctx,
 			)?;
 		} else {
 			destruct(
@@ -42,10 +40,10 @@
 					.into()))
 				},
 				fctx.clone(),
-				&mut bindings,
+				&mut ctx,
 			)?;
 		}
 	}
 
-	Ok(body_ctx.extend_bindings(bindings).into_future(fctx))
+	Ok(ctx.build().into_future(fctx))
 }
modifiedcrates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -2,12 +2,12 @@
 
 use jrsonnet_gcmodule::{Acyclic, Trace};
 use jrsonnet_ir::{ExprParams, IStr, function::FunctionSignature};
-use rustc_hash::{FxHashMap, FxHashSet};
+use rustc_hash::FxHashSet;
 
 use super::{CallLocation, FuncVal};
 use crate::{
 	Context, ContextBuilder, Pending, Result, Thunk, Val, bail, destructure::destruct,
-	error::ErrorKind::*, evaluate_named_param, gc::WithCapacityExt,
+	error::ErrorKind::*, evaluate_named_param,
 };
 
 #[derive(Debug, Trace, Clone)]
@@ -118,7 +118,7 @@
 	unnamed: &[Thunk<Val>],
 	named: &[Thunk<Val>],
 ) -> Result<Context> {
-	let mut passed_args = FxHashMap::with_capacity(params.binds_len());
+	let mut ctx = ContextBuilder::extend(body_ctx);
 
 	let destruct_ctx = Pending::new();
 
@@ -127,7 +127,7 @@
 			&params.exprs[param_idx].destruct,
 			unnamed.clone(),
 			destruct_ctx.clone(),
-			&mut passed_args,
+			&mut ctx,
 		)?;
 	}
 
@@ -136,18 +136,16 @@
 			&params.exprs[param_idx].destruct,
 			named[arg_idx].clone(),
 			destruct_ctx.clone(),
-			&mut passed_args,
+			&mut ctx,
 		)?;
 	}
 
 	if prepared.defaults.is_empty() {
-		let body_ctx = body_ctx
-			.extend_bindings(passed_args)
-			.into_future(destruct_ctx);
+		let body_ctx = ctx.build().into_future(destruct_ctx);
 		Ok(body_ctx)
 	} else {
 		let fctx = Context::new_future();
-		let mut defaults = FxHashMap::with_capacity(params.binds_len() - passed_args.len());
+		let mut ctx = ctx.commit();
 		for param_idx in prepared.defaults.iter().copied() {
 			// let param = params.0.rc_idx(param_idx);
 			destruct(
@@ -163,13 +161,10 @@
 					})
 				},
 				fctx.clone(),
-				&mut defaults,
+				&mut ctx,
 			)?;
 		}
 
-		let mut ctx = ContextBuilder::extend(body_ctx);
-		ctx.binds(passed_args);
-		ctx.binds(defaults);
 		Ok(ctx.build().into_future(fctx).into_future(destruct_ctx))
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -31,3 +31,5 @@
 }
 
 pub fn assert_trace<T: Trace>(_v: &T) {}
+
+pub type ImHashMap<K, V> = im_rc::HashMap<K, V, FxBuildHasher>;
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod map;19mod obj;20pub mod stack;21pub mod stdlib;22pub mod tla;23pub mod trace;24pub mod typed;25pub mod val;2627use std::{28	any::Any,29	cell::{RefCell, RefMut},30	clone::Clone,31	collections::hash_map::Entry,32	fmt::{self, Debug},33	marker::PhantomData,34	rc::Rc,35};3637pub use ctx::*;38pub use dynamic::*;39pub use error::{Error, ErrorKind::*, Result, ResultExt};40pub use evaluate::*;41use function::CallLocation;42pub use import::*;43use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};44pub use jrsonnet_interner::{IBytes, IStr};45pub use jrsonnet_ir as parser;46use jrsonnet_ir::{Expr, Source, SourcePath};47#[doc(hidden)]48pub use jrsonnet_macros;4950#[cfg(not(any(feature = "ir-parser", feature = "peg-parser")))]51compile_error!("at least one of `ir-parser` or `peg-parser` features must be enabled");5253pub use error::SyntaxError;54pub use obj::*;55pub use rustc_hash;56use rustc_hash::FxHashMap;57use stack::check_depth;58pub use tla::apply_tla;59pub use val::{Thunk, Val};6061use crate::gc::WithCapacityExt as _;6263#[allow(clippy::needless_return)]64pub(crate) fn parse_jsonnet(code: &str, source: Source) -> Result<Expr, SyntaxError> {65	#[cfg(feature = "peg-parser")]66	{67		use std::sync::LazyLock;68		static USE_LEGACY_PARSER: LazyLock<bool> =69			LazyLock::new(|| std::env::var_os("JRSONNET_LEGACY_PARSER").is_some());7071		if *USE_LEGACY_PARSER {72			return parse_peg(code, source);73		}74	}75	#[cfg(feature = "ir-parser")]76	{77		return parse_ir(code, source);78	}79	#[cfg(feature = "peg-parser")]80	{81		return parse_peg(code, source);82	}83}8485#[cfg(feature = "ir-parser")]86fn parse_ir(code: &str, source: Source) -> Result<Expr, SyntaxError> {87	jrsonnet_ir_parser::parse(code, &jrsonnet_ir_parser::ParserSettings { source }).map_err(|e| {88		SyntaxError {89			message: e.message,90			location: (e.location.0, e.location.1),91		}92	})93}9495#[cfg(feature = "peg-parser")]96fn parse_peg(code: &str, source: Source) -> Result<Expr, SyntaxError> {97	jrsonnet_peg_parser::parse(code, &jrsonnet_peg_parser::ParserSettings { source }).map_err(|e| {98		let message = e99			.expected100			.tokens()101			.find(|t| t.starts_with("!!!"))102			.map_or_else(103				|| {104					format!(105						"expected {}, got {:?}",106						e.expected,107						code.chars()108							.nth(e.location.0)109							.map_or_else(|| "EOF".into(), |c: char| c.to_string())110					)111				},112				|v| v[3..].into(),113			);114		SyntaxError {115			message,116			location: e.location,117		}118	})119}120121cc_dyn!(122	#[derive(Clone)]123	CcUnbound<V>,124	Unbound<Bound = V>125);126127/// Thunk without bound `super`/`this`128/// object inheritance may be overriden multiple times, and will be fixed only on field read129pub trait Unbound: Trace {130	/// Type of value after object context is bound131	type Bound;132	/// Create value bound to specified object context133	fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;134}135136/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code137/// Standard jsonnet fields are always unbound138#[derive(Clone, Trace)]139pub enum MaybeUnbound {140	/// Value needs to be bound to `this`/`super`141	Unbound(CcUnbound<Val>),142	/// Value is object-independent143	Bound(Thunk<Val>),144}145146impl Debug for MaybeUnbound {147	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {148		write!(f, "MaybeUnbound")149	}150}151impl MaybeUnbound {152	/// Attach object context to value, if required153	pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {154		match self {155			Self::Unbound(v) => v.0.bind(sup_this),156			Self::Bound(v) => Ok(v.evaluate()?),157		}158	}159}160161cc_dyn!(CcContextInitializer, ContextInitializer);162163/// During import, this trait will be called to create initial context for file.164/// It may initialize global variables, stdlib for example.165pub trait ContextInitializer: Trace {166	/// For which size the builder should be preallocated167	fn reserve_vars(&self) -> usize {168		0169	}170	/// Initialize default file context.171	/// Has default implementation, which calls `populate`.172	/// Prefer to always implement `populate` instead.173	fn initialize(&self, for_file: Source) -> Context {174		let mut builder = ContextBuilder::with_capacity(self.reserve_vars());175		self.populate(for_file, &mut builder);176		builder.build()177	}178	/// For composability: extend builder. May panic if this initialization is not supported,179	/// and the context may only be created via `initialize`.180	fn populate(&self, for_file: Source, builder: &mut ContextBuilder);181	/// Allows upcasting from abstract to concrete context initializer.182	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.183	fn as_any(&self) -> &dyn Any;184}185186/// Context initializer which adds nothing.187impl ContextInitializer for () {188	fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}189	fn as_any(&self) -> &dyn Any {190		self191	}192}193194impl<T> ContextInitializer for Option<T>195where196	T: ContextInitializer,197{198	fn initialize(&self, for_file: Source) -> Context {199		if let Some(ctx) = self {200			ctx.initialize(for_file)201		} else {202			().initialize(for_file)203		}204	}205206	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {207		if let Some(ctx) = self {208			ctx.populate(for_file, builder);209		}210	}211212	fn as_any(&self) -> &dyn Any {213		self214	}215}216217macro_rules! impl_context_initializer {218	($($gen:ident)*) => {219		#[allow(non_snake_case)]220		impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {221			fn reserve_vars(&self) -> usize {222				let mut out = 0;223				let ($($gen,)*) = self;224				$(out += $gen.reserve_vars();)*225				out226			}227			fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {228				let ($($gen,)*) = self;229				$($gen.populate(for_file.clone(), builder);)*230			}231			fn as_any(&self) -> &dyn Any {232				self233			}234		}235	};236	($($cur:ident)* @ $c:ident $($rest:ident)*) => {237		impl_context_initializer!($($cur)*);238		impl_context_initializer!($($cur)* $c @ $($rest)*);239	};240	($($cur:ident)* @) => {241		impl_context_initializer!($($cur)*);242	}243}244impl_context_initializer! {245	A @ B C D E F G246}247248#[derive(Trace)]249struct FileData {250	string: Option<IStr>,251	bytes: Option<IBytes>,252	parsed: Option<Rc<Expr>>,253	evaluated: Option<Val>,254255	evaluating: bool,256}257impl FileData {258	fn new_string(data: IStr) -> Self {259		Self {260			string: Some(data),261			bytes: None,262			parsed: None,263			evaluated: None,264			evaluating: false,265		}266	}267	fn new_bytes(data: IBytes) -> Self {268		Self {269			string: None,270			bytes: Some(data),271			parsed: None,272			evaluated: None,273			evaluating: false,274		}275	}276	pub(crate) fn get_string(&mut self) -> Option<IStr> {277		if self.string.is_none() {278			self.string = Some(279				self.bytes280					.as_ref()281					.expect("either string or bytes should be set")282					.clone()283					.cast_str()?,284			);285		}286		Some(self.string.clone().expect("just set"))287	}288}289290#[derive(Trace)]291pub struct EvaluationStateInternals {292	/// Internal state293	file_cache: RefCell<FxHashMap<SourcePath, FileData>>,294	/// Context initializer, which will be used for imports and everything295	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`296	context_initializer: CcContextInitializer,297	/// Used to resolve file locations/contents298	import_resolver: Rc<dyn ImportResolver>,299}300301/// Maintains stack trace and import resolution302#[derive(Clone, Trace)]303pub struct State(Cc<EvaluationStateInternals>);304305thread_local! {306	pub static DEFAULT_STATE: State = State::builder().build();307	pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};308}309pub struct StateEnterGuard(PhantomData<()>);310impl Drop for StateEnterGuard {311	fn drop(&mut self) {312		STATE.with_borrow_mut(|v| *v = None);313	}314}315316pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {317	if let Some(state) = STATE.with_borrow(Clone::clone) {318		v(state)319	} else {320		let s = DEFAULT_STATE.with(Clone::clone);321		v(s)322	}323}324325impl State {326	pub fn enter(&self) -> StateEnterGuard {327		self.try_enter().expect("entered state already exists")328	}329	pub fn try_enter(&self) -> Option<StateEnterGuard> {330		STATE.with_borrow_mut(|v| {331			if v.is_none() {332				*v = Some(self.clone());333				Some(StateEnterGuard(PhantomData))334			} else {335				None336			}337		})338	}339	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise340	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {341		let mut file_cache = self.file_cache();342		let mut file = file_cache.entry(path.clone());343344		let file = match file {345			Entry::Occupied(ref mut d) => d.get_mut(),346			Entry::Vacant(v) => {347				let data = self.import_resolver().load_file_contents(&path)?;348				v.insert(FileData::new_string(349					std::str::from_utf8(&data)350						.map_err(|_| ImportBadFileUtf8(path.clone()))?351						.into(),352				))353			}354		};355		Ok(file356			.get_string()357			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?)358	}359	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise360	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {361		let mut file_cache = self.file_cache();362		let mut file = file_cache.entry(path.clone());363364		let file = match file {365			Entry::Occupied(ref mut d) => d.get_mut(),366			Entry::Vacant(v) => {367				let data = self.import_resolver().load_file_contents(&path)?;368				v.insert(FileData::new_bytes(data.as_slice().into()))369			}370		};371		if let Some(str) = &file.bytes {372			return Ok(str.clone());373		}374		if file.bytes.is_none() {375			file.bytes = Some(376				file.string377					.as_ref()378					.expect("either string or bytes should be set")379					.clone()380					.cast_bytes(),381			);382		}383		Ok(file.bytes.as_ref().expect("just set").clone())384	}385	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise386	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {387		let mut file_cache = self.file_cache();388		let mut file = file_cache.entry(path.clone());389390		let file = match file {391			Entry::Occupied(ref mut d) => d.get_mut(),392			Entry::Vacant(v) => {393				let data = self.import_resolver().load_file_contents(&path)?;394				v.insert(FileData::new_string(395					std::str::from_utf8(&data)396						.map_err(|_| ImportBadFileUtf8(path.clone()))?397						.into(),398				))399			}400		};401		if let Some(val) = &file.evaluated {402			return Ok(val.clone());403		}404		let code = file405			.get_string()406			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?;407		let file_name = Source::new(path.clone(), code.clone());408		if file.parsed.is_none() {409			file.parsed = Some(410				parse_jsonnet(&code, file_name.clone())411					.map(Rc::new)412					.map_err(|e| ImportSyntaxError {413						path: file_name.clone(),414						error: Box::new(e),415					})?,416			);417		}418		let parsed = file.parsed.as_ref().expect("just set").clone();419		if file.evaluating {420			bail!(InfiniteRecursionDetected)421		}422		file.evaluating = true;423		// Dropping file cache guard here, as evaluation may use this map too424		drop(file_cache);425		let res = evaluate(self.create_default_context(file_name), &parsed);426427		let mut file_cache = self.file_cache();428		let mut file = file_cache.entry(path);429430		let Entry::Occupied(file) = &mut file else {431			unreachable!("this file was just here")432		};433		let file = file.get_mut();434		file.evaluating = false;435		match res {436			Ok(v) => {437				file.evaluated = Some(v.clone());438				Ok(v)439			}440			Err(e) => Err(e),441		}442	}443444	/// Has same semantics as `import 'path'` called from `from` file445	pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {446		let resolved = self.resolve_from(from, &path)?;447		self.import_resolved(resolved)448	}449	pub fn import(&self, path: impl AsPathLike) -> Result<Val> {450		let resolved = self.resolve_from_default(&path)?;451		self.import_resolved(resolved)452	}453454	/// Creates context with all passed global variables455	pub fn create_default_context(&self, source: Source) -> Context {456		self.context_initializer().initialize(source)457	}458459	/// Creates context with all passed global variables, calling custom modifier460	pub fn create_default_context_with(461		&self,462		source: Source,463		context_initializer: impl ContextInitializer,464	) -> Context {465		let default_initializer = self.context_initializer();466		let mut builder = ContextBuilder::with_capacity(467			default_initializer.reserve_vars() + context_initializer.reserve_vars(),468		);469		default_initializer.populate(source.clone(), &mut builder);470		context_initializer.populate(source, &mut builder);471472		builder.build()473	}474}475476/// Internals477impl State {478	fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {479		self.0.file_cache.borrow_mut()480	}481}482/// Executes code creating a new stack frame, to be replaced with try{}483pub fn in_frame<T>(484	e: CallLocation<'_>,485	frame_desc: impl FnOnce() -> String,486	f: impl FnOnce() -> Result<T>,487) -> Result<T> {488	let _guard = check_depth()?;489490	f().with_description_src(e, frame_desc)491}492493/// Executes code creating a new stack frame, to be replaced with try{}494pub fn in_description_frame<T>(495	frame_desc: impl FnOnce() -> String,496	f: impl FnOnce() -> Result<T>,497) -> Result<T> {498	let _guard = check_depth()?;499500	f().with_description(frame_desc)501}502503#[derive(Trace)]504pub struct InitialUnderscore(pub Thunk<Val>);505impl ContextInitializer for InitialUnderscore {506	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {507		builder.bind("_", self.0.clone());508	}509510	fn as_any(&self) -> &dyn Any {511		self512	}513}514515/// Raw methods evaluate passed values but don't perform TLA execution516impl State {517	/// Parses and evaluates the given snippet518	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {519		let code = code.into();520		let source = Source::new_virtual(name.into(), code.clone());521		let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {522			path: source.clone(),523			error: Box::new(e),524		})?;525		evaluate(self.create_default_context(source), &parsed)526	}527	/// Parses and evaluates the given snippet with custom context modifier528	pub fn evaluate_snippet_with(529		&self,530		name: impl Into<IStr>,531		code: impl Into<IStr>,532		context_initializer: impl ContextInitializer,533	) -> Result<Val> {534		let code = code.into();535		let source = Source::new_virtual(name.into(), code.clone());536		let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {537			path: source.clone(),538			error: Box::new(e),539		})?;540		evaluate(541			self.create_default_context_with(source, context_initializer),542			&parsed,543		)544	}545}546547/// Settings utilities548impl State {549	// Only panics in case of [`ImportResolver`] contract violation550	#[allow(clippy::missing_panics_doc)]551	pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {552		self.import_resolver().resolve_from(from, path)553	}554	#[allow(clippy::missing_panics_doc)]555	pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {556		self.import_resolver().resolve_from_default(path)557	}558	pub fn import_resolver(&self) -> &dyn ImportResolver {559		&*self.0.import_resolver560	}561	pub fn context_initializer(&self) -> &dyn ContextInitializer {562		&*self.0.context_initializer.0563	}564}565566impl State {567	pub fn builder() -> StateBuilder {568		StateBuilder::default()569	}570}571572impl Default for State {573	fn default() -> Self {574		Self::builder().build()575	}576}577578#[derive(Default)]579pub struct StateBuilder {580	import_resolver: Option<Rc<dyn ImportResolver>>,581	context_initializer: Option<CcContextInitializer>,582}583impl StateBuilder {584	pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {585		let _ = self.import_resolver.insert(Rc::new(import_resolver));586		self587	}588	pub fn context_initializer(589		&mut self,590		context_initializer: impl ContextInitializer,591	) -> &mut Self {592		let _ = self593			.context_initializer594			.insert(CcContextInitializer::new(context_initializer));595		self596	}597	pub fn build(mut self) -> State {598		State(Cc::new(EvaluationStateInternals {599			file_cache: RefCell::new(FxHashMap::new()),600			context_initializer: self601				.context_initializer602				.take()603				.unwrap_or_else(|| CcContextInitializer::new(())),604			import_resolver: self605				.import_resolver606				.take()607				.unwrap_or_else(|| Rc::new(DummyImportResolver)),608		}))609	}610}
after · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod obj;19pub mod stack;20pub mod stdlib;21pub mod tla;22pub mod trace;23pub mod typed;24pub mod val;2526use std::{27	any::Any,28	cell::{RefCell, RefMut},29	clone::Clone,30	collections::hash_map::Entry,31	fmt::{self, Debug},32	marker::PhantomData,33	rc::Rc,34};3536pub use ctx::*;37pub use dynamic::*;38pub use error::{Error, ErrorKind::*, Result, ResultExt};39pub use evaluate::*;40use function::CallLocation;41pub use import::*;42use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};43pub use jrsonnet_interner::{IBytes, IStr};44pub use jrsonnet_ir as parser;45use jrsonnet_ir::{Expr, Source, SourcePath};46#[doc(hidden)]47pub use jrsonnet_macros;4849#[cfg(not(any(feature = "ir-parser", feature = "peg-parser")))]50compile_error!("at least one of `ir-parser` or `peg-parser` features must be enabled");5152pub use error::SyntaxError;53pub use obj::*;54pub use rustc_hash;55use rustc_hash::FxHashMap;56use stack::check_depth;57pub use tla::apply_tla;58pub use val::{Thunk, Val};5960use crate::gc::WithCapacityExt as _;6162#[allow(clippy::needless_return)]63pub(crate) fn parse_jsonnet(code: &str, source: Source) -> Result<Expr, SyntaxError> {64	#[cfg(feature = "peg-parser")]65	{66		use std::sync::LazyLock;67		static USE_LEGACY_PARSER: LazyLock<bool> =68			LazyLock::new(|| std::env::var_os("JRSONNET_LEGACY_PARSER").is_some());6970		if *USE_LEGACY_PARSER {71			return parse_peg(code, source);72		}73	}74	#[cfg(feature = "ir-parser")]75	{76		return parse_ir(code, source);77	}78	#[cfg(feature = "peg-parser")]79	{80		return parse_peg(code, source);81	}82}8384#[cfg(feature = "ir-parser")]85fn parse_ir(code: &str, source: Source) -> Result<Expr, SyntaxError> {86	jrsonnet_ir_parser::parse(code, &jrsonnet_ir_parser::ParserSettings { source }).map_err(|e| {87		SyntaxError {88			message: e.message,89			location: (e.location.0, e.location.1),90		}91	})92}9394#[cfg(feature = "peg-parser")]95fn parse_peg(code: &str, source: Source) -> Result<Expr, SyntaxError> {96	jrsonnet_peg_parser::parse(code, &jrsonnet_peg_parser::ParserSettings { source }).map_err(|e| {97		let message = e98			.expected99			.tokens()100			.find(|t| t.starts_with("!!!"))101			.map_or_else(102				|| {103					format!(104						"expected {}, got {:?}",105						e.expected,106						code.chars()107							.nth(e.location.0)108							.map_or_else(|| "EOF".into(), |c: char| c.to_string())109					)110				},111				|v| v[3..].into(),112			);113		SyntaxError {114			message,115			location: e.location,116		}117	})118}119120cc_dyn!(121	#[derive(Clone)]122	CcUnbound<V>,123	Unbound<Bound = V>124);125126/// Thunk without bound `super`/`this`127/// object inheritance may be overriden multiple times, and will be fixed only on field read128pub trait Unbound: Trace {129	/// Type of value after object context is bound130	type Bound;131	/// Create value bound to specified object context132	fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;133}134135/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code136/// Standard jsonnet fields are always unbound137#[derive(Clone, Trace)]138pub enum MaybeUnbound {139	/// Value needs to be bound to `this`/`super`140	Unbound(CcUnbound<Val>),141	/// Value is object-independent142	Bound(Thunk<Val>),143}144145impl Debug for MaybeUnbound {146	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {147		write!(f, "MaybeUnbound")148	}149}150impl MaybeUnbound {151	/// Attach object context to value, if required152	pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {153		match self {154			Self::Unbound(v) => v.0.bind(sup_this),155			Self::Bound(v) => Ok(v.evaluate()?),156		}157	}158}159160cc_dyn!(CcContextInitializer, ContextInitializer);161162/// During import, this trait will be called to create initial context for file.163/// It may initialize global variables, stdlib for example.164pub trait ContextInitializer {165	/// For composability: extend builder. May panic if this initialization is not supported,166	/// and the context may only be created via `initialize`.167	fn populate(&self, for_file: Source, builder: &mut ContextBuilder);168	/// Allows upcasting from abstract to concrete context initializer.169	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.170	fn as_any(&self) -> &dyn Any;171}172impl<T> ContextInitializer for &T173where174	T: ContextInitializer,175{176	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {177		(*self).populate(for_file, builder);178	}179180	fn as_any(&self) -> &dyn Any {181		(*self).as_any()182	}183}184185/// Context initializer which adds nothing.186impl ContextInitializer for () {187	fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}188	fn as_any(&self) -> &dyn Any {189		self190	}191}192193impl<T> ContextInitializer for Option<T>194where195	T: ContextInitializer + 'static,196{197	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {198		if let Some(ctx) = self {199			ctx.populate(for_file, builder);200		}201	}202203	fn as_any(&self) -> &dyn Any {204		self205	}206}207208macro_rules! impl_context_initializer {209	($($gen:ident)*) => {210		#[allow(non_snake_case)]211		impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {212			fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {213				let ($($gen,)*) = self;214				$($gen.populate(for_file.clone(), builder);)*215			}216			fn as_any(&self) -> &dyn Any {217				self218			}219		}220	};221	($($cur:ident)* @ $c:ident $($rest:ident)*) => {222		impl_context_initializer!($($cur)*);223		impl_context_initializer!($($cur)* $c @ $($rest)*);224	};225	($($cur:ident)* @) => {226		impl_context_initializer!($($cur)*);227	}228}229impl_context_initializer! {230	A @ B C D E F G231}232233#[derive(Trace)]234struct FileData {235	string: Option<IStr>,236	bytes: Option<IBytes>,237	parsed: Option<Rc<Expr>>,238	evaluated: Option<Val>,239240	evaluating: bool,241}242impl FileData {243	fn new_string(data: IStr) -> Self {244		Self {245			string: Some(data),246			bytes: None,247			parsed: None,248			evaluated: None,249			evaluating: false,250		}251	}252	fn new_bytes(data: IBytes) -> Self {253		Self {254			string: None,255			bytes: Some(data),256			parsed: None,257			evaluated: None,258			evaluating: false,259		}260	}261	pub(crate) fn get_string(&mut self) -> Option<IStr> {262		if self.string.is_none() {263			self.string = Some(264				self.bytes265					.as_ref()266					.expect("either string or bytes should be set")267					.clone()268					.cast_str()?,269			);270		}271		Some(self.string.clone().expect("just set"))272	}273}274275#[derive(Trace)]276pub struct EvaluationStateInternals {277	/// Internal state278	file_cache: RefCell<FxHashMap<SourcePath, FileData>>,279	/// Context initializer, which will be used for imports and everything280	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`281	context_initializer: CcContextInitializer,282	/// Used to resolve file locations/contents283	import_resolver: Rc<dyn ImportResolver>,284}285286/// Maintains stack trace and import resolution287#[derive(Clone, Trace)]288pub struct State(Cc<EvaluationStateInternals>);289290thread_local! {291	pub static DEFAULT_STATE: State = State::builder().build();292	pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};293}294pub struct StateEnterGuard(PhantomData<()>);295impl Drop for StateEnterGuard {296	fn drop(&mut self) {297		STATE.with_borrow_mut(|v| *v = None);298	}299}300301pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {302	if let Some(state) = STATE.with_borrow(Clone::clone) {303		v(state)304	} else {305		let s = DEFAULT_STATE.with(Clone::clone);306		v(s)307	}308}309310impl State {311	pub fn enter(&self) -> StateEnterGuard {312		self.try_enter().expect("entered state already exists")313	}314	pub fn try_enter(&self) -> Option<StateEnterGuard> {315		STATE.with_borrow_mut(|v| {316			if v.is_none() {317				*v = Some(self.clone());318				Some(StateEnterGuard(PhantomData))319			} else {320				None321			}322		})323	}324	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise325	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {326		let mut file_cache = self.file_cache();327		let mut file = file_cache.entry(path.clone());328329		let file = match file {330			Entry::Occupied(ref mut d) => d.get_mut(),331			Entry::Vacant(v) => {332				let data = self.import_resolver().load_file_contents(&path)?;333				v.insert(FileData::new_string(334					std::str::from_utf8(&data)335						.map_err(|_| ImportBadFileUtf8(path.clone()))?336						.into(),337				))338			}339		};340		Ok(file341			.get_string()342			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?)343	}344	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise345	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {346		let mut file_cache = self.file_cache();347		let mut file = file_cache.entry(path.clone());348349		let file = match file {350			Entry::Occupied(ref mut d) => d.get_mut(),351			Entry::Vacant(v) => {352				let data = self.import_resolver().load_file_contents(&path)?;353				v.insert(FileData::new_bytes(data.as_slice().into()))354			}355		};356		if let Some(str) = &file.bytes {357			return Ok(str.clone());358		}359		if file.bytes.is_none() {360			file.bytes = Some(361				file.string362					.as_ref()363					.expect("either string or bytes should be set")364					.clone()365					.cast_bytes(),366			);367		}368		Ok(file.bytes.as_ref().expect("just set").clone())369	}370	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise371	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {372		let mut file_cache = self.file_cache();373		let mut file = file_cache.entry(path.clone());374375		let file = match file {376			Entry::Occupied(ref mut d) => d.get_mut(),377			Entry::Vacant(v) => {378				let data = self.import_resolver().load_file_contents(&path)?;379				v.insert(FileData::new_string(380					std::str::from_utf8(&data)381						.map_err(|_| ImportBadFileUtf8(path.clone()))?382						.into(),383				))384			}385		};386		if let Some(val) = &file.evaluated {387			return Ok(val.clone());388		}389		let code = file390			.get_string()391			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?;392		let file_name = Source::new(path.clone(), code.clone());393		if file.parsed.is_none() {394			file.parsed = Some(395				parse_jsonnet(&code, file_name.clone())396					.map(Rc::new)397					.map_err(|e| ImportSyntaxError {398						path: file_name.clone(),399						error: Box::new(e),400					})?,401			);402		}403		let parsed = file.parsed.as_ref().expect("just set").clone();404		if file.evaluating {405			bail!(InfiniteRecursionDetected)406		}407		file.evaluating = true;408		// Dropping file cache guard here, as evaluation may use this map too409		drop(file_cache);410		let res = evaluate(self.create_default_context(file_name), &parsed);411412		let mut file_cache = self.file_cache();413		let mut file = file_cache.entry(path);414415		let Entry::Occupied(file) = &mut file else {416			unreachable!("this file was just here")417		};418		let file = file.get_mut();419		file.evaluating = false;420		match res {421			Ok(v) => {422				file.evaluated = Some(v.clone());423				Ok(v)424			}425			Err(e) => Err(e),426		}427	}428429	/// Has same semantics as `import 'path'` called from `from` file430	pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {431		let resolved = self.resolve_from(from, &path)?;432		self.import_resolved(resolved)433	}434	pub fn import(&self, path: impl AsPathLike) -> Result<Val> {435		let resolved = self.resolve_from_default(&path)?;436		self.import_resolved(resolved)437	}438439	/// Creates context with all passed global variables440	pub fn create_default_context(&self, source: Source) -> Context {441		self.create_default_context_with(source, &())442	}443444	/// Creates context with all passed global variables, calling custom modifier445	pub fn create_default_context_with(446		&self,447		source: Source,448		context_initializer: &dyn ContextInitializer,449	) -> Context {450		let default_initializer = self.context_initializer();451		let mut builder = ContextBuilder::new();452		default_initializer.populate(source.clone(), &mut builder);453		context_initializer.populate(source, &mut builder);454455		builder.build()456	}457}458459/// Internals460impl State {461	fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {462		self.0.file_cache.borrow_mut()463	}464}465/// Executes code creating a new stack frame, to be replaced with try{}466pub fn in_frame<T>(467	e: CallLocation<'_>,468	frame_desc: impl FnOnce() -> String,469	f: impl FnOnce() -> Result<T>,470) -> Result<T> {471	let _guard = check_depth()?;472473	f().with_description_src(e, frame_desc)474}475476/// Executes code creating a new stack frame, to be replaced with try{}477pub fn in_description_frame<T>(478	frame_desc: impl FnOnce() -> String,479	f: impl FnOnce() -> Result<T>,480) -> Result<T> {481	let _guard = check_depth()?;482483	f().with_description(frame_desc)484}485486#[derive(Trace)]487pub struct InitialUnderscore(pub Thunk<Val>);488impl ContextInitializer for InitialUnderscore {489	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {490		builder.bind("_", self.0.clone());491	}492493	fn as_any(&self) -> &dyn Any {494		self495	}496}497498/// Raw methods evaluate passed values but don't perform TLA execution499impl State {500	/// Parses and evaluates the given snippet501	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {502		self.evaluate_snippet_with(name, code, &())503	}504	/// Parses and evaluates the given snippet with custom context modifier505	pub fn evaluate_snippet_with(506		&self,507		name: impl Into<IStr>,508		code: impl Into<IStr>,509		context_initializer: &dyn ContextInitializer,510	) -> Result<Val> {511		let code = code.into();512		let source = Source::new_virtual(name.into(), code.clone());513		let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {514			path: source.clone(),515			error: Box::new(e),516		})?;517		evaluate(518			self.create_default_context_with(source, context_initializer),519			&parsed,520		)521	}522}523524/// Settings utilities525impl State {526	// Only panics in case of [`ImportResolver`] contract violation527	#[allow(clippy::missing_panics_doc)]528	pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {529		self.import_resolver().resolve_from(from, path)530	}531	#[allow(clippy::missing_panics_doc)]532	pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {533		self.import_resolver().resolve_from_default(path)534	}535	pub fn import_resolver(&self) -> &dyn ImportResolver {536		&*self.0.import_resolver537	}538	pub fn context_initializer(&self) -> &dyn ContextInitializer {539		&*self.0.context_initializer.0540	}541}542543impl State {544	pub fn builder() -> StateBuilder {545		StateBuilder::default()546	}547}548549impl Default for State {550	fn default() -> Self {551		Self::builder().build()552	}553}554555#[derive(Default)]556pub struct StateBuilder {557	import_resolver: Option<Rc<dyn ImportResolver>>,558	context_initializer: Option<CcContextInitializer>,559}560impl StateBuilder {561	pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {562		let _ = self.import_resolver.insert(Rc::new(import_resolver));563		self564	}565	pub fn context_initializer(566		&mut self,567		context_initializer: impl ContextInitializer + Trace,568	) -> &mut Self {569		let _ = self570			.context_initializer571			.insert(CcContextInitializer::new(context_initializer));572		self573	}574	pub fn build(mut self) -> State {575		State(Cc::new(EvaluationStateInternals {576			file_cache: RefCell::new(FxHashMap::new()),577			context_initializer: self578				.context_initializer579				.take()580				.unwrap_or_else(|| CcContextInitializer::new(())),581			import_resolver: self582				.import_resolver583				.take()584				.unwrap_or_else(|| Rc::new(DummyImportResolver)),585		}))586	}587}
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,4 +1,4 @@
-use std::{borrow::Cow, fmt::Write, ptr};
+use std::{borrow::Cow, fmt::Write, hint::black_box, ptr};
 
 use crate::{Result, ResultExt, Val, bail, in_description_frame};
 
@@ -44,6 +44,45 @@
 	}
 }
 
+pub struct BlackBoxFormat;
+impl ManifestFormat for BlackBoxFormat {
+	#[allow(clippy::only_used_in_recursion)]
+	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+		match val {
+			Val::Bool(v) => {
+				black_box(v);
+			}
+			val @ Val::Null => {
+				black_box(val);
+			}
+			Val::Str(str_value) => {
+				black_box(format!("{str_value}"));
+			}
+			Val::Num(num_value) => {
+				black_box(num_value);
+			}
+			Val::Arr(arr_value) => {
+				for ele in arr_value.iter() {
+					let ele = ele?;
+					self.manifest_buf(ele, buf)?;
+				}
+			}
+			Val::Obj(obj_value) => {
+				for (name, value) in obj_value.iter() {
+					black_box(name);
+					let value = value?;
+					self.manifest_buf(value, buf)?;
+				}
+			}
+			Val::Func(func_val) => {
+				black_box(func_val);
+				bail!("tried to manifest function")
+			}
+		}
+		Ok(())
+	}
+}
+
 #[derive(PartialEq, Eq, Clone, Copy)]
 enum JsonFormatting {
 	// Applied in manifestification
@@ -66,7 +105,6 @@
 	preserve_order: bool,
 	#[cfg(feature = "exp-bigint")]
 	preserve_bigints: bool,
-	debug_truncate_strings: Option<usize>,
 }
 
 impl<'s> JsonFormat<'s> {
@@ -81,7 +119,6 @@
 			preserve_order,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: false,
-			debug_truncate_strings: None,
 		}
 	}
 	/// Same format as std.toString, except does not keeps top-level string as-is
@@ -96,7 +133,6 @@
 			preserve_order: false,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: false,
-			debug_truncate_strings: None,
 		}
 	}
 	pub fn std_to_json(
@@ -114,7 +150,6 @@
 			preserve_order,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: false,
-			debug_truncate_strings: None,
 		}
 	}
 	// Same format as CLI manifestification
@@ -137,7 +172,6 @@
 			preserve_order,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: false,
-			debug_truncate_strings: None,
 		}
 	}
 	// Same format as CLI manifestification
@@ -151,7 +185,6 @@
 			preserve_order: true,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: true,
-			debug_truncate_strings: Some(256),
 		}
 	}
 }
@@ -166,7 +199,6 @@
 			preserve_order: false,
 			#[cfg(feature = "exp-bigint")]
 			preserve_bigints: false,
-			debug_truncate_strings: None,
 		}
 	}
 }
@@ -197,18 +229,12 @@
 		}
 		Val::Null => buf.push_str("null"),
 		Val::Str(s) => {
-			let flat = s.clone().into_flat();
-			if let Some(truncate) = options.debug_truncate_strings {
-				if flat.len() > truncate {
-					let (start, end) = flat.split_at(truncate / 2);
-					let (_, end) = end.split_at(end.len() - truncate / 2);
-					escape_string_json_buf(&format!("{start}..{end}"), buf);
-				} else {
-					escape_string_json_buf(&flat, buf);
-				}
-			} else {
-				escape_string_json_buf(&flat, buf);
-			}
+			buf.reserve(2 + s.len());
+			buf.push('"');
+			s.chunks(&mut |c| {
+				escape_string_json_buf_raw(c, buf);
+			});
+			buf.push('"');
 		}
 		Val::Num(n) => write!(buf, "{n}").unwrap(),
 		#[cfg(feature = "exp-bigint")]
@@ -476,15 +502,15 @@
 ];
 
 pub fn escape_string_json_buf(value: &str, buf: &mut String) {
+	buf.reserve_exact(value.len() + 2);
+	escape_string_json_buf_raw(value, buf);
+}
+
+fn escape_string_json_buf_raw(value: &str, buf: &mut String) {
 	// Safety: we only write correct utf-8 in this function
 	let buf: &mut Vec<u8> = unsafe { &mut *ptr::from_mut(buf).cast::<Vec<u8>>() };
 	let bytes = value.as_bytes();
-
-	// Perfect for ascii strings, removes any reallocations
-	buf.reserve(value.len() + 2);
 
-	buf.push(b'"');
-
 	let mut start = 0;
 
 	for (i, &byte) in bytes.iter().enumerate() {
@@ -519,10 +545,8 @@
 	}
 
 	if start == bytes.len() {
-		buf.push(b'"');
 		return;
 	}
 
 	buf.extend_from_slice(&bytes[start..]);
-	buf.push(b'"');
 }
deletedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use jrsonnet_gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use rustc_hash::FxHashMap;
-
-use crate::{Thunk, Val, gc::WithCapacityExt as _};
-
-#[derive(Trace, Debug)]
-#[trace(tracking(force))]
-pub struct LayeredHashMapInternals {
-	parent: Option<LayeredHashMap>,
-	current: FxHashMap<IStr, Thunk<Val>>,
-}
-
-#[derive(Trace, Debug)]
-pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
-
-impl LayeredHashMap {
-	pub fn iter_keys(self, mut handler: impl FnMut(IStr)) {
-		for k in self.0.current.keys() {
-			handler(k.clone());
-		}
-		if let Some(parent) = self.0.parent.clone() {
-			parent.iter_keys(handler);
-		}
-	}
-
-	pub(crate) fn new(layer: FxHashMap<IStr, Thunk<Val>>) -> Self {
-		Self(Cc::new(LayeredHashMapInternals {
-			parent: None,
-			current: layer,
-		}))
-	}
-
-	pub fn extend(self, new_layer: FxHashMap<IStr, Thunk<Val>>) -> Self {
-		Self(Cc::new(LayeredHashMapInternals {
-			parent: Some(self),
-			current: new_layer,
-		}))
-	}
-
-	pub fn get(&self, key: &IStr) -> Option<&Thunk<Val>> {
-		(self.0)
-			.current
-			.get(key)
-			.or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
-	}
-
-	pub fn contains_key(&self, key: &IStr) -> bool {
-		(self.0).current.contains_key(key)
-			|| self.0.parent.as_ref().is_some_and(|p| p.contains_key(key))
-	}
-}
-
-impl Clone for LayeredHashMap {
-	fn clone(&self) -> Self {
-		Self(self.0.clone())
-	}
-}
-
-impl Default for LayeredHashMap {
-	fn default() -> Self {
-		Self(Cc::new(LayeredHashMapInternals {
-			parent: None,
-			current: FxHashMap::new(),
-		}))
-	}
-}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -355,8 +355,19 @@
 			Self::Tree(Rc::new((a, b, len)))
 		}
 	}
+	pub fn chunks(&self, c: &mut impl FnMut(&IStr)) {
+		fn write_buf(s: &StrValue, c: &mut impl FnMut(&IStr)) {
+			match s {
+				StrValue::Flat(f) => c(f),
+				StrValue::Tree(t) => {
+					write_buf(&t.0, c);
+					write_buf(&t.1, c);
+				}
+			}
+		}
+		write_buf(self, c);
+	}
 	pub fn into_flat(&self) -> IStr {
-		#[cold]
 		fn write_buf(s: &StrValue, out: &mut String) {
 			match s {
 				StrValue::Flat(f) => out.push_str(f),
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -545,9 +545,6 @@
 	}
 }
 impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
-	fn reserve_vars(&self) -> usize {
-		1
-	}
 	fn populate(&self, source: Source, builder: &mut ContextBuilder) {
 		let mut std = ObjValueBuilder::new();
 		std.with_super(self.stdlib_obj.clone());
modifiedtests/Cargo.tomldiffbeforeafterboth
--- a/tests/Cargo.toml
+++ b/tests/Cargo.toml
@@ -18,6 +18,7 @@
 jrsonnet-evaluator.workspace = true
 jrsonnet-gcmodule.workspace = true
 jrsonnet-stdlib.workspace = true
+mimallocator.workspace = true
 serde.workspace = true
 serde_json.workspace = true