git.delta.rocks / jrsonnet / refs/commits / 3e23ebe1b496

difftreelog

refactor add proper getters for LocExpr

Yaroslav Bolyukin2024-05-27parent: #ea44e44.patch.diff
in: master

10 files changed

modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -53,8 +53,6 @@
 serde.workspace = true
 
 anyhow = { workspace = true, optional = true }
-# Serialized stdlib
-bincode = { workspace = true, optional = true }
 # Explaining traces
 annotate-snippets = { workspace = true, optional = true }
 # Better explaining traces
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -7,7 +7,7 @@
 
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};
+use jrsonnet_parser::{BinaryOpType, LocExpr, Source, SourcePath, Span, UnaryOpType};
 use jrsonnet_types::ValType;
 use thiserror::Error;
 
@@ -275,7 +275,7 @@
 pub struct StackTraceElement {
 	/// Source of this frame
 	/// Some frames only act as description, without attached source
-	pub location: Option<ExprLocation>,
+	pub location: Option<Span>,
 	/// Frame description
 	pub desc: String,
 }
@@ -324,20 +324,20 @@
 impl std::error::Error for Error {}
 
 pub trait ErrorSource {
-	fn to_location(self) -> Option<ExprLocation>;
+	fn to_location(self) -> Option<Span>;
 }
 impl ErrorSource for &LocExpr {
-	fn to_location(self) -> Option<ExprLocation> {
-		Some(self.1.clone())
+	fn to_location(self) -> Option<Span> {
+		Some(self.span())
 	}
 }
-impl ErrorSource for &ExprLocation {
-	fn to_location(self) -> Option<ExprLocation> {
+impl ErrorSource for &Span {
+	fn to_location(self) -> Option<Span> {
 		Some(self.clone())
 	}
 }
 impl ErrorSource for CallLocation<'_> {
-	fn to_location(self) -> Option<ExprLocation> {
+	fn to_location(self) -> Option<Span> {
 		self.0.cloned()
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -26,7 +26,7 @@
 
 pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {
 	fn is_trivial(expr: &LocExpr) -> bool {
-		match &*expr.0 {
+		match expr.expr() {
 			Expr::Str(_)
 			| Expr::Num(_)
 			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,
@@ -35,7 +35,7 @@
 			_ => false,
 		}
 	}
-	Some(match &*expr.0 {
+	Some(match expr.expr() {
 		Expr::Str(s) => Val::string(s.clone()),
 		Expr::Num(n) => {
 			Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))
@@ -72,7 +72,7 @@
 	Ok(match field_name {
 		FieldName::Fixed(n) => Some(n.clone()),
 		FieldName::Dyn(expr) => State::push(
-			CallLocation::new(&expr.1),
+			CallLocation::new(&expr.span()),
 			|| "evaluating field name".to_string(),
 			|| {
 				let value = evaluate(ctx, expr)?;
@@ -231,7 +231,7 @@
 				.field(name.clone())
 				.with_add(*plus)
 				.with_visibility(*visibility)
-				.with_location(value.1.clone())
+				.with_location(value.span())
 				.bindable(UnboundValue {
 					uctx,
 					value: value.clone(),
@@ -266,7 +266,7 @@
 			builder
 				.field(name.clone())
 				.with_visibility(*visibility)
-				.with_location(value.1.clone())
+				.with_location(value.span())
 				.bindable(UnboundMethod {
 					uctx,
 					value: value.clone(),
@@ -385,13 +385,13 @@
 	let value = &assertion.0;
 	let msg = &assertion.1;
 	let assertion_result = State::push(
-		CallLocation::new(&value.1),
+		CallLocation::new(&value.span()),
 		|| "assertion condition".to_owned(),
 		|| bool::from_untyped(evaluate(ctx.clone(), value)?),
 	)?;
 	if !assertion_result {
 		State::push(
-			CallLocation::new(&value.1),
+			CallLocation::new(&value.span()),
 			|| "assertion failure".to_owned(),
 			|| {
 				if let Some(msg) = msg {
@@ -406,8 +406,7 @@
 
 pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {
 	use Expr::*;
-	let LocExpr(raw_expr, _loc) = expr;
-	Ok(match &**raw_expr {
+	Ok(match expr.expr() {
 		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),
 		_ => evaluate(ctx, expr)?,
 	})
@@ -420,8 +419,8 @@
 	if let Some(trivial) = evaluate_trivial(expr) {
 		return Ok(trivial);
 	}
-	let LocExpr(expr, loc) = expr;
-	Ok(match &**expr {
+	let loc = expr.span();
+	Ok(match expr.expr() {
 		Literal(LiteralType::This) => {
 			Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
 		}
@@ -448,7 +447,7 @@
 		// because the standalone super literal is not supported, that is because in other
 		// implementations `in super` treated differently from in `smth_else`.
 		BinaryOp(field, BinaryOpType::In, e)
-			if matches!(&*e.0, Expr::Literal(LiteralType::Super)) =>
+			if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
 		{
 			let Some(super_obj) = ctx.super_obj() else {
 				return Ok(Val::Bool(false));
@@ -459,52 +458,50 @@
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
 		Var(name) => State::push(
-			CallLocation::new(loc),
+			CallLocation::new(&loc),
 			|| format!("variable <{name}> access"),
 			|| ctx.binding(name.clone())?.evaluate(),
 		)?,
 		Index { indexable, parts } => {
 			let mut parts = parts.iter();
-			let mut indexable = match &indexable {
-				// Cheaper to execute than creating object with overriden `this`
-				LocExpr(v, _) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
-					let part = parts.next().expect("at least part should exist");
-					let Some(super_obj) = ctx.super_obj() else {
-						#[cfg(feature = "exp-null-coaelse")]
-						if part.null_coaelse {
-							return Ok(Val::Null);
-						}
-						bail!(NoSuperFound)
-					};
-					let name = evaluate(ctx.clone(), &part.value)?;
+			let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
+				let part = parts.next().expect("at least part should exist");
+				let Some(super_obj) = ctx.super_obj() else {
+					#[cfg(feature = "exp-null-coaelse")]
+					if part.null_coaelse {
+						return Ok(Val::Null);
+					}
+					bail!(NoSuperFound)
+				};
+				let name = evaluate(ctx.clone(), &part.value)?;
 
-					let Val::Str(name) = name else {
-						bail!(ValueIndexMustBeTypeGot(
-							ValType::Obj,
-							ValType::Str,
-							name.value_type(),
-						))
-					};
+				let Val::Str(name) = name else {
+					bail!(ValueIndexMustBeTypeGot(
+						ValType::Obj,
+						ValType::Str,
+						name.value_type(),
+					))
+				};
 
-					let this = ctx
-						.this()
-						.expect("no this found, while super present, should not happen");
-					let name = name.into_flat();
-					match super_obj
-						.get_for(name.clone(), this.clone())
-						.with_description_src(&part.value, || format!("field <{name}> access"))?
-					{
-						Some(v) => v,
-						#[cfg(feature = "exp-null-coaelse")]
-						None if part.null_coaelse => return Ok(Val::Null),
-						None => {
-							let suggestions = suggest_object_fields(super_obj, name.clone());
+				let this = ctx
+					.this()
+					.expect("no this found, while super present, should not happen");
+				let name = name.into_flat();
+				match super_obj
+					.get_for(name.clone(), this.clone())
+					.with_description_src(&part.value, || format!("field <{name}> access"))?
+				{
+					Some(v) => v,
+					#[cfg(feature = "exp-null-coaelse")]
+					None if part.null_coaelse => return Ok(Val::Null),
+					None => {
+						let suggestions = suggest_object_fields(super_obj, name.clone());
 
-							bail!(NoSuchField(name, suggestions))
-						}
+						bail!(NoSuchField(name, suggestions))
 					}
 				}
-				e => evaluate(ctx.clone(), e)?,
+			} else {
+				evaluate(ctx.clone(), indexable)?
 			};
 
 			for part in parts {
@@ -639,7 +636,7 @@
 			&Val::Obj(evaluate_object(ctx, b)?),
 		)?,
 		Apply(value, args, tailstrict) => {
-			evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?
+			evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)?
 		}
 		Function(params, body) => {
 			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())
@@ -649,7 +646,7 @@
 			evaluate(ctx, returned)?
 		}
 		ErrorStmt(e) => State::push(
-			CallLocation::new(loc),
+			CallLocation::new(&loc),
 			|| "error statement".to_owned(),
 			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
 		)?,
@@ -659,7 +656,7 @@
 			cond_else,
 		} => {
 			if State::push(
-				CallLocation::new(loc),
+				CallLocation::new(&loc),
 				|| "if condition".to_owned(),
 				|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
 			)? {
@@ -690,7 +687,7 @@
 			}
 
 			let indexable = evaluate(ctx.clone(), value)?;
-			let loc = CallLocation::new(loc);
+			let loc = CallLocation::new(&loc);
 
 			let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;
 			let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;
@@ -699,7 +696,7 @@
 			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
 		}
 		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
-			let Expr::Str(path) = &*path.0 else {
+			let Expr::Str(path) = &path.expr() else {
 				bail!("computed imports are not supported")
 			};
 			let tmp = loc.clone().0;
@@ -707,7 +704,7 @@
 			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
 			match i {
 				Import(_) => State::push(
-					CallLocation::new(loc),
+					CallLocation::new(&loc),
 					|| format!("import {:?}", path.clone()),
 					|| s.import_resolved(resolved_path),
 				)?,
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -4,7 +4,7 @@
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{Destruct, Expr, ExprLocation, LocExpr, ParamsDesc};
+use jrsonnet_parser::{Destruct, Expr, LocExpr, ParamsDesc, Span};
 
 use self::{
 	arglike::OptionalContext,
@@ -22,10 +22,10 @@
 /// Function callsite location.
 /// Either from other jsonnet code, specified by expression location, or from native (without location).
 #[derive(Clone, Copy)]
-pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
+pub struct CallLocation<'l>(pub Option<&'l Span>);
 impl<'l> CallLocation<'l> {
 	/// Construct new location for calls coming from specified jsonnet expression location.
-	pub const fn new(loc: &'l ExprLocation) -> Self {
+	pub const fn new(loc: &'l Span) -> Self {
 		Self(Some(loc))
 	}
 }
@@ -225,7 +225,7 @@
 					#[cfg(feature = "exp-destruct")]
 					_ => return false,
 				};
-				&desc.body.0 as &Expr == &Expr::Var(id.clone())
+				desc.body.expr() == &Expr::Var(id.clone())
 			}
 			_ => false,
 		}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
 #[doc(hidden)]
 pub use jrsonnet_macros;
 pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{ExprLocation, LocExpr, ParserSettings, Source, SourcePath};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
 pub use obj::*;
 use stack::check_depth;
 pub use tla::apply_tla;
@@ -369,7 +369,7 @@
 	/// Executes code creating a new stack frame
 	pub fn push_val(
 		&self,
-		e: &ExprLocation,
+		e: &Span,
 		frame_desc: impl FnOnce() -> String,
 		f: impl FnOnce() -> Result<Val>,
 	) -> Result<Val> {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{ExprLocation, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	bail,17	error::{suggest_object_fields, Error, ErrorKind::*},18	function::{CallLocation, FuncVal},19	gc::{GcHashMap, GcHashSet, TraceBox},20	operator::evaluate_add_op,21	tb,22	val::{ArrValue, ThunkValue},23	MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28	#![allow(29		// This module works as stub for preserve-order feature30		clippy::unused_self,31	)]3233	use jrsonnet_gcmodule::Trace;3435	#[derive(Clone, Copy, Default, Debug, Trace)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub const fn next(self) -> Self {39			Self(())40		}41	}4243	#[derive(Clone, Copy, Default, Debug, Trace)]44	pub struct SuperDepth(());45	impl SuperDepth {46		pub const fn deeper(self) -> Self {47			Self(())48		}49	}5051	#[derive(Clone, Copy)]52	pub struct FieldSortKey(());53	impl FieldSortKey {54		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55			Self(())56		}57	}58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62	use std::cmp::Reverse;6364	use jrsonnet_gcmodule::Trace;6566	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67	pub struct FieldIndex(u32);68	impl FieldIndex {69		pub fn next(self) -> Self {70			Self(self.0 + 1)71		}72	}7374	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75	pub struct SuperDepth(u32);76	impl SuperDepth {77		pub fn deeper(self) -> Self {78			Self(self.0 + 1)79		}80	}8182	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84	impl FieldSortKey {85		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86			Self(Reverse(depth), index)87		}88	}89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};9293// 0 - add94//  12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98	fn new(add: bool, visibility: Visibility) -> Self {99		let mut v = 0;100		if add {101			v |= 1;102		}103		v |= match visibility {104			Visibility::Normal => 0b000,105			Visibility::Hidden => 0b010,106			Visibility::Unhide => 0b100,107		};108		Self(v)109	}110	pub fn add(&self) -> bool {111		self.0 & 1 != 0112	}113	pub fn visibility(&self) -> Visibility {114		match (self.0 & 0b110) >> 1 {115			0b00 => Visibility::Normal,116			0b01 => Visibility::Hidden,117			0b10 => Visibility::Unhide,118			_ => unreachable!(),119		}120	}121}122impl Debug for ObjFieldFlags {123	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124		f.debug_struct("ObjFieldFlags")125			.field("add", &self.add())126			.field("visibility", &self.visibility())127			.finish()128	}129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134	#[trace(skip)]135	flags: ObjFieldFlags,136	original_index: FieldIndex,137	pub invoke: MaybeUnbound,138	pub location: Option<ExprLocation>,139}140141pub trait ObjectAssertion: Trace {142	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145// Field => This146147#[derive(Trace)]148enum CacheValue {149	Cached(Val),150	NotFound,151	Pending,152	Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159	sup: Option<ObjValue>,160	// this: Option<ObjValue>,161	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162	assertions_ran: RefCell<GcHashSet<ObjValue>>,163	this_entries: Cc<GcHashMap<IStr, ObjMember>>,164	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168		f.debug_struct("OopObject")169			.field("sup", &self.sup)170			// .field("assertions", &self.assertions)171			// .field("assertions_ran", &self.assertions_ran)172			.field("this_entries", &self.this_entries)173			// .field("value_cache", &self.value_cache)174			.finish_non_exhaustive()175	}176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181	fn extend_from(&self, sup: ObjValue) -> ObjValue;182	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed183	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184		ObjValue::new(ThisOverride { inner: me, this })185	}186	fn this(&self) -> Option<ObjValue> {187		None188	}189	fn len(&self) -> usize;190	fn is_empty(&self) -> bool;191	// If callback returns false, iteration stops192	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194	fn has_field_include_hidden(&self, name: IStr) -> bool;195	fn has_field(&self, name: IStr) -> bool;196197	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199	fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208	fn eq(&self, other: &Self) -> bool {209		Weak::ptr_eq(&self.0, &other.0)210	}211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215	fn hash<H: Hasher>(&self, hasher: &mut H) {216		// Safety: usize is POD217		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218		hasher.write_usize(addr);219	}220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229	fn extend_from(&self, sup: ObjValue) -> ObjValue {230		// obj + {} == obj231		sup232	}233234	fn this(&self) -> Option<ObjValue> {235		None236	}237238	fn len(&self) -> usize {239		0240	}241242	fn is_empty(&self) -> bool {243		true244	}245246	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247		false248	}249250	fn has_field_include_hidden(&self, _name: IStr) -> bool {251		false252	}253254	fn has_field(&self, _name: IStr) -> bool {255		false256	}257258	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259		Ok(None)260	}261	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262		Ok(None)263	}264265	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266		Ok(())267	}268269	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270		None271	}272}273274#[derive(Trace, Debug)]275struct ThisOverride {276	inner: ObjValue,277	this: ObjValue,278}279impl ObjectLike for ThisOverride {280	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281		ObjValue::new(Self {282			inner: self.inner.clone(),283			this,284		})285	}286287	fn extend_from(&self, sup: ObjValue) -> ObjValue {288		self.inner.extend_from(sup).with_this(self.this.clone())289	}290291	fn this(&self) -> Option<ObjValue> {292		Some(self.this.clone())293	}294295	fn len(&self) -> usize {296		self.inner.len()297	}298299	fn is_empty(&self) -> bool {300		self.inner.is_empty()301	}302303	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304		self.inner.enum_fields(depth, handler)305	}306307	fn has_field_include_hidden(&self, name: IStr) -> bool {308		self.inner.has_field_include_hidden(name)309	}310311	fn has_field(&self, name: IStr) -> bool {312		self.inner.has_field(name)313	}314315	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316		self.inner.get_for(key, this)317	}318319	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320		self.inner.get_raw(key, this)321	}322323	fn field_visibility(&self, field: IStr) -> Option<Visibility> {324		self.inner.field_visibility(field)325	}326327	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328		self.inner.run_assertions_raw(this)329	}330}331332impl ObjValue {333	pub fn new(v: impl ObjectLike) -> Self {334		Self(Cc::new(tb!(v)))335	}336	pub fn new_empty() -> Self {337		Self::new(EmptyObject)338	}339	pub fn builder() -> ObjValueBuilder {340		ObjValueBuilder::new()341	}342	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343		ObjValueBuilder::with_capacity(capacity)344	}345	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346		let mut out = ObjValueBuilder::with_capacity(1);347		out.with_super(self);348		let mut member = out.field(key);349		if value.flags.add() {350			member = member.add();351		}352		if let Some(loc) = value.location {353			member = member.with_location(loc);354		}355		let _ = member356			.with_visibility(value.flags.visibility())357			.binding(value.invoke);358		out.build()359	}360	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362	}363364	#[must_use]365	pub fn extend_from(&self, sup: Self) -> Self {366		self.0.extend_from(sup)367	}368	#[must_use]369	pub fn with_this(&self, this: Self) -> Self {370		self.0.with_this(self.clone(), this)371	}372	pub fn len(&self) -> usize {373		self.0.len()374	}375	pub fn is_empty(&self) -> bool {376		self.0.is_empty()377	}378	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379		self.0.enum_fields(depth, handler)380	}381382	pub fn has_field_include_hidden(&self, name: IStr) -> bool {383		self.0.has_field_include_hidden(name)384	}385	pub fn has_field(&self, name: IStr) -> bool {386		self.0.has_field(name)387	}388	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389		if include_hidden {390			self.has_field_include_hidden(name)391		} else {392			self.has_field(name)393		}394	}395396	pub fn get(&self, key: IStr) -> Result<Option<Val>> {397		self.run_assertions()?;398		self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399	}400401	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402		self.0.get_for(key, this)403	}404405	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406		let Some(value) = self.get(key.clone())? else {407			let suggestions = suggest_object_fields(self, key.clone());408			bail!(NoSuchField(key, suggestions))409		};410		Ok(value)411	}412413	fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414		self.0.get_for_uncached(key, this)415	}416417	fn field_visibility(&self, field: IStr) -> Option<Visibility> {418		self.0.field_visibility(field)419	}420421	pub fn run_assertions(&self) -> Result<()> {422		// FIXME: Should it use `self.0.this()` in case of standalone super?423		self.run_assertions_raw(self.clone())424	}425	fn run_assertions_raw(&self, this: Self) -> Result<()> {426		self.0.run_assertions_raw(this)427	}428429	pub fn iter(430		&self,431		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,432	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433		let fields = self.fields(434			#[cfg(feature = "exp-preserve-order")]435			preserve_order,436		);437		fields.into_iter().map(|field| {438			(439				field.clone(),440				self.get(field)441					.map(|opt| opt.expect("iterating over keys, field exists")),442			)443		})444	}445	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446		#[derive(Trace)]447		struct ThunkGet {448			obj: ObjValue,449			key: IStr,450		}451		impl ThunkValue for ThunkGet {452			type Output = Val;453454			fn get(self: Box<Self>) -> Result<Self::Output> {455				Ok(self.obj.get(self.key)?.expect("field exists"))456			}457		}458459		if !self.has_field_ex(key.clone(), true) {460			return None;461		}462		Some(Thunk::new(ThunkGet {463			obj: self.clone(),464			key,465		}))466	}467	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468		#[derive(Trace)]469		struct ThunkGet {470			obj: ObjValue,471			key: IStr,472		}473		impl ThunkValue for ThunkGet {474			type Output = Val;475476			fn get(self: Box<Self>) -> Result<Self::Output> {477				self.obj.get_or_bail(self.key)478			}479		}480481		Thunk::new(ThunkGet {482			obj: self.clone(),483			key,484		})485	}486	pub fn ptr_eq(a: &Self, b: &Self) -> bool {487		Cc::ptr_eq(&a.0, &b.0)488	}489	pub fn downgrade(self) -> WeakObjValue {490		WeakObjValue(self.0.downgrade())491	}492	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493		let mut out = FxHashMap::default();494		self.enum_fields(495			SuperDepth::default(),496			&mut |depth, index, name, visibility| {497				let new_sort_key = FieldSortKey::new(depth, index);498				let entry = out.entry(name);499				let (visible, _) = entry.or_insert((true, new_sort_key));500				match visibility {501					Visibility::Normal => {}502					Visibility::Hidden => {503						*visible = false;504					}505					Visibility::Unhide => {506						*visible = true;507					}508				};509				false510			},511		);512		out513	}514	pub fn fields_ex(515		&self,516		include_hidden: bool,517		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,518	) -> Vec<IStr> {519		#[cfg(feature = "exp-preserve-order")]520		if preserve_order {521			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522				.fields_visibility()523				.into_iter()524				.filter(|(_, (visible, _))| include_hidden || *visible)525				.enumerate()526				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527				.unzip();528			keys.sort_unstable_by_key(|v| v.0);529			// Reorder in-place by resulting indexes530			for i in 0..fields.len() {531				let x = fields[i].clone();532				let mut j = i;533				loop {534					let k = keys[j].1;535					keys[j].1 = j;536					if k == i {537						break;538					}539					fields[j] = fields[k].clone();540					j = k;541				}542				fields[j] = x;543			}544			return fields;545		}546547		let mut fields: Vec<_> = self548			.fields_visibility()549			.into_iter()550			.filter(|(_, (visible, _))| include_hidden || *visible)551			.map(|(k, _)| k)552			.collect();553		fields.sort_unstable();554		fields555	}556	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557		self.fields_ex(558			false,559			#[cfg(feature = "exp-preserve-order")]560			preserve_order,561		)562	}563	pub fn values_ex(564		&self,565		include_hidden: bool,566		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,567	) -> ArrValue {568		ArrValue::new(PickObjectValues::new(569			self.clone(),570			self.fields_ex(571				include_hidden,572				#[cfg(feature = "exp-preserve-order")]573				preserve_order,574			),575		))576	}577	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578		self.values_ex(579			false,580			#[cfg(feature = "exp-preserve-order")]581			preserve_order,582		)583	}584	pub fn key_values_ex(585		&self,586		include_hidden: bool,587		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,588	) -> ArrValue {589		ArrValue::new(PickObjectKeyValues::new(590			self.clone(),591			self.fields_ex(592				include_hidden,593				#[cfg(feature = "exp-preserve-order")]594				preserve_order,595			),596		))597	}598	pub fn key_values(599		&self,600		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,601	) -> ArrValue {602		self.key_values_ex(603			false,604			#[cfg(feature = "exp-preserve-order")]605			preserve_order,606		)607	}608}609610impl OopObject {611	pub fn new(612		sup: Option<ObjValue>,613		this_entries: Cc<GcHashMap<IStr, ObjMember>>,614		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615	) -> Self {616		Self {617			sup,618			// this: None,619			assertions,620			assertions_ran: RefCell::new(GcHashSet::new()),621			this_entries,622			value_cache: RefCell::new(GcHashMap::new()),623		}624	}625626	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627		v.invoke.evaluate(self.sup.clone(), Some(real_this))628	}629630	// FIXME: Duplication between ObjValue and OopObject631	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632		let mut out = FxHashMap::default();633		self.enum_fields(634			SuperDepth::default(),635			&mut |depth, index, name, visibility| {636				let new_sort_key = FieldSortKey::new(depth, index);637				let entry = out.entry(name);638				let (visible, _) = entry.or_insert((true, new_sort_key));639				match visibility {640					Visibility::Normal => {}641					Visibility::Hidden => {642						*visible = false;643					}644					Visibility::Unhide => {645						*visible = true;646					}647				};648				false649			},650		);651		out652	}653}654655impl ObjectLike for OopObject {656	fn extend_from(&self, sup: ObjValue) -> ObjValue {657		ObjValue::new(match &self.sup {658			None => Self::new(659				Some(sup),660				self.this_entries.clone(),661				self.assertions.clone(),662			),663			Some(v) => Self::new(664				Some(v.extend_from(sup)),665				self.this_entries.clone(),666				self.assertions.clone(),667			),668		})669	}670671	fn len(&self) -> usize {672		// Maybe it will be better to not compute sort key here?673		self.fields_visibility()674			.into_iter()675			.filter(|(_, (visible, _))| *visible)676			.count()677	}678679	/// Returns false only if there is any visible entry.680	///681	/// Note that object with hidden fields `{a:: 1}` will be reported as empty here.682	fn is_empty(&self) -> bool {683		self.len() == 0684	}685686	/// Run callback for every field found in object687	///688	/// Returns true if ended prematurely689	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {690		if let Some(s) = &self.sup {691			if s.enum_fields(depth.deeper(), handler) {692				return true;693			}694		}695		for (name, member) in self.this_entries.iter() {696			if handler(697				depth,698				member.original_index,699				name.clone(),700				member.flags.visibility(),701			) {702				return true;703			}704		}705		false706	}707708	fn has_field_include_hidden(&self, name: IStr) -> bool {709		if self.this_entries.contains_key(&name) {710			true711		} else if let Some(super_obj) = &self.sup {712			super_obj.has_field_include_hidden(name)713		} else {714			false715		}716	}717	fn has_field(&self, name: IStr) -> bool {718		self.field_visibility(name)719			.map_or(false, |v| v.is_visible())720	}721722	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {723		let cache_key = (key.clone(), Some(this.clone().downgrade()));724		if let Some(v) = self.value_cache.borrow().get(&cache_key) {725			return Ok(match v {726				CacheValue::Cached(v) => Some(v.clone()),727				CacheValue::NotFound => None,728				CacheValue::Pending => bail!(InfiniteRecursionDetected),729				CacheValue::Errored(e) => return Err(e.clone()),730			});731		}732		self.value_cache733			.borrow_mut()734			.insert(cache_key.clone(), CacheValue::Pending);735		let value = self.get_for_uncached(key, this).map_err(|e| {736			self.value_cache737				.borrow_mut()738				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));739			e740		})?;741		self.value_cache.borrow_mut().insert(742			cache_key,743			value744				.as_ref()745				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),746		);747		Ok(value)748	}749	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {750		match (self.this_entries.get(&key), &self.sup) {751			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),752			(Some(k), Some(super_obj)) => {753				let our = self.evaluate_this(k, real_this.clone())?;754				if k.flags.add() {755					super_obj756						.get_raw(key, real_this)?757						.map_or(Ok(Some(our.clone())), |v| {758							Ok(Some(evaluate_add_op(&v, &our)?))759						})760				} else {761					Ok(Some(our))762				}763			}764			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),765			(None, None) => Ok(None),766		}767	}768	fn field_visibility(&self, name: IStr) -> Option<Visibility> {769		if let Some(m) = self.this_entries.get(&name) {770			Some(match &m.flags.visibility() {771				Visibility::Normal => self772					.sup773					.as_ref()774					.and_then(|super_obj| super_obj.field_visibility(name))775					.unwrap_or(Visibility::Normal),776				v => *v,777			})778		} else if let Some(super_obj) = &self.sup {779			super_obj.field_visibility(name)780		} else {781			None782		}783	}784785	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {786		if self.assertions.is_empty() {787			if let Some(super_obj) = &self.sup {788				super_obj.run_assertions_raw(real_this)?;789			}790			return Ok(());791		}792		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {793			for assertion in self.assertions.iter() {794				if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {795					self.assertions_ran.borrow_mut().remove(&real_this);796					return Err(e);797				}798			}799			if let Some(super_obj) = &self.sup {800				super_obj.run_assertions_raw(real_this)?;801			}802		}803		Ok(())804	}805}806807impl PartialEq for ObjValue {808	fn eq(&self, other: &Self) -> bool {809		Cc::ptr_eq(&self.0, &other.0)810	}811}812813impl Eq for ObjValue {}814impl Hash for ObjValue {815	fn hash<H: Hasher>(&self, hasher: &mut H) {816		hasher.write_usize(addr_of!(*self.0) as usize);817	}818}819820#[allow(clippy::module_name_repetitions)]821pub struct ObjValueBuilder {822	sup: Option<ObjValue>,823	map: GcHashMap<IStr, ObjMember>,824	assertions: Vec<TraceBox<dyn ObjectAssertion>>,825	next_field_index: FieldIndex,826}827impl ObjValueBuilder {828	pub fn new() -> Self {829		Self::with_capacity(0)830	}831	pub fn with_capacity(capacity: usize) -> Self {832		Self {833			sup: None,834			map: GcHashMap::with_capacity(capacity),835			assertions: Vec::new(),836			next_field_index: FieldIndex::default(),837		}838	}839	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {840		self.assertions.reserve_exact(capacity);841		self842	}843	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {844		self.sup = Some(super_obj);845		self846	}847848	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {849		self.assertions.push(tb!(assertion));850		self851	}852	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {853		let field_index = self.next_field_index;854		self.next_field_index = self.next_field_index.next();855		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)856	}857	/// Preset for common method definiton pattern:858	/// Create a hidden field with the function value.859	///860	/// `.field(name).hide().value(Val::function(value))`861	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {862		self.field(name).hide().value(Val::Func(value.into()));863		self864	}865	pub fn try_method(866		&mut self,867		name: impl Into<IStr>,868		value: impl Into<FuncVal>,869	) -> Result<&mut Self> {870		self.field(name).hide().try_value(Val::Func(value.into()))?;871		Ok(self)872	}873874	pub fn build(self) -> ObjValue {875		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {876			return ObjValue::new_empty();877		}878		ObjValue::new(OopObject::new(879			self.sup,880			Cc::new(self.map),881			Cc::new(self.assertions),882		))883	}884}885impl Default for ObjValueBuilder {886	fn default() -> Self {887		Self::with_capacity(0)888	}889}890891#[allow(clippy::module_name_repetitions)]892#[must_use = "value not added unless binding() was called"]893pub struct ObjMemberBuilder<Kind> {894	kind: Kind,895	name: IStr,896	add: bool,897	visibility: Visibility,898	original_index: FieldIndex,899	location: Option<ExprLocation>,900}901902#[allow(clippy::missing_const_for_fn)]903impl<Kind> ObjMemberBuilder<Kind> {904	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {905		Self {906			kind,907			name,908			original_index,909			add: false,910			visibility: Visibility::Normal,911			location: None,912		}913	}914915	pub const fn with_add(mut self, add: bool) -> Self {916		self.add = add;917		self918	}919	pub fn add(self) -> Self {920		self.with_add(true)921	}922	pub fn with_visibility(mut self, visibility: Visibility) -> Self {923		self.visibility = visibility;924		self925	}926	pub fn hide(self) -> Self {927		self.with_visibility(Visibility::Hidden)928	}929	pub fn with_location(mut self, location: ExprLocation) -> Self {930		self.location = Some(location);931		self932	}933	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {934		(935			self.kind,936			self.name,937			ObjMember {938				flags: ObjFieldFlags::new(self.add, self.visibility),939				original_index: self.original_index,940				invoke: binding,941				location: self.location,942			},943		)944	}945}946947pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);948impl ObjMemberBuilder<ValueBuilder<'_>> {949	/// Inserts value, replacing if it is already defined950	pub fn value(self, value: impl Into<Val>) {951		let (receiver, name, member) =952			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));953		let entry = receiver.0.map.entry(name);954		entry.insert(member);955	}956957	/// Tries to insert value, returns an error if it was already defined958	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {959		self.thunk(Thunk::evaluated(value.into()))960	}961	pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {962		self.binding(MaybeUnbound::Bound(value.into()))963	}964	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {965		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))966	}967	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {968		let (receiver, name, member) = self.build_member(binding);969		let location = member.location.clone();970		let old = receiver.0.map.insert(name.clone(), member);971		if old.is_some() {972			State::push(973				CallLocation(location.as_ref()),974				|| format!("field <{}> initializtion", name.clone()),975				|| bail!(DuplicateFieldName(name.clone())),976			)?;977		}978		Ok(())979	}980}981982pub struct ExtendBuilder<'v>(&'v mut ObjValue);983impl ObjMemberBuilder<ExtendBuilder<'_>> {984	pub fn value(self, value: impl Into<Val>) {985		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));986	}987	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {988		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));989	}990	pub fn binding(self, binding: MaybeUnbound) {991		let (receiver, name, member) = self.build_member(binding);992		let new = receiver.0.clone();993		*receiver.0 = new.extend_with_raw_member(name, member);994	}995}
after · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{Span, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	bail,17	error::{suggest_object_fields, Error, ErrorKind::*},18	function::{CallLocation, FuncVal},19	gc::{GcHashMap, GcHashSet, TraceBox},20	operator::evaluate_add_op,21	tb,22	val::{ArrValue, ThunkValue},23	MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28	#![allow(29		// This module works as stub for preserve-order feature30		clippy::unused_self,31	)]3233	use jrsonnet_gcmodule::Trace;3435	#[derive(Clone, Copy, Default, Debug, Trace)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub const fn next(self) -> Self {39			Self(())40		}41	}4243	#[derive(Clone, Copy, Default, Debug, Trace)]44	pub struct SuperDepth(());45	impl SuperDepth {46		pub const fn deeper(self) -> Self {47			Self(())48		}49	}5051	#[derive(Clone, Copy)]52	pub struct FieldSortKey(());53	impl FieldSortKey {54		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55			Self(())56		}57	}58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62	use std::cmp::Reverse;6364	use jrsonnet_gcmodule::Trace;6566	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67	pub struct FieldIndex(u32);68	impl FieldIndex {69		pub fn next(self) -> Self {70			Self(self.0 + 1)71		}72	}7374	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75	pub struct SuperDepth(u32);76	impl SuperDepth {77		pub fn deeper(self) -> Self {78			Self(self.0 + 1)79		}80	}8182	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84	impl FieldSortKey {85		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86			Self(Reverse(depth), index)87		}88	}89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};9293// 0 - add94//  12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98	fn new(add: bool, visibility: Visibility) -> Self {99		let mut v = 0;100		if add {101			v |= 1;102		}103		v |= match visibility {104			Visibility::Normal => 0b000,105			Visibility::Hidden => 0b010,106			Visibility::Unhide => 0b100,107		};108		Self(v)109	}110	pub fn add(&self) -> bool {111		self.0 & 1 != 0112	}113	pub fn visibility(&self) -> Visibility {114		match (self.0 & 0b110) >> 1 {115			0b00 => Visibility::Normal,116			0b01 => Visibility::Hidden,117			0b10 => Visibility::Unhide,118			_ => unreachable!(),119		}120	}121}122impl Debug for ObjFieldFlags {123	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124		f.debug_struct("ObjFieldFlags")125			.field("add", &self.add())126			.field("visibility", &self.visibility())127			.finish()128	}129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134	#[trace(skip)]135	flags: ObjFieldFlags,136	original_index: FieldIndex,137	pub invoke: MaybeUnbound,138	pub location: Option<Span>,139}140141pub trait ObjectAssertion: Trace {142	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145// Field => This146147#[derive(Trace)]148enum CacheValue {149	Cached(Val),150	NotFound,151	Pending,152	Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159	sup: Option<ObjValue>,160	// this: Option<ObjValue>,161	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162	assertions_ran: RefCell<GcHashSet<ObjValue>>,163	this_entries: Cc<GcHashMap<IStr, ObjMember>>,164	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168		f.debug_struct("OopObject")169			.field("sup", &self.sup)170			// .field("assertions", &self.assertions)171			// .field("assertions_ran", &self.assertions_ran)172			.field("this_entries", &self.this_entries)173			// .field("value_cache", &self.value_cache)174			.finish_non_exhaustive()175	}176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181	fn extend_from(&self, sup: ObjValue) -> ObjValue;182	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed183	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184		ObjValue::new(ThisOverride { inner: me, this })185	}186	fn this(&self) -> Option<ObjValue> {187		None188	}189	fn len(&self) -> usize;190	fn is_empty(&self) -> bool;191	// If callback returns false, iteration stops192	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194	fn has_field_include_hidden(&self, name: IStr) -> bool;195	fn has_field(&self, name: IStr) -> bool;196197	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199	fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208	fn eq(&self, other: &Self) -> bool {209		Weak::ptr_eq(&self.0, &other.0)210	}211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215	fn hash<H: Hasher>(&self, hasher: &mut H) {216		// Safety: usize is POD217		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218		hasher.write_usize(addr);219	}220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229	fn extend_from(&self, sup: ObjValue) -> ObjValue {230		// obj + {} == obj231		sup232	}233234	fn this(&self) -> Option<ObjValue> {235		None236	}237238	fn len(&self) -> usize {239		0240	}241242	fn is_empty(&self) -> bool {243		true244	}245246	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247		false248	}249250	fn has_field_include_hidden(&self, _name: IStr) -> bool {251		false252	}253254	fn has_field(&self, _name: IStr) -> bool {255		false256	}257258	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259		Ok(None)260	}261	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262		Ok(None)263	}264265	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266		Ok(())267	}268269	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270		None271	}272}273274#[derive(Trace, Debug)]275struct ThisOverride {276	inner: ObjValue,277	this: ObjValue,278}279impl ObjectLike for ThisOverride {280	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281		ObjValue::new(Self {282			inner: self.inner.clone(),283			this,284		})285	}286287	fn extend_from(&self, sup: ObjValue) -> ObjValue {288		self.inner.extend_from(sup).with_this(self.this.clone())289	}290291	fn this(&self) -> Option<ObjValue> {292		Some(self.this.clone())293	}294295	fn len(&self) -> usize {296		self.inner.len()297	}298299	fn is_empty(&self) -> bool {300		self.inner.is_empty()301	}302303	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304		self.inner.enum_fields(depth, handler)305	}306307	fn has_field_include_hidden(&self, name: IStr) -> bool {308		self.inner.has_field_include_hidden(name)309	}310311	fn has_field(&self, name: IStr) -> bool {312		self.inner.has_field(name)313	}314315	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316		self.inner.get_for(key, this)317	}318319	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320		self.inner.get_raw(key, this)321	}322323	fn field_visibility(&self, field: IStr) -> Option<Visibility> {324		self.inner.field_visibility(field)325	}326327	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328		self.inner.run_assertions_raw(this)329	}330}331332impl ObjValue {333	pub fn new(v: impl ObjectLike) -> Self {334		Self(Cc::new(tb!(v)))335	}336	pub fn new_empty() -> Self {337		Self::new(EmptyObject)338	}339	pub fn builder() -> ObjValueBuilder {340		ObjValueBuilder::new()341	}342	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343		ObjValueBuilder::with_capacity(capacity)344	}345	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346		let mut out = ObjValueBuilder::with_capacity(1);347		out.with_super(self);348		let mut member = out.field(key);349		if value.flags.add() {350			member = member.add();351		}352		if let Some(loc) = value.location {353			member = member.with_location(loc);354		}355		let _ = member356			.with_visibility(value.flags.visibility())357			.binding(value.invoke);358		out.build()359	}360	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362	}363364	#[must_use]365	pub fn extend_from(&self, sup: Self) -> Self {366		self.0.extend_from(sup)367	}368	#[must_use]369	pub fn with_this(&self, this: Self) -> Self {370		self.0.with_this(self.clone(), this)371	}372	pub fn len(&self) -> usize {373		self.0.len()374	}375	pub fn is_empty(&self) -> bool {376		self.0.is_empty()377	}378	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379		self.0.enum_fields(depth, handler)380	}381382	pub fn has_field_include_hidden(&self, name: IStr) -> bool {383		self.0.has_field_include_hidden(name)384	}385	pub fn has_field(&self, name: IStr) -> bool {386		self.0.has_field(name)387	}388	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389		if include_hidden {390			self.has_field_include_hidden(name)391		} else {392			self.has_field(name)393		}394	}395396	pub fn get(&self, key: IStr) -> Result<Option<Val>> {397		self.run_assertions()?;398		self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399	}400401	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402		self.0.get_for(key, this)403	}404405	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406		let Some(value) = self.get(key.clone())? else {407			let suggestions = suggest_object_fields(self, key.clone());408			bail!(NoSuchField(key, suggestions))409		};410		Ok(value)411	}412413	fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414		self.0.get_for_uncached(key, this)415	}416417	fn field_visibility(&self, field: IStr) -> Option<Visibility> {418		self.0.field_visibility(field)419	}420421	pub fn run_assertions(&self) -> Result<()> {422		// FIXME: Should it use `self.0.this()` in case of standalone super?423		self.run_assertions_raw(self.clone())424	}425	fn run_assertions_raw(&self, this: Self) -> Result<()> {426		self.0.run_assertions_raw(this)427	}428429	pub fn iter(430		&self,431		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,432	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433		let fields = self.fields(434			#[cfg(feature = "exp-preserve-order")]435			preserve_order,436		);437		fields.into_iter().map(|field| {438			(439				field.clone(),440				self.get(field)441					.map(|opt| opt.expect("iterating over keys, field exists")),442			)443		})444	}445	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446		#[derive(Trace)]447		struct ThunkGet {448			obj: ObjValue,449			key: IStr,450		}451		impl ThunkValue for ThunkGet {452			type Output = Val;453454			fn get(self: Box<Self>) -> Result<Self::Output> {455				Ok(self.obj.get(self.key)?.expect("field exists"))456			}457		}458459		if !self.has_field_ex(key.clone(), true) {460			return None;461		}462		Some(Thunk::new(ThunkGet {463			obj: self.clone(),464			key,465		}))466	}467	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468		#[derive(Trace)]469		struct ThunkGet {470			obj: ObjValue,471			key: IStr,472		}473		impl ThunkValue for ThunkGet {474			type Output = Val;475476			fn get(self: Box<Self>) -> Result<Self::Output> {477				self.obj.get_or_bail(self.key)478			}479		}480481		Thunk::new(ThunkGet {482			obj: self.clone(),483			key,484		})485	}486	pub fn ptr_eq(a: &Self, b: &Self) -> bool {487		Cc::ptr_eq(&a.0, &b.0)488	}489	pub fn downgrade(self) -> WeakObjValue {490		WeakObjValue(self.0.downgrade())491	}492	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493		let mut out = FxHashMap::default();494		self.enum_fields(495			SuperDepth::default(),496			&mut |depth, index, name, visibility| {497				let new_sort_key = FieldSortKey::new(depth, index);498				let entry = out.entry(name);499				let (visible, _) = entry.or_insert((true, new_sort_key));500				match visibility {501					Visibility::Normal => {}502					Visibility::Hidden => {503						*visible = false;504					}505					Visibility::Unhide => {506						*visible = true;507					}508				};509				false510			},511		);512		out513	}514	pub fn fields_ex(515		&self,516		include_hidden: bool,517		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,518	) -> Vec<IStr> {519		#[cfg(feature = "exp-preserve-order")]520		if preserve_order {521			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522				.fields_visibility()523				.into_iter()524				.filter(|(_, (visible, _))| include_hidden || *visible)525				.enumerate()526				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527				.unzip();528			keys.sort_unstable_by_key(|v| v.0);529			// Reorder in-place by resulting indexes530			for i in 0..fields.len() {531				let x = fields[i].clone();532				let mut j = i;533				loop {534					let k = keys[j].1;535					keys[j].1 = j;536					if k == i {537						break;538					}539					fields[j] = fields[k].clone();540					j = k;541				}542				fields[j] = x;543			}544			return fields;545		}546547		let mut fields: Vec<_> = self548			.fields_visibility()549			.into_iter()550			.filter(|(_, (visible, _))| include_hidden || *visible)551			.map(|(k, _)| k)552			.collect();553		fields.sort_unstable();554		fields555	}556	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557		self.fields_ex(558			false,559			#[cfg(feature = "exp-preserve-order")]560			preserve_order,561		)562	}563	pub fn values_ex(564		&self,565		include_hidden: bool,566		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,567	) -> ArrValue {568		ArrValue::new(PickObjectValues::new(569			self.clone(),570			self.fields_ex(571				include_hidden,572				#[cfg(feature = "exp-preserve-order")]573				preserve_order,574			),575		))576	}577	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578		self.values_ex(579			false,580			#[cfg(feature = "exp-preserve-order")]581			preserve_order,582		)583	}584	pub fn key_values_ex(585		&self,586		include_hidden: bool,587		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,588	) -> ArrValue {589		ArrValue::new(PickObjectKeyValues::new(590			self.clone(),591			self.fields_ex(592				include_hidden,593				#[cfg(feature = "exp-preserve-order")]594				preserve_order,595			),596		))597	}598	pub fn key_values(599		&self,600		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,601	) -> ArrValue {602		self.key_values_ex(603			false,604			#[cfg(feature = "exp-preserve-order")]605			preserve_order,606		)607	}608}609610impl OopObject {611	pub fn new(612		sup: Option<ObjValue>,613		this_entries: Cc<GcHashMap<IStr, ObjMember>>,614		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615	) -> Self {616		Self {617			sup,618			// this: None,619			assertions,620			assertions_ran: RefCell::new(GcHashSet::new()),621			this_entries,622			value_cache: RefCell::new(GcHashMap::new()),623		}624	}625626	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627		v.invoke.evaluate(self.sup.clone(), Some(real_this))628	}629630	// FIXME: Duplication between ObjValue and OopObject631	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632		let mut out = FxHashMap::default();633		self.enum_fields(634			SuperDepth::default(),635			&mut |depth, index, name, visibility| {636				let new_sort_key = FieldSortKey::new(depth, index);637				let entry = out.entry(name);638				let (visible, _) = entry.or_insert((true, new_sort_key));639				match visibility {640					Visibility::Normal => {}641					Visibility::Hidden => {642						*visible = false;643					}644					Visibility::Unhide => {645						*visible = true;646					}647				};648				false649			},650		);651		out652	}653}654655impl ObjectLike for OopObject {656	fn extend_from(&self, sup: ObjValue) -> ObjValue {657		ObjValue::new(match &self.sup {658			None => Self::new(659				Some(sup),660				self.this_entries.clone(),661				self.assertions.clone(),662			),663			Some(v) => Self::new(664				Some(v.extend_from(sup)),665				self.this_entries.clone(),666				self.assertions.clone(),667			),668		})669	}670671	fn len(&self) -> usize {672		// Maybe it will be better to not compute sort key here?673		self.fields_visibility()674			.into_iter()675			.filter(|(_, (visible, _))| *visible)676			.count()677	}678679	/// Returns false only if there is any visible entry.680	///681	/// Note that object with hidden fields `{a:: 1}` will be reported as empty here.682	fn is_empty(&self) -> bool {683		self.len() == 0684	}685686	/// Run callback for every field found in object687	///688	/// Returns true if ended prematurely689	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {690		if let Some(s) = &self.sup {691			if s.enum_fields(depth.deeper(), handler) {692				return true;693			}694		}695		for (name, member) in self.this_entries.iter() {696			if handler(697				depth,698				member.original_index,699				name.clone(),700				member.flags.visibility(),701			) {702				return true;703			}704		}705		false706	}707708	fn has_field_include_hidden(&self, name: IStr) -> bool {709		if self.this_entries.contains_key(&name) {710			true711		} else if let Some(super_obj) = &self.sup {712			super_obj.has_field_include_hidden(name)713		} else {714			false715		}716	}717	fn has_field(&self, name: IStr) -> bool {718		self.field_visibility(name)719			.map_or(false, |v| v.is_visible())720	}721722	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {723		let cache_key = (key.clone(), Some(this.clone().downgrade()));724		if let Some(v) = self.value_cache.borrow().get(&cache_key) {725			return Ok(match v {726				CacheValue::Cached(v) => Some(v.clone()),727				CacheValue::NotFound => None,728				CacheValue::Pending => bail!(InfiniteRecursionDetected),729				CacheValue::Errored(e) => return Err(e.clone()),730			});731		}732		self.value_cache733			.borrow_mut()734			.insert(cache_key.clone(), CacheValue::Pending);735		let value = self.get_for_uncached(key, this).map_err(|e| {736			self.value_cache737				.borrow_mut()738				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));739			e740		})?;741		self.value_cache.borrow_mut().insert(742			cache_key,743			value744				.as_ref()745				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),746		);747		Ok(value)748	}749	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {750		match (self.this_entries.get(&key), &self.sup) {751			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),752			(Some(k), Some(super_obj)) => {753				let our = self.evaluate_this(k, real_this.clone())?;754				if k.flags.add() {755					super_obj756						.get_raw(key, real_this)?757						.map_or(Ok(Some(our.clone())), |v| {758							Ok(Some(evaluate_add_op(&v, &our)?))759						})760				} else {761					Ok(Some(our))762				}763			}764			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),765			(None, None) => Ok(None),766		}767	}768	fn field_visibility(&self, name: IStr) -> Option<Visibility> {769		if let Some(m) = self.this_entries.get(&name) {770			Some(match &m.flags.visibility() {771				Visibility::Normal => self772					.sup773					.as_ref()774					.and_then(|super_obj| super_obj.field_visibility(name))775					.unwrap_or(Visibility::Normal),776				v => *v,777			})778		} else if let Some(super_obj) = &self.sup {779			super_obj.field_visibility(name)780		} else {781			None782		}783	}784785	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {786		if self.assertions.is_empty() {787			if let Some(super_obj) = &self.sup {788				super_obj.run_assertions_raw(real_this)?;789			}790			return Ok(());791		}792		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {793			for assertion in self.assertions.iter() {794				if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {795					self.assertions_ran.borrow_mut().remove(&real_this);796					return Err(e);797				}798			}799			if let Some(super_obj) = &self.sup {800				super_obj.run_assertions_raw(real_this)?;801			}802		}803		Ok(())804	}805}806807impl PartialEq for ObjValue {808	fn eq(&self, other: &Self) -> bool {809		Cc::ptr_eq(&self.0, &other.0)810	}811}812813impl Eq for ObjValue {}814impl Hash for ObjValue {815	fn hash<H: Hasher>(&self, hasher: &mut H) {816		hasher.write_usize(addr_of!(*self.0) as usize);817	}818}819820#[allow(clippy::module_name_repetitions)]821pub struct ObjValueBuilder {822	sup: Option<ObjValue>,823	map: GcHashMap<IStr, ObjMember>,824	assertions: Vec<TraceBox<dyn ObjectAssertion>>,825	next_field_index: FieldIndex,826}827impl ObjValueBuilder {828	pub fn new() -> Self {829		Self::with_capacity(0)830	}831	pub fn with_capacity(capacity: usize) -> Self {832		Self {833			sup: None,834			map: GcHashMap::with_capacity(capacity),835			assertions: Vec::new(),836			next_field_index: FieldIndex::default(),837		}838	}839	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {840		self.assertions.reserve_exact(capacity);841		self842	}843	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {844		self.sup = Some(super_obj);845		self846	}847848	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {849		self.assertions.push(tb!(assertion));850		self851	}852	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {853		let field_index = self.next_field_index;854		self.next_field_index = self.next_field_index.next();855		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)856	}857	/// Preset for common method definiton pattern:858	/// Create a hidden field with the function value.859	///860	/// `.field(name).hide().value(Val::function(value))`861	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {862		self.field(name).hide().value(Val::Func(value.into()));863		self864	}865	pub fn try_method(866		&mut self,867		name: impl Into<IStr>,868		value: impl Into<FuncVal>,869	) -> Result<&mut Self> {870		self.field(name).hide().try_value(Val::Func(value.into()))?;871		Ok(self)872	}873874	pub fn build(self) -> ObjValue {875		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {876			return ObjValue::new_empty();877		}878		ObjValue::new(OopObject::new(879			self.sup,880			Cc::new(self.map),881			Cc::new(self.assertions),882		))883	}884}885impl Default for ObjValueBuilder {886	fn default() -> Self {887		Self::with_capacity(0)888	}889}890891#[allow(clippy::module_name_repetitions)]892#[must_use = "value not added unless binding() was called"]893pub struct ObjMemberBuilder<Kind> {894	kind: Kind,895	name: IStr,896	add: bool,897	visibility: Visibility,898	original_index: FieldIndex,899	location: Option<Span>,900}901902#[allow(clippy::missing_const_for_fn)]903impl<Kind> ObjMemberBuilder<Kind> {904	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {905		Self {906			kind,907			name,908			original_index,909			add: false,910			visibility: Visibility::Normal,911			location: None,912		}913	}914915	pub const fn with_add(mut self, add: bool) -> Self {916		self.add = add;917		self918	}919	pub fn add(self) -> Self {920		self.with_add(true)921	}922	pub fn with_visibility(mut self, visibility: Visibility) -> Self {923		self.visibility = visibility;924		self925	}926	pub fn hide(self) -> Self {927		self.with_visibility(Visibility::Hidden)928	}929	pub fn with_location(mut self, location: Span) -> Self {930		self.location = Some(location);931		self932	}933	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {934		(935			self.kind,936			self.name,937			ObjMember {938				flags: ObjFieldFlags::new(self.add, self.visibility),939				original_index: self.original_index,940				invoke: binding,941				location: self.location,942			},943		)944	}945}946947pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);948impl ObjMemberBuilder<ValueBuilder<'_>> {949	/// Inserts value, replacing if it is already defined950	pub fn value(self, value: impl Into<Val>) {951		let (receiver, name, member) =952			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));953		let entry = receiver.0.map.entry(name);954		entry.insert(member);955	}956957	/// Tries to insert value, returns an error if it was already defined958	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {959		self.thunk(Thunk::evaluated(value.into()))960	}961	pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {962		self.binding(MaybeUnbound::Bound(value.into()))963	}964	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {965		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))966	}967	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {968		let (receiver, name, member) = self.build_member(binding);969		let location = member.location.clone();970		let old = receiver.0.map.insert(name.clone(), member);971		if old.is_some() {972			State::push(973				CallLocation(location.as_ref()),974				|| format!("field <{}> initializtion", name.clone()),975				|| bail!(DuplicateFieldName(name.clone())),976			)?;977		}978		Ok(())979	}980}981982pub struct ExtendBuilder<'v>(&'v mut ObjValue);983impl ObjMemberBuilder<ExtendBuilder<'_>> {984	pub fn value(self, value: impl Into<Val>) {985		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));986	}987	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {988		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));989	}990	pub fn binding(self, binding: MaybeUnbound) {991		let (receiver, name, member) = self.build_member(binding);992		let new = receiver.0.clone();993		*receiver.0 = new.extend_with_raw_member(name, member);994	}995}
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -5,7 +5,7 @@
 };
 
 use jrsonnet_gcmodule::Trace;
-use jrsonnet_parser::{CodeLocation, ExprLocation, Source};
+use jrsonnet_parser::{CodeLocation, Source, Span};
 
 use crate::{error::ErrorKind, Error};
 
@@ -380,7 +380,7 @@
 		error: &Error,
 	) -> Result<(), std::fmt::Error> {
 		struct ResetData {
-			loc: ExprLocation,
+			loc: Span,
 		}
 		use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};
 
@@ -399,7 +399,7 @@
 		}
 		let trace = &error.trace();
 		let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);
-		let mut last_location: Option<ExprLocation> = None;
+		let mut last_location: Option<Span> = None;
 		let mut flush_builder = |data: Option<ResetData>| {
 			use std::fmt::Write;
 			let mut out = String::new();
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -376,7 +376,7 @@
 				State, Val,
 				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},
 				Result, Context, typed::Typed,
-				parser::ExprLocation,
+				parser::Span,
 			};
 			const PARAMS: &'static [BuiltinParam] = &[
 				#(#params_desc)*
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -385,17 +385,16 @@
 #[derive(Clone, PartialEq, Eq, Trace)]
 #[trace(skip)]
 #[repr(C)]
-pub struct ExprLocation(pub Source, pub u32, pub u32);
-impl ExprLocation {
-	pub fn belongs_to(&self, other: &ExprLocation) -> bool {
+pub struct Span(pub Source, pub u32, pub u32);
+impl Span {
+	pub fn belongs_to(&self, other: &Span) -> bool {
 		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2
 	}
 }
 
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(ExprLocation, [u8; 16]);
+static_assertions::assert_eq_size!(Span, (usize, usize));
 
-impl Debug for ExprLocation {
+impl Debug for Span {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
 	}
@@ -403,19 +402,32 @@
 
 /// Holds AST expression and its location in source file
 #[derive(Clone, PartialEq, Trace)]
-pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);
+pub struct LocExpr(Rc<(Expr, Span)>);
+impl LocExpr {
+	pub fn new(expr: Expr, span: Span) -> Self {
+		Self(Rc::new((expr, span)))
+	}
+	#[inline]
+	pub fn span(&self) -> Span {
+		self.0 .1.clone()
+	}
+	#[inline]
+	pub fn expr(&self) -> &Expr {
+		&self.0 .0
+	}
+}
 
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(LocExpr, [u8; 24]);
+static_assertions::assert_eq_size!(LocExpr, usize);
 
 impl Debug for LocExpr {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		let expr = self.expr();
 		if f.alternate() {
-			write!(f, "{:#?}", self.0)?;
+			write!(f, "{:#?}", expr)?;
 		} else {
-			write!(f, "{:?}", self.0)?;
+			write!(f, "{:?}", expr)?;
 		}
-		write!(f, " from {:?}", self.1)?;
+		write!(f, " from {:?}", self.span())?;
 		Ok(())
 	}
 }
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -232,7 +232,7 @@
 		pub rule var_expr(s: &ParserSettings) -> Expr
 			= n:id() { expr::Expr::Var(n) }
 		pub rule id_loc(s: &ParserSettings) -> LocExpr
-			= a:position!() n:id() b:position!() { LocExpr(Rc::new(expr::Expr::Str(n)), ExprLocation(s.source.clone(), a as u32,b as u32)) }
+			= a:position!() n:id() b:position!() { LocExpr::new(expr::Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
 		pub rule if_then_else_expr(s: &ParserSettings) -> Expr
 			= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{
 				cond,
@@ -299,7 +299,7 @@
 		use UnaryOpType::*;
 		rule expr(s: &ParserSettings) -> LocExpr
 			= precedence! {
-				start:position!() v:@ end:position!() { LocExpr(Rc::new(v), ExprLocation(s.source.clone(), start as u32, end as u32)) }
+				start:position!() v:@ end:position!() { LocExpr::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:@ {
@@ -370,10 +370,7 @@
 /// Used for importstr values
 pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {
 	let len = str.len();
-	LocExpr(
-		Rc::new(Expr::Str(str)),
-		ExprLocation(settings.source.clone(), 0, len as u32),
-	)
+	LocExpr::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))
 }
 
 #[cfg(test)]
@@ -398,9 +395,9 @@
 
 	macro_rules! el {
 		($expr:expr, $from:expr, $to:expr$(,)?) => {
-			LocExpr(
-				std::rc::Rc::new($expr),
-				ExprLocation(
+			LocExpr::new(
+				$expr,
+				Span(
 					Source::new_virtual("<test>".into(), IStr::empty()),
 					$from,
 					$to,