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
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -8,7 +8,7 @@
 
 use jrsonnet_gcmodule::{Cc, Trace, Weak};
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ExprLocation, Visibility};
+use jrsonnet_parser::{Span, Visibility};
 use rustc_hash::FxHashMap;
 
 use crate::{
@@ -135,7 +135,7 @@
 	flags: ObjFieldFlags,
 	original_index: FieldIndex,
 	pub invoke: MaybeUnbound,
-	pub location: Option<ExprLocation>,
+	pub location: Option<Span>,
 }
 
 pub trait ObjectAssertion: Trace {
@@ -896,7 +896,7 @@
 	add: bool,
 	visibility: Visibility,
 	original_index: FieldIndex,
-	location: Option<ExprLocation>,
+	location: Option<Span>,
 }
 
 #[allow(clippy::missing_const_for_fn)]
@@ -926,7 +926,7 @@
 	pub fn hide(self) -> Self {
 		self.with_visibility(Visibility::Hidden)
 	}
-	pub fn with_location(mut self, location: ExprLocation) -> Self {
+	pub fn with_location(mut self, location: Span) -> Self {
 		self.location = Some(location);
 		self
 	}
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
before · crates/jrsonnet-parser/src/expr.rs
1use std::{2	fmt::{self, Debug, Display},3	ops::Deref,4	rc::Rc,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;910use crate::source::Source;1112#[derive(Debug, PartialEq, Trace)]13pub enum FieldName {14	/// {fixed: 2}15	Fixed(IStr),16	/// {["dyn"+"amic"]: 3}17	Dyn(LocExpr),18}1920#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]21#[repr(u8)]22pub enum Visibility {23	/// :24	Normal,25	/// ::26	Hidden,27	/// :::28	Unhide,29}3031impl Visibility {32	pub fn is_visible(&self) -> bool {33		matches!(self, Self::Normal | Self::Unhide)34	}35}3637#[derive(Clone, Debug, PartialEq, Trace)]38pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);3940#[derive(Debug, PartialEq, Trace)]41pub struct FieldMember {42	pub name: FieldName,43	pub plus: bool,44	pub params: Option<ParamsDesc>,45	pub visibility: Visibility,46	pub value: LocExpr,47}4849#[derive(Debug, PartialEq, Trace)]50pub enum Member {51	Field(FieldMember),52	BindStmt(BindSpec),53	AssertStmt(AssertStmt),54}5556#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]57pub enum UnaryOpType {58	Plus,59	Minus,60	BitNot,61	Not,62}6364impl Display for UnaryOpType {65	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {66		use UnaryOpType::*;67		write!(68			f,69			"{}",70			match self {71				Plus => "+",72				Minus => "-",73				BitNot => "~",74				Not => "!",75			}76		)77	}78}7980#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]81pub enum BinaryOpType {82	Mul,83	Div,8485	/// Implemented as intrinsic, put here for completeness86	Mod,8788	Add,89	Sub,9091	Lhs,92	Rhs,9394	Lt,95	Gt,96	Lte,97	Gte,9899	BitAnd,100	BitOr,101	BitXor,102103	Eq,104	Neq,105106	And,107	Or,108	#[cfg(feature = "exp-null-coaelse")]109	NullCoaelse,110111	// Equialent to std.objectHasEx(a, b, true)112	In,113}114115impl Display for BinaryOpType {116	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {117		use BinaryOpType::*;118		write!(119			f,120			"{}",121			match self {122				Mul => "*",123				Div => "/",124				Mod => "%",125				Add => "+",126				Sub => "-",127				Lhs => "<<",128				Rhs => ">>",129				Lt => "<",130				Gt => ">",131				Lte => "<=",132				Gte => ">=",133				BitAnd => "&",134				BitOr => "|",135				BitXor => "^",136				Eq => "==",137				Neq => "!=",138				And => "&&",139				Or => "||",140				In => "in",141				#[cfg(feature = "exp-null-coaelse")]142				NullCoaelse => "??",143			}144		)145	}146}147148/// name, default value149#[derive(Debug, PartialEq, Trace)]150pub struct Param(pub Destruct, pub Option<LocExpr>);151152/// Defined function parameters153#[derive(Debug, Clone, PartialEq, Trace)]154pub struct ParamsDesc(pub Rc<Vec<Param>>);155156impl Deref for ParamsDesc {157	type Target = Vec<Param>;158	fn deref(&self) -> &Self::Target {159		&self.0160	}161}162163#[derive(Debug, PartialEq, Trace)]164pub struct ArgsDesc {165	pub unnamed: Vec<LocExpr>,166	pub named: Vec<(IStr, LocExpr)>,167}168impl ArgsDesc {169	pub fn new(unnamed: Vec<LocExpr>, named: Vec<(IStr, LocExpr)>) -> Self {170		Self { unnamed, named }171	}172}173174#[derive(Debug, Clone, PartialEq, Eq, Trace)]175pub enum DestructRest {176	/// ...rest177	Keep(IStr),178	/// ...179	Drop,180}181182#[derive(Debug, Clone, PartialEq, Trace)]183pub enum Destruct {184	Full(IStr),185	#[cfg(feature = "exp-destruct")]186	Skip,187	#[cfg(feature = "exp-destruct")]188	Array {189		start: Vec<Destruct>,190		rest: Option<DestructRest>,191		end: Vec<Destruct>,192	},193	#[cfg(feature = "exp-destruct")]194	Object {195		fields: Vec<(IStr, Option<Destruct>, Option<LocExpr>)>,196		rest: Option<DestructRest>,197	},198}199impl Destruct {200	/// Name of destructure, used for function parameter names201	pub fn name(&self) -> Option<IStr> {202		match self {203			Self::Full(name) => Some(name.clone()),204			#[cfg(feature = "exp-destruct")]205			_ => None,206		}207	}208	pub fn capacity_hint(&self) -> usize {209		#[cfg(feature = "exp-destruct")]210		fn cap_rest(rest: &Option<DestructRest>) -> usize {211			match rest {212				Some(DestructRest::Keep(_)) => 1,213				Some(DestructRest::Drop) => 0,214				None => 0,215			}216		}217		match self {218			Self::Full(_) => 1,219			#[cfg(feature = "exp-destruct")]220			Self::Skip => 0,221			#[cfg(feature = "exp-destruct")]222			Self::Array { start, rest, end } => {223				start.iter().map(Destruct::capacity_hint).sum::<usize>()224					+ end.iter().map(Destruct::capacity_hint).sum::<usize>()225					+ cap_rest(rest)226			}227			#[cfg(feature = "exp-destruct")]228			Self::Object { fields, rest } => {229				let mut out = 0;230				for (_, into, _) in fields {231					match into {232						Some(v) => out += v.capacity_hint(),233						// Field is destructured to default name234						None => out += 1,235					}236				}237				out + cap_rest(rest)238			}239		}240	}241}242243#[derive(Debug, Clone, PartialEq, Trace)]244pub enum BindSpec {245	Field {246		into: Destruct,247		value: LocExpr,248	},249	Function {250		name: IStr,251		params: ParamsDesc,252		value: LocExpr,253	},254}255impl BindSpec {256	pub fn capacity_hint(&self) -> usize {257		match self {258			BindSpec::Field { into, .. } => into.capacity_hint(),259			BindSpec::Function { .. } => 1,260		}261	}262}263264#[derive(Debug, PartialEq, Trace)]265pub struct IfSpecData(pub LocExpr);266267#[derive(Debug, PartialEq, Trace)]268pub struct ForSpecData(pub Destruct, pub LocExpr);269270#[derive(Debug, PartialEq, Trace)]271pub enum CompSpec {272	IfSpec(IfSpecData),273	ForSpec(ForSpecData),274}275276#[derive(Debug, PartialEq, Trace)]277pub struct ObjComp {278	pub pre_locals: Vec<BindSpec>,279	pub field: FieldMember,280	pub post_locals: Vec<BindSpec>,281	pub compspecs: Vec<CompSpec>,282}283284#[derive(Debug, PartialEq, Trace)]285pub enum ObjBody {286	MemberList(Vec<Member>),287	ObjComp(ObjComp),288}289290#[derive(Debug, PartialEq, Eq, Clone, Copy, Trace)]291pub enum LiteralType {292	This,293	Super,294	Dollar,295	Null,296	True,297	False,298}299300#[derive(Debug, PartialEq, Trace)]301pub struct SliceDesc {302	pub start: Option<LocExpr>,303	pub end: Option<LocExpr>,304	pub step: Option<LocExpr>,305}306307/// Syntax base308#[derive(Debug, PartialEq, Trace)]309pub enum Expr {310	Literal(LiteralType),311312	/// String value: "hello"313	Str(IStr),314	/// Number: 1, 2.0, 2e+20315	Num(f64),316	/// Variable name: test317	Var(IStr),318319	/// Array of expressions: [1, 2, "Hello"]320	Arr(Vec<LocExpr>),321	/// Array comprehension:322	/// ```jsonnet323	///  ingredients: [324	///    { kind: kind, qty: 4 / 3 }325	///    for kind in [326	///      'Honey Syrup',327	///      'Lemon Juice',328	///      'Farmers Gin',329	///    ]330	///  ],331	/// ```332	ArrComp(LocExpr, Vec<CompSpec>),333334	/// Object: {a: 2}335	Obj(ObjBody),336	/// Object extension: var1 {b: 2}337	ObjExtend(LocExpr, ObjBody),338339	/// (obj)340	Parened(LocExpr),341342	/// -2343	UnaryOp(UnaryOpType, LocExpr),344	/// 2 - 2345	BinaryOp(LocExpr, BinaryOpType, LocExpr),346	/// assert 2 == 2 : "Math is broken"347	AssertExpr(AssertStmt, LocExpr),348	/// local a = 2; { b: a }349	LocalExpr(Vec<BindSpec>, LocExpr),350351	/// import "hello"352	Import(LocExpr),353	/// importStr "file.txt"354	ImportStr(LocExpr),355	/// importBin "file.txt"356	ImportBin(LocExpr),357	/// error "I'm broken"358	ErrorStmt(LocExpr),359	/// a(b, c)360	Apply(LocExpr, ArgsDesc, bool),361	/// a[b], a.b, a?.b362	Index {363		indexable: LocExpr,364		parts: Vec<IndexPart>,365	},366	/// function(x) x367	Function(ParamsDesc, LocExpr),368	/// if true == false then 1 else 2369	IfElse {370		cond: IfSpecData,371		cond_then: LocExpr,372		cond_else: Option<LocExpr>,373	},374	Slice(LocExpr, SliceDesc),375}376377#[derive(Debug, PartialEq, Trace)]378pub struct IndexPart {379	pub value: LocExpr,380	#[cfg(feature = "exp-null-coaelse")]381	pub null_coaelse: bool,382}383384/// file, begin offset, end offset385#[derive(Clone, PartialEq, Eq, Trace)]386#[trace(skip)]387#[repr(C)]388pub struct ExprLocation(pub Source, pub u32, pub u32);389impl ExprLocation {390	pub fn belongs_to(&self, other: &ExprLocation) -> bool {391		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2392	}393}394395#[cfg(target_pointer_width = "64")]396static_assertions::assert_eq_size!(ExprLocation, [u8; 16]);397398impl Debug for ExprLocation {399	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {400		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)401	}402}403404/// Holds AST expression and its location in source file405#[derive(Clone, PartialEq, Trace)]406pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);407408#[cfg(target_pointer_width = "64")]409static_assertions::assert_eq_size!(LocExpr, [u8; 24]);410411impl Debug for LocExpr {412	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {413		if f.alternate() {414			write!(f, "{:#?}", self.0)?;415		} else {416			write!(f, "{:?}", self.0)?;417		}418		write!(f, " from {:?}", self.1)?;419		Ok(())420	}421}
after · crates/jrsonnet-parser/src/expr.rs
1use std::{2	fmt::{self, Debug, Display},3	ops::Deref,4	rc::Rc,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;910use crate::source::Source;1112#[derive(Debug, PartialEq, Trace)]13pub enum FieldName {14	/// {fixed: 2}15	Fixed(IStr),16	/// {["dyn"+"amic"]: 3}17	Dyn(LocExpr),18}1920#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]21#[repr(u8)]22pub enum Visibility {23	/// :24	Normal,25	/// ::26	Hidden,27	/// :::28	Unhide,29}3031impl Visibility {32	pub fn is_visible(&self) -> bool {33		matches!(self, Self::Normal | Self::Unhide)34	}35}3637#[derive(Clone, Debug, PartialEq, Trace)]38pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);3940#[derive(Debug, PartialEq, Trace)]41pub struct FieldMember {42	pub name: FieldName,43	pub plus: bool,44	pub params: Option<ParamsDesc>,45	pub visibility: Visibility,46	pub value: LocExpr,47}4849#[derive(Debug, PartialEq, Trace)]50pub enum Member {51	Field(FieldMember),52	BindStmt(BindSpec),53	AssertStmt(AssertStmt),54}5556#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]57pub enum UnaryOpType {58	Plus,59	Minus,60	BitNot,61	Not,62}6364impl Display for UnaryOpType {65	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {66		use UnaryOpType::*;67		write!(68			f,69			"{}",70			match self {71				Plus => "+",72				Minus => "-",73				BitNot => "~",74				Not => "!",75			}76		)77	}78}7980#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]81pub enum BinaryOpType {82	Mul,83	Div,8485	/// Implemented as intrinsic, put here for completeness86	Mod,8788	Add,89	Sub,9091	Lhs,92	Rhs,9394	Lt,95	Gt,96	Lte,97	Gte,9899	BitAnd,100	BitOr,101	BitXor,102103	Eq,104	Neq,105106	And,107	Or,108	#[cfg(feature = "exp-null-coaelse")]109	NullCoaelse,110111	// Equialent to std.objectHasEx(a, b, true)112	In,113}114115impl Display for BinaryOpType {116	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {117		use BinaryOpType::*;118		write!(119			f,120			"{}",121			match self {122				Mul => "*",123				Div => "/",124				Mod => "%",125				Add => "+",126				Sub => "-",127				Lhs => "<<",128				Rhs => ">>",129				Lt => "<",130				Gt => ">",131				Lte => "<=",132				Gte => ">=",133				BitAnd => "&",134				BitOr => "|",135				BitXor => "^",136				Eq => "==",137				Neq => "!=",138				And => "&&",139				Or => "||",140				In => "in",141				#[cfg(feature = "exp-null-coaelse")]142				NullCoaelse => "??",143			}144		)145	}146}147148/// name, default value149#[derive(Debug, PartialEq, Trace)]150pub struct Param(pub Destruct, pub Option<LocExpr>);151152/// Defined function parameters153#[derive(Debug, Clone, PartialEq, Trace)]154pub struct ParamsDesc(pub Rc<Vec<Param>>);155156impl Deref for ParamsDesc {157	type Target = Vec<Param>;158	fn deref(&self) -> &Self::Target {159		&self.0160	}161}162163#[derive(Debug, PartialEq, Trace)]164pub struct ArgsDesc {165	pub unnamed: Vec<LocExpr>,166	pub named: Vec<(IStr, LocExpr)>,167}168impl ArgsDesc {169	pub fn new(unnamed: Vec<LocExpr>, named: Vec<(IStr, LocExpr)>) -> Self {170		Self { unnamed, named }171	}172}173174#[derive(Debug, Clone, PartialEq, Eq, Trace)]175pub enum DestructRest {176	/// ...rest177	Keep(IStr),178	/// ...179	Drop,180}181182#[derive(Debug, Clone, PartialEq, Trace)]183pub enum Destruct {184	Full(IStr),185	#[cfg(feature = "exp-destruct")]186	Skip,187	#[cfg(feature = "exp-destruct")]188	Array {189		start: Vec<Destruct>,190		rest: Option<DestructRest>,191		end: Vec<Destruct>,192	},193	#[cfg(feature = "exp-destruct")]194	Object {195		fields: Vec<(IStr, Option<Destruct>, Option<LocExpr>)>,196		rest: Option<DestructRest>,197	},198}199impl Destruct {200	/// Name of destructure, used for function parameter names201	pub fn name(&self) -> Option<IStr> {202		match self {203			Self::Full(name) => Some(name.clone()),204			#[cfg(feature = "exp-destruct")]205			_ => None,206		}207	}208	pub fn capacity_hint(&self) -> usize {209		#[cfg(feature = "exp-destruct")]210		fn cap_rest(rest: &Option<DestructRest>) -> usize {211			match rest {212				Some(DestructRest::Keep(_)) => 1,213				Some(DestructRest::Drop) => 0,214				None => 0,215			}216		}217		match self {218			Self::Full(_) => 1,219			#[cfg(feature = "exp-destruct")]220			Self::Skip => 0,221			#[cfg(feature = "exp-destruct")]222			Self::Array { start, rest, end } => {223				start.iter().map(Destruct::capacity_hint).sum::<usize>()224					+ end.iter().map(Destruct::capacity_hint).sum::<usize>()225					+ cap_rest(rest)226			}227			#[cfg(feature = "exp-destruct")]228			Self::Object { fields, rest } => {229				let mut out = 0;230				for (_, into, _) in fields {231					match into {232						Some(v) => out += v.capacity_hint(),233						// Field is destructured to default name234						None => out += 1,235					}236				}237				out + cap_rest(rest)238			}239		}240	}241}242243#[derive(Debug, Clone, PartialEq, Trace)]244pub enum BindSpec {245	Field {246		into: Destruct,247		value: LocExpr,248	},249	Function {250		name: IStr,251		params: ParamsDesc,252		value: LocExpr,253	},254}255impl BindSpec {256	pub fn capacity_hint(&self) -> usize {257		match self {258			BindSpec::Field { into, .. } => into.capacity_hint(),259			BindSpec::Function { .. } => 1,260		}261	}262}263264#[derive(Debug, PartialEq, Trace)]265pub struct IfSpecData(pub LocExpr);266267#[derive(Debug, PartialEq, Trace)]268pub struct ForSpecData(pub Destruct, pub LocExpr);269270#[derive(Debug, PartialEq, Trace)]271pub enum CompSpec {272	IfSpec(IfSpecData),273	ForSpec(ForSpecData),274}275276#[derive(Debug, PartialEq, Trace)]277pub struct ObjComp {278	pub pre_locals: Vec<BindSpec>,279	pub field: FieldMember,280	pub post_locals: Vec<BindSpec>,281	pub compspecs: Vec<CompSpec>,282}283284#[derive(Debug, PartialEq, Trace)]285pub enum ObjBody {286	MemberList(Vec<Member>),287	ObjComp(ObjComp),288}289290#[derive(Debug, PartialEq, Eq, Clone, Copy, Trace)]291pub enum LiteralType {292	This,293	Super,294	Dollar,295	Null,296	True,297	False,298}299300#[derive(Debug, PartialEq, Trace)]301pub struct SliceDesc {302	pub start: Option<LocExpr>,303	pub end: Option<LocExpr>,304	pub step: Option<LocExpr>,305}306307/// Syntax base308#[derive(Debug, PartialEq, Trace)]309pub enum Expr {310	Literal(LiteralType),311312	/// String value: "hello"313	Str(IStr),314	/// Number: 1, 2.0, 2e+20315	Num(f64),316	/// Variable name: test317	Var(IStr),318319	/// Array of expressions: [1, 2, "Hello"]320	Arr(Vec<LocExpr>),321	/// Array comprehension:322	/// ```jsonnet323	///  ingredients: [324	///    { kind: kind, qty: 4 / 3 }325	///    for kind in [326	///      'Honey Syrup',327	///      'Lemon Juice',328	///      'Farmers Gin',329	///    ]330	///  ],331	/// ```332	ArrComp(LocExpr, Vec<CompSpec>),333334	/// Object: {a: 2}335	Obj(ObjBody),336	/// Object extension: var1 {b: 2}337	ObjExtend(LocExpr, ObjBody),338339	/// (obj)340	Parened(LocExpr),341342	/// -2343	UnaryOp(UnaryOpType, LocExpr),344	/// 2 - 2345	BinaryOp(LocExpr, BinaryOpType, LocExpr),346	/// assert 2 == 2 : "Math is broken"347	AssertExpr(AssertStmt, LocExpr),348	/// local a = 2; { b: a }349	LocalExpr(Vec<BindSpec>, LocExpr),350351	/// import "hello"352	Import(LocExpr),353	/// importStr "file.txt"354	ImportStr(LocExpr),355	/// importBin "file.txt"356	ImportBin(LocExpr),357	/// error "I'm broken"358	ErrorStmt(LocExpr),359	/// a(b, c)360	Apply(LocExpr, ArgsDesc, bool),361	/// a[b], a.b, a?.b362	Index {363		indexable: LocExpr,364		parts: Vec<IndexPart>,365	},366	/// function(x) x367	Function(ParamsDesc, LocExpr),368	/// if true == false then 1 else 2369	IfElse {370		cond: IfSpecData,371		cond_then: LocExpr,372		cond_else: Option<LocExpr>,373	},374	Slice(LocExpr, SliceDesc),375}376377#[derive(Debug, PartialEq, Trace)]378pub struct IndexPart {379	pub value: LocExpr,380	#[cfg(feature = "exp-null-coaelse")]381	pub null_coaelse: bool,382}383384/// file, begin offset, end offset385#[derive(Clone, PartialEq, Eq, Trace)]386#[trace(skip)]387#[repr(C)]388pub struct Span(pub Source, pub u32, pub u32);389impl Span {390	pub fn belongs_to(&self, other: &Span) -> bool {391		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2392	}393}394395static_assertions::assert_eq_size!(Span, (usize, usize));396397impl Debug for Span {398	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {399		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)400	}401}402403/// Holds AST expression and its location in source file404#[derive(Clone, PartialEq, Trace)]405pub struct LocExpr(Rc<(Expr, Span)>);406impl LocExpr {407	pub fn new(expr: Expr, span: Span) -> Self {408		Self(Rc::new((expr, span)))409	}410	#[inline]411	pub fn span(&self) -> Span {412		self.0 .1.clone()413	}414	#[inline]415	pub fn expr(&self) -> &Expr {416		&self.0 .0417	}418}419420static_assertions::assert_eq_size!(LocExpr, usize);421422impl Debug for LocExpr {423	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {424		let expr = self.expr();425		if f.alternate() {426			write!(f, "{:#?}", expr)?;427		} else {428			write!(f, "{:?}", expr)?;429		}430		write!(f, " from {:?}", self.span())?;431		Ok(())432	}433}
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,