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

difftreelog

refactor only keep used spans in IR

uxonrmwzYaroslav Bolyukin2026-03-22parent: #44f6e2c.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -730,6 +730,7 @@
 version = "0.5.0-pre97"
 dependencies = [
  "insta",
+ "jrsonnet-gcmodule",
  "jrsonnet-ir",
  "peg",
 ]
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -38,7 +38,7 @@
 		Self::new(RangeArray::empty())
 	}
 
-	pub fn expr(ctx: Context, exprs: Rc<Vec<Spanned<Expr>>>) -> Self {
+	pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {
 		Self::new(ExprArray::new(ctx, exprs))
 	}
 
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -118,11 +118,11 @@
 #[derive(Debug, Trace, Clone)]
 pub struct ExprArray {
 	ctx: Context,
-	src: Rc<Vec<Spanned<Expr>>>,
+	src: Rc<Vec<Expr>>,
 	cached: Cc<RefCell<Vec<ArrayThunk>>>,
 }
 impl ExprArray {
-	pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {
+	pub fn new(ctx: Context, src: Rc<Vec<Expr>>) -> Self {
 		Self {
 			ctx,
 			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),
modifiedcrates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -139,7 +139,7 @@
 			if let Expr::Str(s) = &***v {
 				out.0.push(Import {
 					path: ResolvePathOwned::Str(s.to_string()),
-					expression: matches!(&**expr, Expr::Import(ImportKind::Normal, _)),
+					expression: todo!(),
 				});
 			}
 			// Non-string import will fail in runtime
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6	function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,7	FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,8	Spanned,9};10use jrsonnet_types::ValType;11use rustc_hash::FxHashMap;1213use self::destructure::destruct;14use crate::{15	arr::ArrValue,16	bail,17	destructure::evaluate_dest,18	error::{suggest_object_fields, ErrorKind::*},19	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},20	function::{CallLocation, FuncDesc, FuncVal},21	gc::WithCapacityExt as _,22	in_frame,23	typed::{FromUntyped, IntoUntyped as _, Typed},24	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25	with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,26	ResultExt, SupThis, Unbound, Val,27};28pub mod destructure;29pub mod operator;3031// This is the amount of bytes that need to be left on the stack before increasing the size.32// It must be at least as large as the stack required by any code that does not call33// `ensure_sufficient_stack`.34const RED_ZONE: usize = 100 * 1024; // 100k3536// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then37// on. This flag has performance relevant characteristics. Don't set it too high.38const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3940/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations41/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit42/// from this.43///44/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.45#[inline]46pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {47	stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)48}4950pub fn evaluate_trivial(expr: &Expr) -> Option<Val> {51	fn is_trivial(expr: &Expr) -> bool {52		match &*expr {53			Expr::Str(_)54			| Expr::Num(_)55			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,56			Expr::Arr(a) => a.iter().all(|e| is_trivial(&**e)),57			_ => false,58		}59	}60	Some(match &*expr {61		Expr::Str(s) => Val::string(s.clone()),62		Expr::Num(n) => {63			Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64		}65		Expr::Literal(LiteralType::False) => Val::Bool(false),66		Expr::Literal(LiteralType::True) => Val::Bool(true),67		Expr::Literal(LiteralType::Null) => Val::Null,68		Expr::Arr(n) => {69			if n.iter().any(|e| !is_trivial(e)) {70				return None;71			}72			Val::Arr(ArrValue::eager(73				n.iter()74					.map(|e| evaluate_trivial(&**e))75					.map(|e| e.expect("checked trivial"))76					.collect(),77			))78		}79		_ => return None,80	})81}8283pub fn evaluate_method(84	ctx: Context,85	name: IStr,86	params: ExprParams,87	body: Rc<Spanned<Expr>>,88) -> Val {89	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {90		name,91		ctx,92		params,93		body,94	})))95}9697pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {98	Ok(match field_name {99		FieldName::Fixed(n) => Some(n.clone()),100		FieldName::Dyn(expr) => in_frame(101			CallLocation::new(&expr.span()),102			|| "evaluating field name".to_string(),103			|| {104				let value = evaluate(ctx, expr)?;105				if matches!(value, Val::Null) {106					Ok(None)107				} else {108					Ok(Some(IStr::from_untyped(value)?))109				}110			},111		)?,112	})113}114115pub fn evaluate_comp(116	ctx: Context,117	specs: &[CompSpec],118	callback: &mut impl FnMut(Context) -> Result<()>,119) -> Result<()> {120	match specs.first() {121		None => callback(ctx)?,122		Some(CompSpec::IfSpec(IfSpecData(cond))) => {123			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {124				evaluate_comp(ctx, &specs[1..], callback)?;125			}126		}127		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {128			Val::Arr(list) => {129				for item in list.iter_lazy() {130					let fctx = Pending::new();131					let mut new_bindings = FxHashMap::with_capacity(var.binds_len());132					destruct(var, item, fctx.clone(), &mut new_bindings)?;133					let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);134135					evaluate_comp(ctx, &specs[1..], callback)?;136				}137			}138			#[cfg(feature = "exp-object-iteration")]139			Val::Obj(obj) => {140				for field in obj.fields(141					// TODO: Should there be ability to preserve iteration order?142					#[cfg(feature = "exp-preserve-order")]143					false,144				) {145					let fctx = Pending::new();146					let mut new_bindings = FxHashMap::with_capacity(var.binds_len());147					let obj = obj.clone();148					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![149						Thunk::evaluated(Val::string(field.clone())),150						Thunk!(move || obj.get(field).transpose().expect(151							"field exists, as field name was obtained from object.fields()",152						)),153					])));154					destruct(var, value, fctx.clone(), &mut new_bindings)?;155					let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);156157					evaluate_comp(ctx, &specs[1..], callback)?;158				}159			}160			_ => bail!(InComprehensionCanOnlyIterateOverArray),161		},162	}163	Ok(())164}165166trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}167impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}168169fn evaluate_object_locals(170	fctx: Context,171	locals: Rc<Vec<BindSpec>>,172) -> impl CloneableUnbound<Context> {173	#[derive(Trace, Clone)]174	struct UnboundLocals {175		fctx: Context,176		locals: Rc<Vec<BindSpec>>,177	}178	impl Unbound for UnboundLocals {179		type Bound = Context;180181		fn bind(&self, sup_this: SupThis) -> Result<Context> {182			let fctx = Context::new_future();183			let mut new_bindings =184				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());185			for b in self.locals.iter() {186				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;187			}188189			let ctx = self.fctx.clone();190191			let ctx = ctx192				.extend_bindings_sup_this(new_bindings, sup_this)193				.into_future(fctx);194195			Ok(ctx)196		}197	}198199	UnboundLocals { fctx, locals }200}201202pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(203	builder: &mut ObjValueBuilder,204	ctx: Context,205	uctx: B,206	field: &FieldMember,207) -> Result<()> {208	let name = evaluate_field_name(ctx, &field.name)?;209	let Some(name) = name else {210		return Ok(());211	};212213	match field {214		FieldMember {215			plus,216			params: None,217			visibility,218			value,219			..220		} => {221			#[derive(Trace)]222			struct UnboundValue<B: Trace> {223				uctx: B,224				value: Rc<Spanned<Expr>>,225				name: IStr,226			}227			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {228				type Bound = Val;229				fn bind(&self, sup_this: SupThis) -> Result<Val> {230					evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())231				}232			}233234			builder235				.field(name.clone())236				.with_add(*plus)237				.with_visibility(*visibility)238				.with_location(value.span())239				.bindable(UnboundValue {240					uctx,241					value: value.clone(),242					name,243				})?;244		}245		FieldMember {246			params: Some(params),247			visibility,248			value,249			..250		} => {251			#[derive(Trace)]252			struct UnboundMethod<B: Trace> {253				uctx: B,254				value: Rc<Spanned<Expr>>,255				params: ExprParams,256				name: IStr,257			}258			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {259				type Bound = Val;260				fn bind(&self, sup_this: SupThis) -> Result<Val> {261					Ok(evaluate_method(262						self.uctx.bind(sup_this)?,263						self.name.clone(),264						self.params.clone(),265						self.value.clone(),266					))267				}268			}269270			builder271				.field(name.clone())272				.with_visibility(*visibility)273				.with_location(value.span())274				.bindable(UnboundMethod {275					uctx,276					value: value.clone(),277					params: params.clone(),278					name,279				})?;280		}281	}282	Ok(())283}284285#[allow(clippy::too_many_lines)]286pub fn evaluate_member_list_object(ctx: Context, members: &ObjMembers) -> Result<ObjValue> {287	let mut builder = ObjValueBuilder::new();288	let locals = members.locals.clone();289290	// We have single context for all fields, so we can cache binds291	let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));292293	for field in &members.fields {294		evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;295	}296297	if !members.asserts.is_empty() {298		#[derive(Trace)]299		struct ObjectAssert<B: Trace> {300			uctx: B,301			asserts: Rc<Vec<AssertStmt>>,302		}303		impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {304			fn run(&self, sup_this: SupThis) -> Result<()> {305				let ctx = self.uctx.bind(sup_this)?;306				for assert in &*self.asserts {307					evaluate_assert(ctx.clone(), assert)?;308				}309				Ok(())310			}311		}312		builder.assert(ObjectAssert {313			uctx,314			asserts: members.asserts.clone(),315		});316	}317318	Ok(builder.build())319}320321pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {322	Ok(match object {323		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,324		ObjBody::ObjComp(obj) => {325			let mut builder = ObjValueBuilder::new();326			let locals = obj.locals.clone();327			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {328				let uctx = evaluate_object_locals(ctx.clone(), locals.clone());329330				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)331			})?;332333			builder.build()334		}335	})336}337338pub fn evaluate_apply(339	ctx: Context,340	value: &Spanned<Expr>,341	args: &ArgsDesc,342	loc: CallLocation<'_>,343	tailstrict: bool,344) -> Result<Val> {345	let value = evaluate(ctx.clone(), value)?;346	Ok(match value {347		Val::Func(f) => {348			let body = || f.evaluate(ctx, loc, args, tailstrict);349			if tailstrict {350				body()?351			} else {352				in_frame(loc, || format!("function <{}> call", f.name()), body)?353			}354		}355		v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),356	})357}358359pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {360	let value = &assertion.0;361	let msg = &assertion.1;362	let assertion_result = in_frame(363		CallLocation::new(&value.span()),364		|| "assertion condition".to_owned(),365		|| bool::from_untyped(evaluate(ctx.clone(), value)?),366	)?;367	if !assertion_result {368		in_frame(369			CallLocation::new(&value.span()),370			|| "assertion failure".to_owned(),371			|| {372				if let Some(msg) = msg {373					bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));374				}375				bail!(AssertionFailed(Val::Null.to_string()?));376			},377		)?;378	}379	Ok(())380}381382pub fn evaluate_named_param(ctx: Context, expr: &Spanned<Expr>, name: ParamName) -> Result<Val> {383	match name {384		ParamName::Named(name) => evaluate_named(ctx, expr, name),385		ParamName::Unnamed => evaluate(ctx, expr),386	}387}388389pub fn evaluate_named(ctx: Context, expr: &Spanned<Expr>, name: IStr) -> Result<Val> {390	use Expr::*;391	Ok(match &**expr {392		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),393		_ => evaluate(ctx, expr)?,394	})395}396397#[allow(clippy::too_many_lines)]398pub fn evaluate(ctx: Context, expr: &Expr) -> Result<Val> {399	use Expr::*;400401	if let Some(trivial) = evaluate_trivial(expr) {402		return Ok(trivial);403	}404	Ok(match expr {405		Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),406		Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),407		Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),408		Literal(LiteralType::True) => Val::Bool(true),409		Literal(LiteralType::False) => Val::Bool(false),410		Literal(LiteralType::Null) => Val::Null,411		Str(v) => Val::string(v.clone()),412		Num(v) => Val::try_num(*v)?,413		// I have tried to remove special behavior from super by implementing standalone-super414		// expresion, but looks like this case still needs special treatment.415		//416		// Note that other jsonnet implementations will fail on `if value in (super)` expression,417		// because the standalone super literal is not supported, that is because in other418		// implementations `in super` treated differently from `in smth_else`.419		BinaryOp(bin)420			if matches!(&*bin.rhs, Expr::Literal(LiteralType::Super))421				&& bin.op == BinaryOpType::In =>422		{423			let sup_this = ctx.try_sup_this()?;424			// In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.425			// In jrsonnet, however, this wasn't true, this was kept here for compatibility.426			if !sup_this.has_super() {427				return Ok(Val::Bool(false));428			}429			let field = evaluate(ctx, &bin.lhs)?;430			Val::Bool(sup_this.field_in_super(field.to_string()?))431		}432		BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,433		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,434		Var(name) => in_frame(435			CallLocation::new(&name.span()),436			|| format!("local <{name}> access"),437			|| ctx.binding((**name).clone())?.evaluate(),438		)?,439		Index { indexable, parts } => ensure_sufficient_stack(|| {440			let mut parts = parts.iter();441			let mut indexable = if matches!(&***indexable, Expr::Literal(LiteralType::Super)) {442				let part = parts.next().expect("at least part should exist");443				// sup_this existence check might also be skipped here for null-coalesce...444				// But I believe this might cause errors.445				let sup_this = ctx.try_sup_this()?;446				if !sup_this.has_super() {447					#[cfg(feature = "exp-null-coaelse")]448					if part.null_coaelse {449						return Ok(Val::Null);450					}451					bail!(NoSuperFound)452				}453				let name = evaluate(ctx.clone(), &part.value)?;454455				let Val::Str(name) = name else {456					bail!(ValueIndexMustBeTypeGot(457						ValType::Obj,458						ValType::Str,459						name.value_type(),460					))461				};462463				let name = name.into_flat();464				match sup_this465					.get_super(name.clone())466					.with_description_src(&part.value, || format!("field <{name}> access"))?467				{468					Some(v) => v,469					#[cfg(feature = "exp-null-coaelse")]470					None if part.null_coaelse => return Ok(Val::Null),471					None => {472						let suggestions = suggest_object_fields(473							&sup_this.standalone_super().expect("super exists"),474							name.clone(),475						);476477						bail!(NoSuchField(name, suggestions))478					}479				}480			} else {481				evaluate(ctx.clone(), indexable)?482			};483484			for part in parts {485				indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {486					(Val::Obj(v), Val::Str(key)) => match v487						.get(key.clone().into_flat())488						.with_description_src(&part.value, || format!("field <{key}> access"))?489					{490						Some(v) => v,491						#[cfg(feature = "exp-null-coaelse")]492						None if part.null_coaelse => return Ok(Val::Null),493						None => {494							let suggestions = suggest_object_fields(&v, key.clone().into_flat());495496							return Err(Error::from(NoSuchField(497								key.clone().into_flat(),498								suggestions,499							)))500							.with_description_src(&part.value, || format!("field <{key}> access"));501						}502					},503					(Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(504						ValType::Obj,505						ValType::Str,506						n.value_type(),507					)),508					(Val::Arr(v), Val::Num(n)) => {509						let n = n.get();510						if n.fract() > f64::EPSILON {511							bail!(FractionalIndex)512						}513						if n < 0.0 {514							bail!(ArrayBoundsError(n as isize, v.len()));515						}516						v.get(n as usize)?517							.ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?518					}519					(Val::Arr(_), Val::Str(n)) => {520						bail!(AttemptedIndexAnArrayWithString(n.into_flat()))521					}522					(Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(523						ValType::Arr,524						ValType::Num,525						n.value_type(),526					)),527528					(Val::Str(s), Val::Num(n)) => Val::Str({529						let n = n.get();530						if n.fract() > f64::EPSILON {531							bail!(FractionalIndex)532						}533						if n < 0.0 {534							bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));535						}536						let v: IStr = s537							.clone()538							.into_flat()539							.chars()540							.skip(n as usize)541							.take(1)542							.collect::<String>()543							.into();544						if v.is_empty() {545							bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))546						}547						StrValue::Flat(v)548					}),549					(Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(550						ValType::Str,551						ValType::Num,552						n.value_type(),553					)),554					#[cfg(feature = "exp-null-coaelse")]555					(Val::Null, _) if part.null_coaelse => return Ok(Val::Null),556					(v, _) => bail!(CantIndexInto(v.value_type())),557				};558			}559			Ok(indexable)560		})?,561		LocalExpr(bindings, returned) => {562			let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =563				FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());564			let fctx = Context::new_future();565			for b in bindings {566				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;567			}568			let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);569			evaluate(ctx, returned)?570		}571		Arr(items) => {572			if items.is_empty() {573				Val::Arr(ArrValue::empty())574			} else {575				Val::Arr(ArrValue::expr(ctx, items.clone()))576			}577		}578		ArrComp(expr, comp_specs) => {579			let mut out = Vec::new();580			evaluate_comp(ctx, comp_specs, &mut |ctx| {581				let expr = expr.clone();582				out.push(Thunk!(move || evaluate(ctx, &expr)));583				Ok(())584			})?;585			Val::Arr(ArrValue::lazy(out))586		}587		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),588		ObjExtend(a, b) => evaluate_add_op(589			&evaluate(ctx.clone(), a)?,590			&Val::Obj(evaluate_object(ctx, b)?),591		)?,592		Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {593			evaluate_apply(594				ctx,595				value,596				args,597				CallLocation::new(&args.span()),598				*tailstrict,599			)600		})?,601		Function(params, body) => {602			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())603		}604		AssertExpr(assert) => {605			evaluate_assert(ctx.clone(), &assert.assert)?;606			evaluate(ctx, &assert.rest)?607		}608		ErrorStmt(e) => in_frame(609			CallLocation::new(&e.span()),610			|| "error statement".to_owned(),611			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),612		)?,613		IfElse(if_else) => {614			if in_frame(615				CallLocation::new(&if_else.cond.0.span()),616				|| "if condition".to_owned(),617				|| bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.0)?),618			)? {619				evaluate(ctx, &if_else.cond_then)?620			} else {621				match &if_else.cond_else {622					Some(v) => evaluate(ctx, v)?,623					None => Val::Null,624				}625			}626		}627		Slice(slice) => {628			fn parse_idx<T: Typed + FromUntyped>(629				loc: CallLocation<'_>,630				ctx: Context,631				expr: Option<&Spanned<Expr>>,632				desc: &'static str,633			) -> Result<Option<T>> {634				if let Some(value) = expr {635					Ok(in_frame(636						loc,637						|| format!("slice {desc}"),638						|| <Option<T>>::from_untyped(evaluate(ctx, value)?),639					)?)640				} else {641					Ok(None)642				}643			}644645			let indexable = evaluate(ctx.clone(), &slice.value)?;646			let loc = CallLocation::new(&loc);647648			let start = parse_idx(loc, ctx.clone(), slice.slice.start.as_ref(), "start")?;649			let end = parse_idx(loc, ctx.clone(), slice.slice.end.as_ref(), "end")?;650			let step = parse_idx(loc, ctx, slice.slice.step.as_ref(), "step")?;651652			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?653		}654		Import(kind, path) => {655			let Expr::Str(path) = &***path else {656				bail!("computed imports are not supported")657			};658			let tmp = loc.clone().0;659			with_state(|s| {660				let resolved_path = s.resolve_from(tmp.source_path(), path)?;661				Ok(match kind {662					ImportKind::Normal => in_frame(663						CallLocation::new(&loc),664						|| format!("import {:?}", path.clone()),665						|| s.import_resolved(resolved_path),666					)?,667					ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),668					ImportKind::Bin => {669						Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))670					}671				}) as Result<Val>672			})?673		}674	})675}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6	function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,7	FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,8	Spanned,9};10use jrsonnet_types::ValType;11use rustc_hash::FxHashMap;1213use self::destructure::destruct;14use crate::{15	arr::ArrValue,16	bail,17	destructure::evaluate_dest,18	error::{suggest_object_fields, ErrorKind::*},19	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},20	function::{CallLocation, FuncDesc, FuncVal},21	gc::WithCapacityExt as _,22	in_frame,23	typed::{FromUntyped, IntoUntyped as _, Typed},24	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25	with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,26	ResultExt, SupThis, Unbound, Val,27};28pub mod destructure;29pub mod operator;3031// This is the amount of bytes that need to be left on the stack before increasing the size.32// It must be at least as large as the stack required by any code that does not call33// `ensure_sufficient_stack`.34const RED_ZONE: usize = 100 * 1024; // 100k3536// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then37// on. This flag has performance relevant characteristics. Don't set it too high.38const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3940/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations41/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit42/// from this.43///44/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.45#[inline]46pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {47	stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)48}4950pub fn evaluate_trivial(expr: &Expr) -> Option<Val> {51	fn is_trivial(expr: &Expr) -> bool {52		match &*expr {53			Expr::Str(_)54			| Expr::Num(_)55			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,56			Expr::Arr(a) => a.iter().all(|e| is_trivial(&*e)),57			_ => false,58		}59	}60	Some(match &*expr {61		Expr::Str(s) => Val::string(s.clone()),62		Expr::Num(n) => {63			Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64		}65		Expr::Literal(LiteralType::False) => Val::Bool(false),66		Expr::Literal(LiteralType::True) => Val::Bool(true),67		Expr::Literal(LiteralType::Null) => Val::Null,68		Expr::Arr(n) => {69			if n.iter().any(|e| !is_trivial(e)) {70				return None;71			}72			Val::Arr(ArrValue::eager(73				n.iter()74					.map(|e| evaluate_trivial(&*e))75					.map(|e| e.expect("checked trivial"))76					.collect(),77			))78		}79		_ => return None,80	})81}8283pub fn evaluate_method(ctx: Context, name: IStr, params: ExprParams, body: Rc<Expr>) -> Val {84	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {85		name,86		ctx,87		params,88		body,89	})))90}9192pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {93	Ok(match field_name {94		FieldName::Fixed(n) => Some(n.clone()),95		FieldName::Dyn(expr) => {96			// FIXME: Span97			let value = evaluate(ctx, expr)?;98			if matches!(value, Val::Null) {99				None100			} else {101				Some(IStr::from_untyped(value)?)102			}103		} //104		  // 	in_frame(105		  // 	CallLocation::new(&expr.span()),106		  // 	|| "evaluating field name".to_string(),107		  // 	|| {108		  // 	},109		  // )?,110	})111}112113pub fn evaluate_comp(114	ctx: Context,115	specs: &[CompSpec],116	callback: &mut impl FnMut(Context) -> Result<()>,117) -> Result<()> {118	match specs.first() {119		None => callback(ctx)?,120		Some(CompSpec::IfSpec(Spanned(IfSpecData(cond), _))) => {121			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {122				evaluate_comp(ctx, &specs[1..], callback)?;123			}124		}125		Some(CompSpec::ForSpec(Spanned(ForSpecData(var, expr), _))) => {126			match evaluate(ctx.clone(), expr)? {127				Val::Arr(list) => {128					for item in list.iter_lazy() {129						let fctx = Pending::new();130						let mut new_bindings = FxHashMap::with_capacity(var.binds_len());131						destruct(var, item, fctx.clone(), &mut new_bindings)?;132						let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);133134						evaluate_comp(ctx, &specs[1..], callback)?;135					}136				}137				#[cfg(feature = "exp-object-iteration")]138				Val::Obj(obj) => {139					for field in obj.fields(140						// TODO: Should there be ability to preserve iteration order?141						#[cfg(feature = "exp-preserve-order")]142						false,143					) {144						let fctx = Pending::new();145						let mut new_bindings = FxHashMap::with_capacity(var.binds_len());146						let obj = obj.clone();147						let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![148							Thunk::evaluated(Val::string(field.clone())),149							Thunk!(move || obj.get(field).transpose().expect(150								"field exists, as field name was obtained from object.fields()",151							)),152						])));153						destruct(var, value, fctx.clone(), &mut new_bindings)?;154						let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);155156						evaluate_comp(ctx, &specs[1..], callback)?;157					}158				}159				_ => bail!(InComprehensionCanOnlyIterateOverArray),160			}161		}162	}163	Ok(())164}165166trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}167impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}168169fn evaluate_object_locals(170	fctx: Context,171	locals: Rc<Vec<BindSpec>>,172) -> impl CloneableUnbound<Context> {173	#[derive(Trace, Clone)]174	struct UnboundLocals {175		fctx: Context,176		locals: Rc<Vec<BindSpec>>,177	}178	impl Unbound for UnboundLocals {179		type Bound = Context;180181		fn bind(&self, sup_this: SupThis) -> Result<Context> {182			let fctx = Context::new_future();183			let mut new_bindings =184				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());185			for b in self.locals.iter() {186				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;187			}188189			let ctx = self.fctx.clone();190191			let ctx = ctx192				.extend_bindings_sup_this(new_bindings, sup_this)193				.into_future(fctx);194195			Ok(ctx)196		}197	}198199	UnboundLocals { fctx, locals }200}201202pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(203	builder: &mut ObjValueBuilder,204	ctx: Context,205	uctx: B,206	field: &FieldMember,207) -> Result<()> {208	let name = evaluate_field_name(ctx, &field.name)?;209	let Some(name) = name else {210		return Ok(());211	};212213	match field {214		FieldMember {215			plus,216			params: None,217			visibility,218			value,219			..220		} => {221			#[derive(Trace)]222			struct UnboundValue<B: Trace> {223				uctx: B,224				value: Rc<Expr>,225				name: IStr,226			}227			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {228				type Bound = Val;229				fn bind(&self, sup_this: SupThis) -> Result<Val> {230					evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())231				}232			}233234			builder235				.field(name.clone())236				.with_add(*plus)237				.with_visibility(*visibility)238				// FIXME239				// .with_location(value.span())240				.bindable(UnboundValue {241					uctx,242					value: value.clone(),243					name,244				})?;245		}246		FieldMember {247			params: Some(params),248			visibility,249			value,250			..251		} => {252			#[derive(Trace)]253			struct UnboundMethod<B: Trace> {254				uctx: B,255				value: Rc<Expr>,256				params: ExprParams,257				name: IStr,258			}259			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {260				type Bound = Val;261				fn bind(&self, sup_this: SupThis) -> Result<Val> {262					Ok(evaluate_method(263						self.uctx.bind(sup_this)?,264						self.name.clone(),265						self.params.clone(),266						self.value.clone(),267					))268				}269			}270271			builder272				.field(name.clone())273				.with_visibility(*visibility)274				// .with_location(value.span())275				.bindable(UnboundMethod {276					uctx,277					value: value.clone(),278					params: params.clone(),279					name,280				})?;281		}282	}283	Ok(())284}285286#[allow(clippy::too_many_lines)]287pub fn evaluate_member_list_object(ctx: Context, members: &ObjMembers) -> Result<ObjValue> {288	let mut builder = ObjValueBuilder::new();289	let locals = members.locals.clone();290291	// We have single context for all fields, so we can cache binds292	let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));293294	for field in &members.fields {295		evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;296	}297298	if !members.asserts.is_empty() {299		#[derive(Trace)]300		struct ObjectAssert<B: Trace> {301			uctx: B,302			asserts: Rc<Vec<AssertStmt>>,303		}304		impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {305			fn run(&self, sup_this: SupThis) -> Result<()> {306				let ctx = self.uctx.bind(sup_this)?;307				for assert in &*self.asserts {308					evaluate_assert(ctx.clone(), assert)?;309				}310				Ok(())311			}312		}313		builder.assert(ObjectAssert {314			uctx,315			asserts: members.asserts.clone(),316		});317	}318319	Ok(builder.build())320}321322pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {323	Ok(match object {324		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,325		ObjBody::ObjComp(obj) => {326			let mut builder = ObjValueBuilder::new();327			let locals = obj.locals.clone();328			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {329				let uctx = evaluate_object_locals(ctx.clone(), locals.clone());330331				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)332			})?;333334			builder.build()335		}336	})337}338339pub fn evaluate_apply(340	ctx: Context,341	value: &Expr,342	args: &ArgsDesc,343	loc: CallLocation<'_>,344	tailstrict: bool,345) -> Result<Val> {346	let value = evaluate(ctx.clone(), value)?;347	Ok(match value {348		Val::Func(f) => {349			let body = || f.evaluate(ctx, loc, args, tailstrict);350			if tailstrict {351				body()?352			} else {353				in_frame(loc, || format!("function <{}> call", f.name()), body)?354			}355		}356		v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),357	})358}359360pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {361	let value = &assertion.0;362	let msg = &assertion.1;363	let assertion_result = in_frame(364		CallLocation::new(&value.span()),365		|| "assertion condition".to_owned(),366		|| bool::from_untyped(evaluate(ctx.clone(), value)?),367	)?;368	if !assertion_result {369		in_frame(370			CallLocation::new(&value.span()),371			|| "assertion failure".to_owned(),372			|| {373				if let Some(msg) = msg {374					bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));375				}376				bail!(AssertionFailed(Val::Null.to_string()?));377			},378		)?;379	}380	Ok(())381}382383pub fn evaluate_named_param(ctx: Context, expr: &Expr, name: ParamName) -> Result<Val> {384	match name {385		ParamName::Named(name) => evaluate_named(ctx, expr, name),386		ParamName::Unnamed => evaluate(ctx, expr),387	}388}389390pub fn evaluate_named(ctx: Context, expr: &Expr, name: IStr) -> Result<Val> {391	use Expr::*;392	Ok(match &*expr {393		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),394		_ => evaluate(ctx, expr)?,395	})396}397398#[allow(clippy::too_many_lines)]399pub fn evaluate(ctx: Context, expr: &Expr) -> Result<Val> {400	use Expr::*;401402	if let Some(trivial) = evaluate_trivial(expr) {403		return Ok(trivial);404	}405	Ok(match expr {406		Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),407		Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),408		Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),409		Literal(LiteralType::True) => Val::Bool(true),410		Literal(LiteralType::False) => Val::Bool(false),411		Literal(LiteralType::Null) => Val::Null,412		Str(v) => Val::string(v.clone()),413		Num(v) => Val::try_num(*v)?,414		// I have tried to remove special behavior from super by implementing standalone-super415		// expresion, but looks like this case still needs special treatment.416		//417		// Note that other jsonnet implementations will fail on `if value in (super)` expression,418		// because the standalone super literal is not supported, that is because in other419		// implementations `in super` treated differently from `in smth_else`.420		BinaryOp(bin)421			if matches!(&bin.rhs, Expr::Literal(LiteralType::Super))422				&& bin.op == BinaryOpType::In =>423		{424			let sup_this = ctx.try_sup_this()?;425			// In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.426			// In jrsonnet, however, this wasn't true, this was kept here for compatibility.427			if !sup_this.has_super() {428				return Ok(Val::Bool(false));429			}430			let field = evaluate(ctx, &bin.lhs)?;431			Val::Bool(sup_this.field_in_super(field.to_string()?))432		}433		BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,434		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,435		Var(name) => in_frame(436			CallLocation::new(&name.span()),437			|| format!("local <{}> access", &**name),438			|| ctx.binding((**name).clone())?.evaluate(),439		)?,440		Index { indexable, parts } => ensure_sufficient_stack(|| {441			let mut parts = parts.iter();442			let mut indexable = if matches!(&**indexable, Expr::Literal(LiteralType::Super)) {443				let part = parts.next().expect("at least part should exist");444				// sup_this existence check might also be skipped here for null-coalesce...445				// But I believe this might cause errors.446				let sup_this = ctx.try_sup_this()?;447				if !sup_this.has_super() {448					#[cfg(feature = "exp-null-coaelse")]449					if part.null_coaelse {450						return Ok(Val::Null);451					}452					bail!(NoSuperFound)453				}454				let name = evaluate(ctx.clone(), &part.value)?;455456				let Val::Str(name) = name else {457					bail!(ValueIndexMustBeTypeGot(458						ValType::Obj,459						ValType::Str,460						name.value_type(),461					))462				};463464				let name = name.into_flat();465				match sup_this466					.get_super(name.clone())467					.with_description_src(&part.span, || format!("field <{name}> access"))?468				{469					Some(v) => v,470					#[cfg(feature = "exp-null-coaelse")]471					None if part.null_coaelse => return Ok(Val::Null),472					None => {473						let suggestions = suggest_object_fields(474							&sup_this.standalone_super().expect("super exists"),475							name.clone(),476						);477478						bail!(NoSuchField(name, suggestions))479					}480				}481			} else {482				evaluate(ctx.clone(), indexable)?483			};484485			for part in parts {486				indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {487					(Val::Obj(v), Val::Str(key)) => match v488						.get(key.clone().into_flat())489						.with_description_src(&part.span, || format!("field <{key}> access"))?490					{491						Some(v) => v,492						#[cfg(feature = "exp-null-coaelse")]493						None if part.null_coaelse => return Ok(Val::Null),494						None => {495							let suggestions = suggest_object_fields(&v, key.clone().into_flat());496497							return Err(Error::from(NoSuchField(498								key.clone().into_flat(),499								suggestions,500							)))501							.with_description_src(&part.span, || format!("field <{key}> access"));502						}503					},504					(Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(505						ValType::Obj,506						ValType::Str,507						n.value_type(),508					)),509					(Val::Arr(v), Val::Num(n)) => {510						let n = n.get();511						if n.fract() > f64::EPSILON {512							bail!(FractionalIndex)513						}514						if n < 0.0 {515							bail!(ArrayBoundsError(n as isize, v.len()));516						}517						v.get(n as usize)?518							.ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?519					}520					(Val::Arr(_), Val::Str(n)) => {521						bail!(AttemptedIndexAnArrayWithString(n.into_flat()))522					}523					(Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(524						ValType::Arr,525						ValType::Num,526						n.value_type(),527					)),528529					(Val::Str(s), Val::Num(n)) => Val::Str({530						let n = n.get();531						if n.fract() > f64::EPSILON {532							bail!(FractionalIndex)533						}534						if n < 0.0 {535							bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));536						}537						let v: IStr = s538							.clone()539							.into_flat()540							.chars()541							.skip(n as usize)542							.take(1)543							.collect::<String>()544							.into();545						if v.is_empty() {546							bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))547						}548						StrValue::Flat(v)549					}),550					(Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(551						ValType::Str,552						ValType::Num,553						n.value_type(),554					)),555					#[cfg(feature = "exp-null-coaelse")]556					(Val::Null, _) if part.null_coaelse => return Ok(Val::Null),557					(v, _) => bail!(CantIndexInto(v.value_type())),558				};559			}560			Ok(indexable)561		})?,562		LocalExpr(bindings, returned) => {563			let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =564				FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());565			let fctx = Context::new_future();566			for b in bindings {567				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;568			}569			let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);570			evaluate(ctx, returned)?571		}572		Arr(items) => {573			if items.is_empty() {574				Val::Arr(ArrValue::empty())575			} else {576				Val::Arr(ArrValue::expr(ctx, items.clone()))577			}578		}579		ArrComp(expr, comp_specs) => {580			let mut out = Vec::new();581			evaluate_comp(ctx, comp_specs, &mut |ctx| {582				let expr = expr.clone();583				out.push(Thunk!(move || evaluate(ctx, &expr)));584				Ok(())585			})?;586			Val::Arr(ArrValue::lazy(out))587		}588		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),589		ObjExtend(a, b) => evaluate_add_op(590			&evaluate(ctx.clone(), a)?,591			&Val::Obj(evaluate_object(ctx, b)?),592		)?,593		Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {594			evaluate_apply(595				ctx,596				value,597				args,598				CallLocation::new(&args.span()),599				*tailstrict,600			)601		})?,602		Function(params, body) => {603			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())604		}605		AssertExpr(assert) => {606			evaluate_assert(ctx.clone(), &assert.assert)?;607			evaluate(ctx, &assert.rest)?608		}609		ErrorStmt(s, e) => in_frame(610			CallLocation::new(&s),611			|| "error statement".to_owned(),612			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),613		)?,614		IfElse(if_else) => {615			if616			// FIXME617			//in_frame(618			// CallLocation::new(&if_else.cond.0.span()),619			// || "if condition".to_owned(),620			// ||621			bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.0)?)?622			// )?623			{624				evaluate(ctx, &if_else.cond_then)?625			} else {626				match &if_else.cond_else {627					Some(v) => evaluate(ctx, v)?,628					None => Val::Null,629				}630			}631		}632		Slice(slice) => {633			fn parse_idx<T: Typed + FromUntyped>(634				ctx: Context,635				expr: Option<&Spanned<Expr>>,636				desc: &'static str,637			) -> Result<Option<T>> {638				if let Some(value) = expr {639					Ok(in_frame(640						CallLocation::new(&value.span()),641						|| format!("slice {desc}"),642						|| <Option<T>>::from_untyped(evaluate(ctx, value)?),643					)?)644				} else {645					Ok(None)646				}647			}648649			let indexable = evaluate(ctx.clone(), &slice.value)?;650651			let start = parse_idx(ctx.clone(), slice.slice.start.as_ref(), "start")?;652			let end = parse_idx(ctx.clone(), slice.slice.end.as_ref(), "end")?;653			let step = parse_idx(ctx, slice.slice.step.as_ref(), "step")?;654655			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?656		}657		Import(kind, path) => {658			let Expr::Str(path) = &**path else {659				bail!("computed imports are not supported")660			};661			with_state(|s| {662				let span = kind.span();663				let resolved_path = s.resolve_from(span.0.source_path(), path)?;664				Ok(match &**kind {665					ImportKind::Normal => in_frame(666						CallLocation::new(&span),667						|| format!("import {:?}", path.clone()),668						|| s.import_resolved(resolved_path),669					)?,670					ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),671					ImportKind::Bin => {672						Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))673					}674				}) as Result<Val>675			})?676		}677	})678}
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -147,9 +147,9 @@
 
 pub fn evaluate_binary_op_special(
 	ctx: Context,
-	a: &Spanned<Expr>,
+	a: &Expr,
 	op: BinaryOpType,
-	b: &Spanned<Expr>,
+	b: &Expr,
 ) -> Result<Val> {
 	use BinaryOpType::*;
 	use Val::*;
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -3,8 +3,8 @@
 use educe::Educe;
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
+use jrsonnet_ir::{ArgsDesc, Destruct, Expr, ExprParams, Span, Spanned};
 pub use jrsonnet_macros::builtin;
-use jrsonnet_ir::{ArgsDesc, Destruct, Expr, ExprParams, Span, Spanned};
 
 use self::{
 	builtin::{Builtin, StaticBuiltin},
@@ -71,7 +71,7 @@
 	/// Function parameter definition
 	pub params: ExprParams,
 	/// Function body
-	pub body: Rc<Spanned<Expr>>,
+	pub body: Rc<Expr>,
 }
 impl FuncDesc {
 	/// Create body context, but fill arguments without defaults with lazy error
@@ -256,7 +256,7 @@
 					#[cfg(feature = "exp-destruct")]
 					_ => return false,
 				};
-				**desc.body == Expr::Var(id.clone())
+				matches!(&*desc.body, Expr::Var(v) if &**v == id)
 			}
 			_ => false,
 		}
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -2,7 +2,7 @@
 
 use jrsonnet_ir::{
 	function::{FunctionSignature, ParamName},
-	ArgsDesc, Expr, ExprParams, Spanned,
+	ArgsDesc, Expr, ExprParams,
 };
 use rustc_hash::FxHashMap;
 
@@ -15,7 +15,7 @@
 	Context, Pending, Thunk, Val,
 };
 
-fn eval_arg(ctx: Context, arg: &Rc<Spanned<Expr>>, tailstrict: bool) -> Result<Thunk<Val>> {
+fn eval_arg(ctx: Context, arg: &Rc<Expr>, tailstrict: bool) -> Result<Thunk<Val>> {
 	if tailstrict {
 		Ok(Thunk::evaluated(evaluate(ctx, arg)?))
 	} else {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -5,7 +5,7 @@
 extern crate self as jrsonnet_evaluator;
 
 mod arr;
-pub mod async_import;
+// pub mod async_import;
 mod ctx;
 mod dynamic;
 pub mod error;
@@ -187,7 +187,7 @@
 struct FileData {
 	string: Option<IStr>,
 	bytes: Option<IBytes>,
-	parsed: Option<Rc<Spanned<Expr>>>,
+	parsed: Option<Rc<Expr>>,
 	evaluated: Option<Val>,
 
 	evaluating: bool,
modifiedcrates/jrsonnet-ir/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir/src/expr.rs
+++ b/crates/jrsonnet-ir/src/expr.rs
@@ -17,7 +17,7 @@
 	/// {fixed: 2}
 	Fixed(IStr),
 	/// {["dyn"+"amic"]: 3}
-	Dyn(Spanned<Expr>),
+	Dyn(Expr),
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]
@@ -46,7 +46,7 @@
 	pub plus: bool,
 	pub params: Option<ExprParams>,
 	pub visibility: Visibility,
-	pub value: Rc<Spanned<Expr>>,
+	pub value: Rc<Expr>,
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
@@ -152,7 +152,7 @@
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct ExprParam {
 	pub destruct: Destruct,
-	pub default: Option<Rc<Spanned<Expr>>>,
+	pub default: Option<Rc<Expr>>,
 }
 
 /// Defined function parameters
@@ -194,11 +194,11 @@
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct ArgsDesc {
-	pub unnamed: Vec<Rc<Spanned<Expr>>>,
-	pub named: Vec<(IStr, Rc<Spanned<Expr>>)>,
+	pub unnamed: Vec<Rc<Expr>>,
+	pub named: Vec<(IStr, Rc<Expr>)>,
 }
 impl ArgsDesc {
-	pub fn new(unnamed: Vec<Rc<Spanned<Expr>>>, named: Vec<(IStr, Rc<Spanned<Expr>>)>) -> Self {
+	pub fn new(unnamed: Vec<Rc<Expr>>, named: Vec<(IStr, Rc<Expr>)>) -> Self {
 		Self { unnamed, named }
 	}
 }
@@ -277,12 +277,12 @@
 pub enum BindSpec {
 	Field {
 		into: Destruct,
-		value: Rc<Spanned<Expr>>,
+		value: Rc<Expr>,
 	},
 	Function {
 		name: IStr,
 		params: ExprParams,
-		value: Rc<Spanned<Expr>>,
+		value: Rc<Expr>,
 	},
 }
 impl BindSpec {
@@ -295,15 +295,15 @@
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
-pub struct IfSpecData(pub Spanned<Expr>);
+pub struct IfSpecData(pub Expr);
 
 #[derive(Debug, PartialEq, Acyclic)]
-pub struct ForSpecData(pub Destruct, pub Spanned<Expr>);
+pub struct ForSpecData(pub Destruct, pub Expr);
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub enum CompSpec {
-	IfSpec(IfSpecData),
-	ForSpec(ForSpecData),
+	IfSpec(Spanned<IfSpecData>),
+	ForSpec(Spanned<ForSpecData>),
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
@@ -346,14 +346,14 @@
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct AssertExpr {
 	pub assert: AssertStmt,
-	pub rest: Spanned<Expr>,
+	pub rest: Expr,
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct BinaryOp {
-	pub lhs: Spanned<Expr>,
+	pub lhs: Expr,
 	pub op: BinaryOpType,
-	pub rhs: Spanned<Expr>,
+	pub rhs: Expr,
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
@@ -366,13 +366,13 @@
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct IfElse {
 	pub cond: IfSpecData,
-	pub cond_then: Spanned<Expr>,
-	pub cond_else: Option<Spanned<Expr>>,
+	pub cond_then: Expr,
+	pub cond_else: Option<Expr>,
 }
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct Slice {
-	pub value: Spanned<Expr>,
+	pub value: Expr,
 	pub slice: SliceDesc,
 }
 
@@ -389,7 +389,7 @@
 	Var(Spanned<IStr>),
 
 	/// Array of expressions: [1, 2, "Hello"]
-	Arr(Rc<Vec<Spanned<Expr>>>),
+	Arr(Rc<Vec<Expr>>),
 	/// Array comprehension:
 	/// ```jsonnet
 	///  ingredients: [
@@ -401,35 +401,35 @@
 	///    ]
 	///  ],
 	/// ```
-	ArrComp(Rc<Spanned<Expr>>, Vec<CompSpec>),
+	ArrComp(Rc<Expr>, Vec<CompSpec>),
 
 	/// Object: {a: 2}
 	Obj(ObjBody),
 	/// Object extension: var1 {b: 2}
-	ObjExtend(Rc<Spanned<Expr>>, ObjBody),
+	ObjExtend(Rc<Expr>, ObjBody),
 
 	/// -2
-	UnaryOp(UnaryOpType, Box<Spanned<Expr>>),
+	UnaryOp(UnaryOpType, Box<Expr>),
 	/// 2 - 2
 	BinaryOp(Box<BinaryOp>),
 	/// assert 2 == 2 : "Math is broken"
 	AssertExpr(Rc<AssertExpr>),
 	/// local a = 2; { b: a }
-	LocalExpr(Vec<BindSpec>, Box<Spanned<Expr>>),
+	LocalExpr(Vec<BindSpec>, Box<Expr>),
 
 	/// import* "hello"
-	Import(ImportKind, Box<Spanned<Expr>>),
+	Import(Spanned<ImportKind>, Box<Expr>),
 	/// error "I'm broken"
-	ErrorStmt(Box<Spanned<Expr>>),
+	ErrorStmt(Span, Box<Expr>),
 	/// a(b, c)
-	Apply(Box<Spanned<Expr>>, Spanned<ArgsDesc>, bool),
+	Apply(Box<Expr>, Spanned<ArgsDesc>, bool),
 	/// a[b], a.b, a?.b
 	Index {
-		indexable: Box<Spanned<Expr>>,
+		indexable: Box<Expr>,
 		parts: Vec<IndexPart>,
 	},
 	/// function(x) x
-	Function(ExprParams, Rc<Spanned<Expr>>),
+	Function(ExprParams, Rc<Expr>),
 	/// if true == false then 1 else 2
 	IfElse(Box<IfElse>),
 	Slice(Box<Slice>),
@@ -437,7 +437,8 @@
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub struct IndexPart {
-	pub value: Spanned<Expr>,
+	pub span: Span,
+	pub value: Expr,
 	#[cfg(feature = "exp-null-coaelse")]
 	pub null_coaelse: bool,
 }
@@ -461,7 +462,7 @@
 }
 
 #[derive(Clone, PartialEq, Acyclic)]
-pub struct Spanned<T: Acyclic>(T, Span);
+pub struct Spanned<T: Acyclic>(pub T, pub Span);
 impl<T: Acyclic> Deref for Spanned<T> {
 	type Target = T;
 	fn deref(&self) -> &Self::Target {
modifiedcrates/jrsonnet-peg-parser/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-peg-parser/Cargo.toml
+++ b/crates/jrsonnet-peg-parser/Cargo.toml
@@ -7,6 +7,7 @@
 version.workspace = true
 
 [dependencies]
+jrsonnet-gcmodule.workspace = true
 jrsonnet-ir.workspace = true
 peg.workspace = true
 
modifiedcrates/jrsonnet-peg-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-peg-parser/src/lib.rs
+++ b/crates/jrsonnet-peg-parser/src/lib.rs
@@ -1,7 +1,9 @@
+use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_ir::{
-	BinaryOp, Expr, ExprParams, IStr, IndexPart, Member, Slice, SliceDesc, Source, Span, Spanned,
-	ExprParam, ArgsDesc, AssertExpr, ImportKind, LiteralType, IfElse, CompSpec, ForSpecData, IfSpecData, ObjMembers, ObjBody,
-	ObjComp, FieldMember, Visibility, FieldName, unescape, AssertStmt, BindSpec, Destruct, DestructRest,
+	unescape, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BindSpec, CompSpec, Destruct,
+	DestructRest, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse,
+	IfSpecData, ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice,
+	SliceDesc, Source, Span, Spanned, Visibility,
 };
 use peg::parser;
 use std::rc::Rc;
@@ -63,7 +65,7 @@
 			= params:param(s) ** comma() comma()? { ExprParams::new(params) }
 			/ { ExprParams::new(Vec::new()) }
 
-		pub rule arg(s: &ParserSettings) -> (Option<IStr>, Rc<Spanned<Expr>>)
+		pub rule arg(s: &ParserSettings) -> (Option<IStr>, Rc<Expr>)
 			= name:(quiet! { (s:id() _ "=" !['='] _ {s})? } / expected!("<argument name>")) expr:expr(s) {(name, Rc::new(expr))}
 
 		pub rule args(s: &ParserSettings) -> ArgsDesc
@@ -133,7 +135,7 @@
 			/ name:id() _ "(" _ params:params(s) _ ")" _ "=" _ value:expr(s) {BindSpec::Function{name, params, value: Rc::new(value)}}
 
 		pub rule assertion(s: &ParserSettings) -> AssertStmt
-			= keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { AssertStmt(cond, msg) }
+			= keyword("assert") _ cond:spanned(<expr(s)>, s) msg:(_ ":" _ e:spanned(<expr(s)>, s) {e})? { AssertStmt(cond, msg) }
 
 		pub rule whole_line() -> &'input str
 			= str:$((!['\n'][_])* "\n") {str}
@@ -241,7 +243,7 @@
 		pub rule forspec(s: &ParserSettings) -> ForSpecData
 			= keyword("for") _ id:destruct(s) _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}
 		rule compspec(s: &ParserSettings) -> CompSpec
-			= i:ifspec(s) { CompSpec::IfSpec(i) } / f:forspec(s) {CompSpec::ForSpec(f)}
+			= i:spanned(<ifspec(s)>, s) { CompSpec::IfSpec(i) } / f:spanned(<forspec(s)>, s) {CompSpec::ForSpec(f)}
 		pub rule compspecs(s: &ParserSettings) -> Vec<CompSpec>
 			= specs:compspec(s) ++ _ {?
 				if !matches!(specs[0], CompSpec::ForSpec(_)) {
@@ -267,8 +269,12 @@
 			} else {
 				Err("!!!numbers are finite")
 			}}
+
+		rule spanned<T: Acyclic>(x: rule<T>, s: &ParserSettings) -> Spanned<T>
+			= a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), a as u32, b as u32)) }
+
 		pub rule var_expr(s: &ParserSettings) -> Expr
-			= n:id() { Expr::Var(n) }
+			= n:spanned(<id()>, s) { Expr::Var(n) }
 		pub rule id_loc(s: &ParserSettings) -> Spanned<Expr>
 			= a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
 		pub rule if_then_else_expr(s: &ParserSettings) -> Expr
@@ -302,7 +308,7 @@
 			/ array_expr(s)
 			/ array_comp_expr(s)
 
-			/ kind:import_kind() _ path:expr(s) {Expr::Import(kind, Box::new(path))}
+			/ kind:spanned(<import_kind()>, s) _ path:expr(s) {Expr::Import(kind, Box::new(path))}
 
 			/ var_expr(s)
 			/ local_expr(s)
@@ -313,10 +319,10 @@
 				assert, rest
 			})) }
 
-			/ keyword("error") _ expr:expr(s) { Expr::ErrorStmt(Box::new(expr)) }
+			/ err_kw:spanned(<keyword("error")>, s) _ expr:expr(s) { Expr::ErrorStmt(err_kw.1, Box::new(expr)) }
 
 		rule slice_part(s: &ParserSettings) -> Option<Spanned<Expr>>
-			= _ e:(e:expr(s) _{e})? {e}
+			= _ e:(e:spanned(<expr(s)>, s) _{e})? {e}
 		pub rule slice_desc(s: &ParserSettings) -> SliceDesc
 			= start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {
 				let (end, step) = if let Some((end, step)) = pair {
@@ -340,11 +346,8 @@
 			}
 		use jrsonnet_ir::BinaryOpType::*;
 		use jrsonnet_ir::UnaryOpType::*;
-		rule expr(s: &ParserSettings) -> Spanned<Expr>
+		rule expr(s: &ParserSettings) -> Expr
 			= precedence! {
-				"(" _ e:expr(s) _ ")" {e}
-				start:position!() v:@ end:position!() { Spanned::new(v, Span(s.source.clone(), start as u32, end as u32)) }
-				--
 				a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}
 				a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {
 					#[cfg(feature = "exp-null-coaelse")] return expr_bin!(a NullCoaelse b);
@@ -385,29 +388,32 @@
 				--
 				value:(@) _ "[" _ slice:slice_desc(s) _ "]" {Expr::Slice(Box::new(Slice{value, slice}))}
 				indexable:(@) _ parts:index_part(s)+ {Expr::Index{indexable: Box::new(indexable), parts}}
-				a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {Expr::Apply(Box::new(a), args, ts.is_some())}
+				a:(@) _ args:spanned(<"(" _ a:args(s) _ ")" {a}>, s) ts:(_ keyword("tailstrict"))? {Expr::Apply(Box::new(a), args, ts.is_some())}
 				a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(Rc::new(a), body)}
 				--
 				e:expr_basic(s) {e}
+				"(" _ e:expr(s) _ ")" {e}
 			}
 		pub rule index_part(s: &ParserSettings) -> IndexPart
 		= n:("?" _ ensure_null_coaelse())? "." _ value:id_loc(s) {IndexPart {
-			value,
+			span: value.1,
+			value: value.0,
 			#[cfg(feature = "exp-null-coaelse")]
 			null_coaelse: n.is_some(),
 		}}
-		/ n:("?" _ "." _ ensure_null_coaelse())? "[" _ value:expr(s) _ "]" {IndexPart {
-			value,
+		/ n:("?" _ "." _ ensure_null_coaelse())? value:spanned(<"[" _ v:expr(s) _ "]" {v}>, s) {IndexPart {
+			span: value.1,
+			value: value.0,
 			#[cfg(feature = "exp-null-coaelse")]
 			null_coaelse: n.is_some(),
 		}}
 
-		pub rule jsonnet(s: &ParserSettings) -> Spanned<Expr> = _ e:expr(s) _ {e}
+		pub rule jsonnet(s: &ParserSettings) -> Expr = _ e:expr(s) _ {e}
 	}
 }
 
 pub type ParseError = peg::error::ParseError<peg::str::LineCol>;
-pub fn parse(str: &str, settings: &ParserSettings) -> Result<Spanned<Expr>, ParseError> {
+pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {
 	jsonnet_parser::jsonnet(str, settings)
 }
 /// Used for importstr values