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
before · crates/jrsonnet-macros/src/lib.rs
1use std::string::String;23use proc_macro2::TokenStream;4use quote::quote;5use syn::{6	parenthesized,7	parse::{Parse, ParseStream},8	parse_macro_input,9	punctuated::Punctuated,10	spanned::Spanned,11	token::{self, Comma},12	Attribute, DeriveInput, Error, Expr, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,13	PathArguments, Result, ReturnType, Token, Type,14};1516fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>17where18	Ident: PartialEq<I>,19{20	let attrs = attrs21		.iter()22		.filter(|a| a.path().is_ident(&ident))23		.collect::<Vec<_>>();24	if attrs.len() > 1 {25		return Err(Error::new(26			attrs[1].span(),27			"this attribute may be specified only once",28		));29	} else if attrs.is_empty() {30		return Ok(None);31	}32	let attr = attrs[0];33	let attr = attr.parse_args::<A>()?;3435	Ok(Some(attr))36}37fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)38where39	Ident: PartialEq<I>,40{41	attrs.retain(|a| !a.path().is_ident(&ident));42}4344fn path_is(path: &Path, needed: &str) -> bool {45	path.leading_colon.is_none()46		&& !path.segments.is_empty()47		&& path.segments.iter().last().unwrap().ident == needed48}4950fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {51	match ty {52		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {53			let args = &path.path.segments.iter().last().unwrap().arguments;54			Some(args)55		}56		_ => None,57	}58}5960fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {61	let Some(args) = type_is_path(ty, "Option") else {62		return Ok(None);63	};64	// It should have only on angle-bracketed param ("<String>"):65	let PathArguments::AngleBracketed(params) = args else {66		return Err(Error::new(args.span(), "missing option generic"));67	};68	let generic_arg = params.args.iter().next().unwrap();69	// This argument must be a type:70	let GenericArgument::Type(ty) = generic_arg else {71		return Err(Error::new(72			generic_arg.span(),73			"option generic should be a type",74		));75	};76	Ok(Some(ty))77}7879struct Field {80	attrs: Vec<Attribute>,81	name: Ident,82	_colon: Token![:],83	ty: Type,84}85impl Parse for Field {86	fn parse(input: ParseStream) -> syn::Result<Self> {87		Ok(Self {88			attrs: input.call(Attribute::parse_outer)?,89			name: input.parse()?,90			_colon: input.parse()?,91			ty: input.parse()?,92		})93	}94}9596mod kw {97	syn::custom_keyword!(fields);98	syn::custom_keyword!(rename);99	syn::custom_keyword!(flatten);100	syn::custom_keyword!(add);101	syn::custom_keyword!(hide);102	syn::custom_keyword!(ok);103}104105struct EmptyAttr;106impl Parse for EmptyAttr {107	fn parse(_input: ParseStream) -> Result<Self> {108		Ok(Self)109	}110}111112struct BuiltinAttrs {113	fields: Vec<Field>,114}115impl Parse for BuiltinAttrs {116	fn parse(input: ParseStream) -> syn::Result<Self> {117		if input.is_empty() {118			return Ok(Self { fields: Vec::new() });119		}120		input.parse::<kw::fields>()?;121		let fields;122		parenthesized!(fields in input);123		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;124		Ok(Self {125			fields: p.into_iter().collect(),126		})127	}128}129130enum Optionality {131	Required,132	Optional,133	Default(Expr),134}135136enum ArgInfo {137	Normal {138		ty: Box<Type>,139		optionality: Optionality,140		name: Option<String>,141		cfg_attrs: Vec<Attribute>,142	},143	Lazy {144		is_option: bool,145		name: Option<String>,146	},147	Context,148	Location,149	This,150}151152impl ArgInfo {153	fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {154		let FnArg::Typed(arg) = arg else {155			unreachable!()156		};157		let ident = match &arg.pat as &Pat {158			Pat::Ident(i) => Some(i.ident.clone()),159			_ => None,160		};161		let ty = &arg.ty;162		if type_is_path(ty, "Context").is_some() {163			return Ok(Self::Context);164		} else if type_is_path(ty, "CallLocation").is_some() {165			return Ok(Self::Location);166		} else if type_is_path(ty, "Thunk").is_some() {167			return Ok(Self::Lazy {168				is_option: false,169				name: ident.map(|v| v.to_string()),170			});171		}172173		match ty as &Type {174			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),175			_ => {}176		}177178		let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {179			remove_attr(&mut arg.attrs, "default");180			(Optionality::Default(default), ty.clone())181		} else if let Some(ty) = extract_type_from_option(ty)? {182			if type_is_path(ty, "Thunk").is_some() {183				return Ok(Self::Lazy {184					is_option: true,185					name: ident.map(|v| v.to_string()),186				});187			}188189			(Optionality::Optional, Box::new(ty.clone()))190		} else {191			(Optionality::Required, ty.clone())192		};193194		let cfg_attrs = arg195			.attrs196			.iter()197			.filter(|a| a.path().is_ident("cfg"))198			.cloned()199			.collect();200201		Ok(Self::Normal {202			ty,203			optionality,204			name: ident.map(|v| v.to_string()),205			cfg_attrs,206		})207	}208}209210#[proc_macro_attribute]211pub fn builtin(212	attr: proc_macro::TokenStream,213	item: proc_macro::TokenStream,214) -> proc_macro::TokenStream {215	let attr = parse_macro_input!(attr as BuiltinAttrs);216	let item_fn = parse_macro_input!(item as ItemFn);217218	match builtin_inner(attr, item_fn) {219		Ok(v) => v.into(),220		Err(e) => e.into_compile_error().into(),221	}222}223224#[allow(clippy::too_many_lines)]225fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {226	let ReturnType::Type(_, result) = &fun.sig.output else {227		return Err(Error::new(228			fun.sig.span(),229			"builtin should return something",230		));231	};232233	let name = fun.sig.ident.to_string();234	let args = fun235		.sig236		.inputs237		.iter_mut()238		.map(|arg| ArgInfo::parse(&name, arg))239		.collect::<Result<Vec<_>>>()?;240241	let params_desc = args.iter().filter_map(|a| match a {242		ArgInfo::Normal {243			optionality,244			name,245			cfg_attrs,246			..247		} => {248			let name = name249				.as_ref()250				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});251			let default = match optionality {252				Optionality::Required => quote!(ParamDefault::None),253				Optionality::Optional => quote!(ParamDefault::Exists),254				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),255			};256			Some(quote! {257				#(#cfg_attrs)*258				BuiltinParam::new(#name, #default),259			})260		}261		ArgInfo::Lazy { is_option, name } => {262			let name = name263				.as_ref()264				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});265			Some(quote! {266				BuiltinParam::new(#name, ParamDefault::exists(#is_option)),267			})268		}269		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,270	});271272	let mut id = 0usize;273	let pass = args274		.iter()275		.map(|a| match a {276			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {277				let cid = id;278				id += 1;279				(quote! {#cid}, a)280			}281			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {282				(quote! {compile_error!("should not use id")}, a)283			}284		})285		.map(|(id, a)| match a {286			ArgInfo::Normal {287				ty,288				optionality,289				name,290				cfg_attrs,291			} => {292				let name = name.as_ref().map_or("<unnamed>", String::as_str);293				let eval = quote! {jrsonnet_evaluator::State::push_description(294					|| format!("argument <{}> evaluation", #name),295					|| <#ty>::from_untyped(value.evaluate()?),296				)?};297				let value = match optionality {298					Optionality::Required => quote! {{299						let value = parsed[#id].as_ref().expect("args shape is checked");300						#eval301					},},302					Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {303						Some(#eval)304					} else {305						None306					},},307					Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {308						#eval309					} else {310						let v: #ty = #expr;311						v312					},},313				};314				quote! {315					#(#cfg_attrs)*316					#value317				}318			}319			ArgInfo::Lazy { is_option, .. } => {320				if *is_option {321					quote! {if let Some(value) = &parsed[#id] {322						Some(value.clone())323					} else {324						None325					},}326				} else {327					quote! {328						parsed[#id].as_ref().expect("args shape is correct").clone(),329					}330				}331			}332			ArgInfo::Context => quote! {ctx.clone(),},333			ArgInfo::Location => quote! {location,},334			ArgInfo::This => quote! {self,},335		});336337	let fields = attr.fields.iter().map(|field| {338		let attrs = &field.attrs;339		let name = &field.name;340		let ty = &field.ty;341		quote! {342			#(#attrs)*343			pub #name: #ty,344		}345	});346347	let name = &fun.sig.ident;348	let vis = &fun.vis;349	let static_ext = if attr.fields.is_empty() {350		quote! {351			impl #name {352				pub const INST: &'static dyn StaticBuiltin = &#name {};353			}354			impl StaticBuiltin for #name {}355		}356	} else {357		quote! {}358	};359	let static_derive_copy = if attr.fields.is_empty() {360		quote! {, Copy}361	} else {362		quote! {}363	};364365	Ok(quote! {366		#fun367368		#[doc(hidden)]369		#[allow(non_camel_case_types)]370		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]371		#vis struct #name {372			#(#fields)*373		}374		const _: () = {375			use ::jrsonnet_evaluator::{376				State, Val,377				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},378				Result, Context, typed::Typed,379				parser::ExprLocation,380			};381			const PARAMS: &'static [BuiltinParam] = &[382				#(#params_desc)*383			];384385			#static_ext386			impl Builtin for #name387			where388				Self: 'static389			{390				fn name(&self) -> &str {391					stringify!(#name)392				}393				fn params(&self) -> &[BuiltinParam] {394					PARAMS395				}396				#[allow(unused_variables)]397				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {398					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;399400					let result: #result = #name(#(#pass)*);401					<_ as Typed>::into_result(result)402				}403				fn as_any(&self) -> &dyn ::std::any::Any {404					self405				}406			}407		};408	})409}410411#[derive(Default)]412#[allow(clippy::struct_excessive_bools)]413struct TypedAttr {414	rename: Option<String>,415	flatten: bool,416	/// flatten(ok) strategy for flattened optionals417	/// field would be None in case of any parsing error (as in serde)418	flatten_ok: bool,419	// Should it be `field+:` instead of `field:`420	add: bool,421	// Should it be `field::` instead of `field:`422	hide: bool,423}424impl Parse for TypedAttr {425	fn parse(input: ParseStream) -> syn::Result<Self> {426		let mut out = Self::default();427		loop {428			let lookahead = input.lookahead1();429			if lookahead.peek(kw::rename) {430				input.parse::<kw::rename>()?;431				input.parse::<Token![=]>()?;432				let name = input.parse::<LitStr>()?;433				if out.rename.is_some() {434					return Err(Error::new(435						name.span(),436						"rename attribute may only be specified once",437					));438				}439				out.rename = Some(name.value());440			} else if lookahead.peek(kw::flatten) {441				input.parse::<kw::flatten>()?;442				out.flatten = true;443				if input.peek(token::Paren) {444					let content;445					parenthesized!(content in input);446					let lookahead = content.lookahead1();447					if lookahead.peek(kw::ok) {448						content.parse::<kw::ok>()?;449						out.flatten_ok = true;450					} else {451						return Err(lookahead.error());452					}453				}454			} else if lookahead.peek(kw::add) {455				input.parse::<kw::add>()?;456				out.add = true;457			} else if lookahead.peek(kw::hide) {458				input.parse::<kw::hide>()?;459				out.hide = true;460			} else if input.is_empty() {461				break;462			} else {463				return Err(lookahead.error());464			}465			if input.peek(Token![,]) {466				input.parse::<Token![,]>()?;467			} else {468				break;469			}470		}471		Ok(out)472	}473}474475struct TypedField {476	attr: TypedAttr,477	ident: Ident,478	ty: Type,479	is_option: bool,480}481impl TypedField {482	fn parse(field: &syn::Field) -> Result<Self> {483		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();484		let Some(ident) = field.ident.clone() else {485			return Err(Error::new(486				field.span(),487				"this field should appear in output object, but it has no visible name",488			));489		};490		let (is_option, ty) = extract_type_from_option(&field.ty)?491			.map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));492		if is_option && attr.flatten {493			if !attr.flatten_ok {494				return Err(Error::new(495					field.span(),496					"strategy should be set when flattening Option",497				));498			}499		} else if attr.flatten_ok {500			return Err(Error::new(501				field.span(),502				"flatten(ok) is only useable on optional fields",503			));504		}505506		Ok(Self {507			attr,508			ident,509			ty,510			is_option,511		})512	}513	/// None if this field is flattened in jsonnet output514	fn name(&self) -> Option<String> {515		if self.attr.flatten {516			return None;517		}518		Some(519			self.attr520				.rename521				.clone()522				.unwrap_or_else(|| self.ident.to_string()),523		)524	}525526	fn expand_field(&self) -> Option<TokenStream> {527		if self.is_option {528			return None;529		}530		let name = self.name()?;531		let ty = &self.ty;532		Some(quote! {533			(#name, <#ty as Typed>::TYPE)534		})535	}536	fn expand_parse(&self) -> TokenStream {537		let ident = &self.ident;538		let ty = &self.ty;539		if self.attr.flatten {540			// optional flatten is handled in same way as serde541			return if self.is_option {542				quote! {543					#ident: <#ty as TypedObj>::parse(&obj).ok(),544				}545			} else {546				quote! {547					#ident: <#ty as TypedObj>::parse(&obj)?,548				}549			};550		};551552		let name = self.name().unwrap();553		let value = if self.is_option {554			quote! {555				if let Some(value) = obj.get(#name.into())? {556					Some(<#ty as Typed>::from_untyped(value)?)557				} else {558					None559				}560			}561		} else {562			quote! {563				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?564			}565		};566567		quote! {568			#ident: #value,569		}570	}571	fn expand_serialize(&self) -> TokenStream {572		let ident = &self.ident;573		let ty = &self.ty;574		self.name().map_or_else(575			|| {576				if self.is_option {577					quote! {578						if let Some(value) = self.#ident {579							<#ty as TypedObj>::serialize(value, out)?;580						}581					}582				} else {583					quote! {584						<#ty as TypedObj>::serialize(self.#ident, out)?;585					}586				}587			},588			|name| {589				let hide = if self.attr.hide {590					quote! {.hide()}591				} else {592					quote! {}593				};594				let add = if self.attr.add {595					quote! {.add()}596				} else {597					quote! {}598				};599				if self.is_option {600					quote! {601						if let Some(value) = self.#ident {602							out.field(#name)603								#hide604								#add605								.try_value(<#ty as Typed>::into_untyped(value)?)?;606						}607					}608				} else {609					quote! {610						out.field(#name)611							#hide612							#add613							.try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;614					}615				}616			},617		)618	}619}620621#[proc_macro_derive(Typed, attributes(typed))]622pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {623	let input = parse_macro_input!(item as DeriveInput);624625	match derive_typed_inner(input) {626		Ok(v) => v.into(),627		Err(e) => e.to_compile_error().into(),628	}629}630631fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {632	let syn::Data::Struct(data) = &input.data else {633		return Err(Error::new(input.span(), "only structs supported"));634	};635636	let ident = &input.ident;637	let fields = data638		.fields639		.iter()640		.map(TypedField::parse)641		.collect::<Result<Vec<_>>>()?;642643	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();644645	let typed = {646		let fields = fields647			.iter()648			.filter_map(TypedField::expand_field)649			.collect::<Vec<_>>();650		quote! {651			impl #impl_generics Typed for #ident #ty_generics #where_clause {652				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[653					#(#fields,)*654				]);655656				fn from_untyped(value: Val) -> JrResult<Self> {657					let obj = value.as_obj().expect("shape is correct");658					Self::parse(&obj)659				}660661				fn into_untyped(value: Self) -> JrResult<Val> {662					let mut out = ObjValueBuilder::new();663					value.serialize(&mut out)?;664					Ok(Val::Obj(out.build()))665				}666667			}668		}669	};670671	let fields_parse = fields.iter().map(TypedField::expand_parse);672	let fields_serialize = fields673		.iter()674		.map(TypedField::expand_serialize)675		.collect::<Vec<_>>();676677	Ok(quote! {678		const _: () = {679			use ::jrsonnet_evaluator::{680				typed::{ComplexValType, Typed, TypedObj, CheckType},681				Val, State,682				error::{ErrorKind, Result as JrResult},683				ObjValueBuilder, ObjValue,684			};685686			#typed687688			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {689				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {690					#(#fields_serialize)*691692					Ok(())693				}694				fn parse(obj: &ObjValue) -> JrResult<Self> {695					Ok(Self {696						#(#fields_parse)*697					})698				}699			}700		};701	})702}703704struct FormatInput {705	formatting: LitStr,706	arguments: Vec<Expr>,707}708impl Parse for FormatInput {709	fn parse(input: ParseStream) -> Result<Self> {710		let formatting = input.parse()?;711		let mut arguments = Vec::new();712713		while input.peek(Token![,]) {714			input.parse::<Token![,]>()?;715			if input.is_empty() {716				// Trailing comma717				break;718			}719			let expr = input.parse()?;720			arguments.push(expr);721		}722723		if !input.is_empty() {724			return Err(syn::Error::new(input.span(), "unexpected trailing input"));725		}726727		Ok(Self {728			formatting,729			arguments,730		})731	}732}733fn is_format_str(i: &str) -> bool {734	let mut is_plain = true;735	// -1 = {736	// +1 = }737	let mut is_bracket = 0i8;738	for ele in i.chars() {739		match ele {740			'{' if is_bracket == -1 => {741				is_bracket = 0;742			}743			'}' if is_bracket == -1 => {744				is_plain = false;745				break;746			}747			'}' if is_bracket == 1 => {748				is_bracket = 0;749			}750			'{' if is_bracket == 1 => {751				is_plain = false;752				break;753			}754			'{' => {755				is_bracket = -1;756			}757			'}' => {758				is_bracket = 1;759			}760			_ if is_bracket != 0 => {761				is_plain = false;762				break;763			}764			_ => {}765		}766	}767	!is_plain || is_bracket != 0768}769impl FormatInput {770	fn expand(self) -> TokenStream {771		let format = self.formatting;772		if is_format_str(&format.value()) {773			let args = self.arguments;774			quote! {775				::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))776			}777		} else {778			if let Some(first) = self.arguments.first() {779				return syn::Error::new(780					first.span(),781					"string has no formatting codes, it should not have the arguments",782				)783				.into_compile_error();784			}785			quote! {786				::jrsonnet_evaluator::IStr::from(#format)787			}788		}789	}790}791792/// `IStr` formatting helper793///794/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`795/// This macro looks for formatting codes in the input string, and uses796/// `format!()` only when necessary797#[proc_macro]798pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {799	let input = parse_macro_input!(input as FormatInput);800	input.expand().into()801}
after · crates/jrsonnet-macros/src/lib.rs
1use std::string::String;23use proc_macro2::TokenStream;4use quote::quote;5use syn::{6	parenthesized,7	parse::{Parse, ParseStream},8	parse_macro_input,9	punctuated::Punctuated,10	spanned::Spanned,11	token::{self, Comma},12	Attribute, DeriveInput, Error, Expr, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,13	PathArguments, Result, ReturnType, Token, Type,14};1516fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>17where18	Ident: PartialEq<I>,19{20	let attrs = attrs21		.iter()22		.filter(|a| a.path().is_ident(&ident))23		.collect::<Vec<_>>();24	if attrs.len() > 1 {25		return Err(Error::new(26			attrs[1].span(),27			"this attribute may be specified only once",28		));29	} else if attrs.is_empty() {30		return Ok(None);31	}32	let attr = attrs[0];33	let attr = attr.parse_args::<A>()?;3435	Ok(Some(attr))36}37fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)38where39	Ident: PartialEq<I>,40{41	attrs.retain(|a| !a.path().is_ident(&ident));42}4344fn path_is(path: &Path, needed: &str) -> bool {45	path.leading_colon.is_none()46		&& !path.segments.is_empty()47		&& path.segments.iter().last().unwrap().ident == needed48}4950fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {51	match ty {52		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {53			let args = &path.path.segments.iter().last().unwrap().arguments;54			Some(args)55		}56		_ => None,57	}58}5960fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {61	let Some(args) = type_is_path(ty, "Option") else {62		return Ok(None);63	};64	// It should have only on angle-bracketed param ("<String>"):65	let PathArguments::AngleBracketed(params) = args else {66		return Err(Error::new(args.span(), "missing option generic"));67	};68	let generic_arg = params.args.iter().next().unwrap();69	// This argument must be a type:70	let GenericArgument::Type(ty) = generic_arg else {71		return Err(Error::new(72			generic_arg.span(),73			"option generic should be a type",74		));75	};76	Ok(Some(ty))77}7879struct Field {80	attrs: Vec<Attribute>,81	name: Ident,82	_colon: Token![:],83	ty: Type,84}85impl Parse for Field {86	fn parse(input: ParseStream) -> syn::Result<Self> {87		Ok(Self {88			attrs: input.call(Attribute::parse_outer)?,89			name: input.parse()?,90			_colon: input.parse()?,91			ty: input.parse()?,92		})93	}94}9596mod kw {97	syn::custom_keyword!(fields);98	syn::custom_keyword!(rename);99	syn::custom_keyword!(flatten);100	syn::custom_keyword!(add);101	syn::custom_keyword!(hide);102	syn::custom_keyword!(ok);103}104105struct EmptyAttr;106impl Parse for EmptyAttr {107	fn parse(_input: ParseStream) -> Result<Self> {108		Ok(Self)109	}110}111112struct BuiltinAttrs {113	fields: Vec<Field>,114}115impl Parse for BuiltinAttrs {116	fn parse(input: ParseStream) -> syn::Result<Self> {117		if input.is_empty() {118			return Ok(Self { fields: Vec::new() });119		}120		input.parse::<kw::fields>()?;121		let fields;122		parenthesized!(fields in input);123		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;124		Ok(Self {125			fields: p.into_iter().collect(),126		})127	}128}129130enum Optionality {131	Required,132	Optional,133	Default(Expr),134}135136enum ArgInfo {137	Normal {138		ty: Box<Type>,139		optionality: Optionality,140		name: Option<String>,141		cfg_attrs: Vec<Attribute>,142	},143	Lazy {144		is_option: bool,145		name: Option<String>,146	},147	Context,148	Location,149	This,150}151152impl ArgInfo {153	fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {154		let FnArg::Typed(arg) = arg else {155			unreachable!()156		};157		let ident = match &arg.pat as &Pat {158			Pat::Ident(i) => Some(i.ident.clone()),159			_ => None,160		};161		let ty = &arg.ty;162		if type_is_path(ty, "Context").is_some() {163			return Ok(Self::Context);164		} else if type_is_path(ty, "CallLocation").is_some() {165			return Ok(Self::Location);166		} else if type_is_path(ty, "Thunk").is_some() {167			return Ok(Self::Lazy {168				is_option: false,169				name: ident.map(|v| v.to_string()),170			});171		}172173		match ty as &Type {174			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),175			_ => {}176		}177178		let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {179			remove_attr(&mut arg.attrs, "default");180			(Optionality::Default(default), ty.clone())181		} else if let Some(ty) = extract_type_from_option(ty)? {182			if type_is_path(ty, "Thunk").is_some() {183				return Ok(Self::Lazy {184					is_option: true,185					name: ident.map(|v| v.to_string()),186				});187			}188189			(Optionality::Optional, Box::new(ty.clone()))190		} else {191			(Optionality::Required, ty.clone())192		};193194		let cfg_attrs = arg195			.attrs196			.iter()197			.filter(|a| a.path().is_ident("cfg"))198			.cloned()199			.collect();200201		Ok(Self::Normal {202			ty,203			optionality,204			name: ident.map(|v| v.to_string()),205			cfg_attrs,206		})207	}208}209210#[proc_macro_attribute]211pub fn builtin(212	attr: proc_macro::TokenStream,213	item: proc_macro::TokenStream,214) -> proc_macro::TokenStream {215	let attr = parse_macro_input!(attr as BuiltinAttrs);216	let item_fn = parse_macro_input!(item as ItemFn);217218	match builtin_inner(attr, item_fn) {219		Ok(v) => v.into(),220		Err(e) => e.into_compile_error().into(),221	}222}223224#[allow(clippy::too_many_lines)]225fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {226	let ReturnType::Type(_, result) = &fun.sig.output else {227		return Err(Error::new(228			fun.sig.span(),229			"builtin should return something",230		));231	};232233	let name = fun.sig.ident.to_string();234	let args = fun235		.sig236		.inputs237		.iter_mut()238		.map(|arg| ArgInfo::parse(&name, arg))239		.collect::<Result<Vec<_>>>()?;240241	let params_desc = args.iter().filter_map(|a| match a {242		ArgInfo::Normal {243			optionality,244			name,245			cfg_attrs,246			..247		} => {248			let name = name249				.as_ref()250				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});251			let default = match optionality {252				Optionality::Required => quote!(ParamDefault::None),253				Optionality::Optional => quote!(ParamDefault::Exists),254				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),255			};256			Some(quote! {257				#(#cfg_attrs)*258				BuiltinParam::new(#name, #default),259			})260		}261		ArgInfo::Lazy { is_option, name } => {262			let name = name263				.as_ref()264				.map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});265			Some(quote! {266				BuiltinParam::new(#name, ParamDefault::exists(#is_option)),267			})268		}269		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,270	});271272	let mut id = 0usize;273	let pass = args274		.iter()275		.map(|a| match a {276			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {277				let cid = id;278				id += 1;279				(quote! {#cid}, a)280			}281			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {282				(quote! {compile_error!("should not use id")}, a)283			}284		})285		.map(|(id, a)| match a {286			ArgInfo::Normal {287				ty,288				optionality,289				name,290				cfg_attrs,291			} => {292				let name = name.as_ref().map_or("<unnamed>", String::as_str);293				let eval = quote! {jrsonnet_evaluator::State::push_description(294					|| format!("argument <{}> evaluation", #name),295					|| <#ty>::from_untyped(value.evaluate()?),296				)?};297				let value = match optionality {298					Optionality::Required => quote! {{299						let value = parsed[#id].as_ref().expect("args shape is checked");300						#eval301					},},302					Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {303						Some(#eval)304					} else {305						None306					},},307					Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {308						#eval309					} else {310						let v: #ty = #expr;311						v312					},},313				};314				quote! {315					#(#cfg_attrs)*316					#value317				}318			}319			ArgInfo::Lazy { is_option, .. } => {320				if *is_option {321					quote! {if let Some(value) = &parsed[#id] {322						Some(value.clone())323					} else {324						None325					},}326				} else {327					quote! {328						parsed[#id].as_ref().expect("args shape is correct").clone(),329					}330				}331			}332			ArgInfo::Context => quote! {ctx.clone(),},333			ArgInfo::Location => quote! {location,},334			ArgInfo::This => quote! {self,},335		});336337	let fields = attr.fields.iter().map(|field| {338		let attrs = &field.attrs;339		let name = &field.name;340		let ty = &field.ty;341		quote! {342			#(#attrs)*343			pub #name: #ty,344		}345	});346347	let name = &fun.sig.ident;348	let vis = &fun.vis;349	let static_ext = if attr.fields.is_empty() {350		quote! {351			impl #name {352				pub const INST: &'static dyn StaticBuiltin = &#name {};353			}354			impl StaticBuiltin for #name {}355		}356	} else {357		quote! {}358	};359	let static_derive_copy = if attr.fields.is_empty() {360		quote! {, Copy}361	} else {362		quote! {}363	};364365	Ok(quote! {366		#fun367368		#[doc(hidden)]369		#[allow(non_camel_case_types)]370		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]371		#vis struct #name {372			#(#fields)*373		}374		const _: () = {375			use ::jrsonnet_evaluator::{376				State, Val,377				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},378				Result, Context, typed::Typed,379				parser::Span,380			};381			const PARAMS: &'static [BuiltinParam] = &[382				#(#params_desc)*383			];384385			#static_ext386			impl Builtin for #name387			where388				Self: 'static389			{390				fn name(&self) -> &str {391					stringify!(#name)392				}393				fn params(&self) -> &[BuiltinParam] {394					PARAMS395				}396				#[allow(unused_variables)]397				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {398					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;399400					let result: #result = #name(#(#pass)*);401					<_ as Typed>::into_result(result)402				}403				fn as_any(&self) -> &dyn ::std::any::Any {404					self405				}406			}407		};408	})409}410411#[derive(Default)]412#[allow(clippy::struct_excessive_bools)]413struct TypedAttr {414	rename: Option<String>,415	flatten: bool,416	/// flatten(ok) strategy for flattened optionals417	/// field would be None in case of any parsing error (as in serde)418	flatten_ok: bool,419	// Should it be `field+:` instead of `field:`420	add: bool,421	// Should it be `field::` instead of `field:`422	hide: bool,423}424impl Parse for TypedAttr {425	fn parse(input: ParseStream) -> syn::Result<Self> {426		let mut out = Self::default();427		loop {428			let lookahead = input.lookahead1();429			if lookahead.peek(kw::rename) {430				input.parse::<kw::rename>()?;431				input.parse::<Token![=]>()?;432				let name = input.parse::<LitStr>()?;433				if out.rename.is_some() {434					return Err(Error::new(435						name.span(),436						"rename attribute may only be specified once",437					));438				}439				out.rename = Some(name.value());440			} else if lookahead.peek(kw::flatten) {441				input.parse::<kw::flatten>()?;442				out.flatten = true;443				if input.peek(token::Paren) {444					let content;445					parenthesized!(content in input);446					let lookahead = content.lookahead1();447					if lookahead.peek(kw::ok) {448						content.parse::<kw::ok>()?;449						out.flatten_ok = true;450					} else {451						return Err(lookahead.error());452					}453				}454			} else if lookahead.peek(kw::add) {455				input.parse::<kw::add>()?;456				out.add = true;457			} else if lookahead.peek(kw::hide) {458				input.parse::<kw::hide>()?;459				out.hide = true;460			} else if input.is_empty() {461				break;462			} else {463				return Err(lookahead.error());464			}465			if input.peek(Token![,]) {466				input.parse::<Token![,]>()?;467			} else {468				break;469			}470		}471		Ok(out)472	}473}474475struct TypedField {476	attr: TypedAttr,477	ident: Ident,478	ty: Type,479	is_option: bool,480}481impl TypedField {482	fn parse(field: &syn::Field) -> Result<Self> {483		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();484		let Some(ident) = field.ident.clone() else {485			return Err(Error::new(486				field.span(),487				"this field should appear in output object, but it has no visible name",488			));489		};490		let (is_option, ty) = extract_type_from_option(&field.ty)?491			.map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));492		if is_option && attr.flatten {493			if !attr.flatten_ok {494				return Err(Error::new(495					field.span(),496					"strategy should be set when flattening Option",497				));498			}499		} else if attr.flatten_ok {500			return Err(Error::new(501				field.span(),502				"flatten(ok) is only useable on optional fields",503			));504		}505506		Ok(Self {507			attr,508			ident,509			ty,510			is_option,511		})512	}513	/// None if this field is flattened in jsonnet output514	fn name(&self) -> Option<String> {515		if self.attr.flatten {516			return None;517		}518		Some(519			self.attr520				.rename521				.clone()522				.unwrap_or_else(|| self.ident.to_string()),523		)524	}525526	fn expand_field(&self) -> Option<TokenStream> {527		if self.is_option {528			return None;529		}530		let name = self.name()?;531		let ty = &self.ty;532		Some(quote! {533			(#name, <#ty as Typed>::TYPE)534		})535	}536	fn expand_parse(&self) -> TokenStream {537		let ident = &self.ident;538		let ty = &self.ty;539		if self.attr.flatten {540			// optional flatten is handled in same way as serde541			return if self.is_option {542				quote! {543					#ident: <#ty as TypedObj>::parse(&obj).ok(),544				}545			} else {546				quote! {547					#ident: <#ty as TypedObj>::parse(&obj)?,548				}549			};550		};551552		let name = self.name().unwrap();553		let value = if self.is_option {554			quote! {555				if let Some(value) = obj.get(#name.into())? {556					Some(<#ty as Typed>::from_untyped(value)?)557				} else {558					None559				}560			}561		} else {562			quote! {563				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?564			}565		};566567		quote! {568			#ident: #value,569		}570	}571	fn expand_serialize(&self) -> TokenStream {572		let ident = &self.ident;573		let ty = &self.ty;574		self.name().map_or_else(575			|| {576				if self.is_option {577					quote! {578						if let Some(value) = self.#ident {579							<#ty as TypedObj>::serialize(value, out)?;580						}581					}582				} else {583					quote! {584						<#ty as TypedObj>::serialize(self.#ident, out)?;585					}586				}587			},588			|name| {589				let hide = if self.attr.hide {590					quote! {.hide()}591				} else {592					quote! {}593				};594				let add = if self.attr.add {595					quote! {.add()}596				} else {597					quote! {}598				};599				if self.is_option {600					quote! {601						if let Some(value) = self.#ident {602							out.field(#name)603								#hide604								#add605								.try_value(<#ty as Typed>::into_untyped(value)?)?;606						}607					}608				} else {609					quote! {610						out.field(#name)611							#hide612							#add613							.try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;614					}615				}616			},617		)618	}619}620621#[proc_macro_derive(Typed, attributes(typed))]622pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {623	let input = parse_macro_input!(item as DeriveInput);624625	match derive_typed_inner(input) {626		Ok(v) => v.into(),627		Err(e) => e.to_compile_error().into(),628	}629}630631fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {632	let syn::Data::Struct(data) = &input.data else {633		return Err(Error::new(input.span(), "only structs supported"));634	};635636	let ident = &input.ident;637	let fields = data638		.fields639		.iter()640		.map(TypedField::parse)641		.collect::<Result<Vec<_>>>()?;642643	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();644645	let typed = {646		let fields = fields647			.iter()648			.filter_map(TypedField::expand_field)649			.collect::<Vec<_>>();650		quote! {651			impl #impl_generics Typed for #ident #ty_generics #where_clause {652				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[653					#(#fields,)*654				]);655656				fn from_untyped(value: Val) -> JrResult<Self> {657					let obj = value.as_obj().expect("shape is correct");658					Self::parse(&obj)659				}660661				fn into_untyped(value: Self) -> JrResult<Val> {662					let mut out = ObjValueBuilder::new();663					value.serialize(&mut out)?;664					Ok(Val::Obj(out.build()))665				}666667			}668		}669	};670671	let fields_parse = fields.iter().map(TypedField::expand_parse);672	let fields_serialize = fields673		.iter()674		.map(TypedField::expand_serialize)675		.collect::<Vec<_>>();676677	Ok(quote! {678		const _: () = {679			use ::jrsonnet_evaluator::{680				typed::{ComplexValType, Typed, TypedObj, CheckType},681				Val, State,682				error::{ErrorKind, Result as JrResult},683				ObjValueBuilder, ObjValue,684			};685686			#typed687688			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {689				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {690					#(#fields_serialize)*691692					Ok(())693				}694				fn parse(obj: &ObjValue) -> JrResult<Self> {695					Ok(Self {696						#(#fields_parse)*697					})698				}699			}700		};701	})702}703704struct FormatInput {705	formatting: LitStr,706	arguments: Vec<Expr>,707}708impl Parse for FormatInput {709	fn parse(input: ParseStream) -> Result<Self> {710		let formatting = input.parse()?;711		let mut arguments = Vec::new();712713		while input.peek(Token![,]) {714			input.parse::<Token![,]>()?;715			if input.is_empty() {716				// Trailing comma717				break;718			}719			let expr = input.parse()?;720			arguments.push(expr);721		}722723		if !input.is_empty() {724			return Err(syn::Error::new(input.span(), "unexpected trailing input"));725		}726727		Ok(Self {728			formatting,729			arguments,730		})731	}732}733fn is_format_str(i: &str) -> bool {734	let mut is_plain = true;735	// -1 = {736	// +1 = }737	let mut is_bracket = 0i8;738	for ele in i.chars() {739		match ele {740			'{' if is_bracket == -1 => {741				is_bracket = 0;742			}743			'}' if is_bracket == -1 => {744				is_plain = false;745				break;746			}747			'}' if is_bracket == 1 => {748				is_bracket = 0;749			}750			'{' if is_bracket == 1 => {751				is_plain = false;752				break;753			}754			'{' => {755				is_bracket = -1;756			}757			'}' => {758				is_bracket = 1;759			}760			_ if is_bracket != 0 => {761				is_plain = false;762				break;763			}764			_ => {}765		}766	}767	!is_plain || is_bracket != 0768}769impl FormatInput {770	fn expand(self) -> TokenStream {771		let format = self.formatting;772		if is_format_str(&format.value()) {773			let args = self.arguments;774			quote! {775				::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))776			}777		} else {778			if let Some(first) = self.arguments.first() {779				return syn::Error::new(780					first.span(),781					"string has no formatting codes, it should not have the arguments",782				)783				.into_compile_error();784			}785			quote! {786				::jrsonnet_evaluator::IStr::from(#format)787			}788		}789	}790}791792/// `IStr` formatting helper793///794/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`795/// This macro looks for formatting codes in the input string, and uses796/// `format!()` only when necessary797#[proc_macro]798pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {799	let input = parse_macro_input!(input as FormatInput);800	input.expand().into()801}
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,