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

difftreelog

refactor prepared signatures in IR

zvuulvvlYaroslav Bolyukin2026-03-21parent: #df5053d.patch.diff
in: master

15 files changed

modifiedcrates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -3,9 +3,9 @@
 
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_parser::{
-	ArgsDesc, AssertExpr, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, FieldName,
-	ForSpecData, IfElse, IfSpecData, ImportKind, ObjBody, Param, ParamsDesc,
-	ParserSettings, Slice, SliceDesc, Source, SourcePath, Spanned,
+	ArgsDesc, AssertExpr, AssertStmt, BindSpec, CompSpec, Destruct, Expr, ExprParam, ExprParams,
+	FieldMember, FieldName, ForSpecData, IfElse, IfSpecData, ImportKind, ObjBody, ParserSettings,
+	Slice, SliceDesc, Source, SourcePath, Spanned,
 };
 use rustc_hash::FxHashMap;
 
@@ -63,9 +63,9 @@
 			}
 		}
 	}
-	fn in_params(params: &ParamsDesc, out: &mut FoundImports) {
-		for Param(dest, default) in &*params.0 {
-			in_destruct(dest, out);
+	fn in_params(params: &ExprParams, out: &mut FoundImports) {
+		for ExprParam { destruct, default } in &*params.exprs {
+			in_destruct(destruct, out);
 			if let Some(expr) = default {
 				find_imports(expr, out);
 			}
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -180,6 +180,12 @@
 		assert!(old.is_none(), "variable bound twice in single context call");
 		self
 	}
+	pub fn binds(&mut self, bindings: FxHashMap<IStr, Thunk<Val>>) -> &mut Self {
+		for (k, v) in bindings {
+			self.bind(k, v);
+		}
+		self
+	}
 	pub fn build(self) -> Context {
 		if let Some(parent) = self.extend {
 			parent.extend_bindings(self.bindings)
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,7 +1,7 @@
 use std::{
 	cmp::Ordering,
 	convert::Infallible,
-	fmt::{Debug, Display},
+	fmt::{self, Debug, Display},
 };
 
 use jrsonnet_gcmodule::{Acyclic, Trace};
@@ -11,7 +11,7 @@
 use thiserror::Error;
 
 use crate::{
-	function::{builtin::ParamDefault, CallLocation},
+	function::{CallLocation, FunctionSignature, ParamDefault, ParamName},
 	stdlib::format::FormatError,
 	typed::TypeLocError,
 	val::ConvertNumValueError,
@@ -43,37 +43,7 @@
 			out.push_str(", ");
 		}
 		out.push_str(v as &str);
-	}
-	out
-}
-
-fn format_signature(sig: &FunctionSignature) -> String {
-	let mut out = String::new();
-	out.push_str("\nFunction has the following signature: ");
-	out.push('(');
-	if sig.is_empty() {
-		out.push_str("/*no arguments*/");
-	} else {
-		for (i, (name, default)) in sig.iter().enumerate() {
-			if i != 0 {
-				out.push_str(", ");
-			}
-			if let Some(name) = name {
-				out.push_str(name);
-			} else {
-				out.push_str("<unnamed>");
-			}
-			match default {
-				ParamDefault::None => {}
-				ParamDefault::Exists => out.push_str(" = <default>"),
-				ParamDefault::Literal(lit) => {
-					out.push_str(" = ");
-					out.push_str(lit);
-				}
-			}
-		}
 	}
-	out.push(')');
 	out
 }
 
@@ -103,8 +73,6 @@
 	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
 	heap.into_iter().map(|v| v.1).collect()
 }
-
-type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;
 
 /// Possible errors
 #[allow(missing_docs)]
@@ -148,13 +116,13 @@
 	#[error("only functions can be called, got {0}")]
 	OnlyFunctionsCanBeCalledGot(ValType),
 	#[error("parameter {0} is not defined")]
-	UnknownFunctionParameter(String),
+	UnknownFunctionParameter(IStr),
 	#[error("argument {0} is already bound")]
 	BindingParameterASecondTime(IStr),
-	#[error("too many args, function has {0}{sig}", sig = format_signature(.1))]
+	#[error("too many args, function has {0}\nFunction has the following signature: {1}")]
 	TooManyArgsFunctionHas(usize, FunctionSignature),
-	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]
-	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),
+	#[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]
+	FunctionParameterNotBoundInCall(ParamName, FunctionSignature),
 
 	#[error("external variable is not defined: {0}")]
 	UndefinedExternalVariable(IStr),
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -170,7 +170,7 @@
 			let value = value.clone();
 			let data = {
 				let fctx = fctx.clone();
-				Thunk!(move || name.map_or_else(
+				Thunk!(move || name.0.map_or_else(
 					|| evaluate(fctx.unwrap(), &value),
 					|name| evaluate_named(fctx.unwrap(), &value, name),
 				))
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -3,15 +3,27 @@
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
-	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, FieldName,
-	ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers, ParamsDesc, Spanned,
+	function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,
+	FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,
+	Spanned,
 };
 use jrsonnet_types::ValType;
 use rustc_hash::FxHashMap;
 
 use self::destructure::destruct;
 use crate::{
-	Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt, SupThis, Unbound, Val, arr::ArrValue, bail, destructure::evaluate_dest, error::{ErrorKind::*, suggest_object_fields}, evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op}, function::{CallLocation, FuncDesc, FuncVal, builtin::{ParamDefault, ParamName, ParamParse}}, gc::WithCapacityExt as _, in_frame, typed::Typed, val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk}, with_state
+	arr::ArrValue,
+	bail,
+	destructure::evaluate_dest,
+	error::{suggest_object_fields, ErrorKind::*},
+	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+	function::{CallLocation, FuncDesc, FuncVal},
+	gc::WithCapacityExt as _,
+	in_frame,
+	typed::Typed,
+	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
+	with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+	ResultExt, SupThis, Unbound, Val,
 };
 pub mod destructure;
 pub mod operator;
@@ -71,21 +83,12 @@
 pub fn evaluate_method(
 	ctx: Context,
 	name: IStr,
-	params: ParamsDesc,
+	params: ExprParams,
 	body: Rc<Spanned<Expr>>,
 ) -> Val {
 	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {
 		name,
 		ctx,
-		params_parse: params
-			.iter()
-			.map(|p| {
-				ParamParse::new(
-					p.0.name().map_or(ParamName::ANONYMOUS, ParamName::new),
-					ParamDefault::exists(p.1.is_some()),
-				)
-			})
-			.collect(),
 		params,
 		body,
 	})))
@@ -125,7 +128,7 @@
 			Val::Arr(list) => {
 				for item in list.iter_lazy() {
 					let fctx = Pending::new();
-					let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());
+					let mut new_bindings = FxHashMap::with_capacity(var.binds_len());
 					destruct(var, item, fctx.clone(), &mut new_bindings)?;
 					let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
 
@@ -178,7 +181,7 @@
 		fn bind(&self, sup_this: SupThis) -> Result<Context> {
 			let fctx = Context::new_future();
 			let mut new_bindings =
-				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());
+				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());
 			for b in self.locals.iter() {
 				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
 			}
@@ -249,7 +252,7 @@
 			struct UnboundMethod<B: Trace> {
 				uctx: B,
 				value: Rc<Spanned<Expr>>,
-				params: ParamsDesc,
+				params: ExprParams,
 				name: IStr,
 			}
 			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {
@@ -376,6 +379,13 @@
 	Ok(())
 }
 
+pub fn evaluate_named_param(ctx: Context, expr: &Spanned<Expr>, name: ParamName) -> Result<Val> {
+	match name.0 {
+		Some(name) => evaluate_named(ctx, expr, name),
+		None => evaluate(ctx, expr),
+	}
+}
+
 pub fn evaluate_named(ctx: Context, expr: &Spanned<Expr>, name: IStr) -> Result<Val> {
 	use Expr::*;
 	Ok(match &**expr {
@@ -551,7 +561,7 @@
 		})?,
 		LocalExpr(bindings, returned) => {
 			let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =
-				FxHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());
+				FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());
 			let fctx = Context::new_future();
 			for b in bindings {
 				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -1,82 +1,25 @@
 use std::any::Any;
+use std::fmt;
 
 use jrsonnet_gcmodule::{cc_dyn, Acyclic, Trace, TraceBox};
 use jrsonnet_interner::IStr;
+use jrsonnet_parser::function::{FunctionSignature, ParamDefault, ParamName, ParamParse};
 
 use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
 use crate::{Context, Result, Val};
 
-#[derive(Clone, Acyclic)]
-pub struct ParamName(Option<IStr>);
-impl ParamName {
-	pub const ANONYMOUS: Self = Self(None);
-	pub fn new(name: IStr) -> Self {
-		Self(Some(name))
-	}
-	pub fn as_str(&self) -> Option<&str> {
-		self.0.as_deref()
-	}
-	pub fn is_anonymous(&self) -> bool {
-		self.0.is_none()
-	}
-}
-impl PartialEq<IStr> for ParamName {
-	fn eq(&self, other: &IStr) -> bool {
-		self.0
-			.as_ref()
-			.map_or(false, |s| s.as_bytes() == other.as_bytes())
-	}
-}
-
-#[derive(Clone, Copy, Debug, Acyclic)]
-pub enum ParamDefault {
-	None,
-	Exists,
-	Literal(&'static str),
-}
-impl ParamDefault {
-	pub const fn exists(is_exists: bool) -> Self {
-		if is_exists {
-			Self::Exists
-		} else {
-			Self::None
-		}
-	}
-}
-
 #[macro_export]
 macro_rules! params {
 	(@name unnamed) => { ParamName::ANONYMOUS };
 	(@name named $name:literal) => { ParamName::new($crate::IStr::from($name)) };
 	($($(#[$meta:meta])* [$kind:ident $(($lit:literal))? => $default:expr]),* $(,)?) => {
 		thread_local! {
-			static PARAMS: [ParamParse; { const N: usize = <[u8]>::len(&[$($(#[$meta])* 0u8),*]); N }] = [
+			static PARAMS: FunctionSignature = FunctionSignature::new([
 				$($(#[$meta])* ParamParse::new(params!(@name $kind $($lit)?), $default)),*
-			];
+			].into());
 		}
 	};
-}
-
-#[derive(Clone, Acyclic)]
-pub struct ParamParse {
-	name: ParamName,
-	default: ParamDefault,
 }
-impl ParamParse {
-	pub fn new(name: ParamName, default: ParamDefault) -> Self {
-		Self { name, default }
-	}
-	/// Parameter name for named call parsing
-	pub fn name(&self) -> &ParamName {
-		&self.name
-	}
-	pub fn default(&self) -> ParamDefault {
-		self.default
-	}
-	pub fn has_default(&self) -> bool {
-		!matches!(self.default, ParamDefault::None)
-	}
-}
 
 cc_dyn!(
 	#[derive(Clone)]
@@ -89,7 +32,7 @@
 		self.0.name()
 	}
 
-	fn params(&self) -> &[ParamParse] {
+	fn params(&self) -> FunctionSignature {
 		self.0.params()
 	}
 
@@ -109,7 +52,7 @@
 	/// Function name to be used in stack traces
 	fn name(&self) -> &str;
 	/// Parameter names for named calls
-	fn params(&self) -> &[ParamParse];
+	fn params(&self) -> FunctionSignature;
 	/// Call the builtin
 	fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val>;
 
@@ -126,20 +69,19 @@
 
 #[derive(Trace)]
 pub struct NativeCallback {
-	pub(crate) params: Vec<ParamParse>,
+	pub(crate) params: FunctionSignature,
 	handler: TraceBox<dyn NativeCallbackHandler>,
 }
 impl NativeCallback {
 	#[deprecated = "prefer using builtins directly, use this interface only for bindings"]
 	pub fn new(params: Vec<String>, handler: impl NativeCallbackHandler) -> Self {
 		Self {
-			params: params
-				.into_iter()
-				.map(|n| ParamParse {
-					name: ParamName::new(n.into()),
-					default: ParamDefault::None,
-				})
-				.collect(),
+			params: FunctionSignature::new(
+				params
+					.into_iter()
+					.map(|n| ParamParse::new(ParamName::new(n.into()), ParamDefault::None))
+					.collect(),
+			),
 			handler: TraceBox(Box::new(handler)),
 		}
 	}
@@ -152,12 +94,12 @@
 		"<native>"
 	}
 
-	fn params(&self) -> &[ParamParse] {
-		&self.params
+	fn params(&self) -> FunctionSignature {
+		self.params.clone()
 	}
 
 	fn call(&self, ctx: Context, _loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val> {
-		let args = parse_builtin_call(ctx, &self.params, args, true)?;
+		let args = parse_builtin_call(ctx, self.params.clone(), args, true)?;
 		let args = args
 			.into_iter()
 			.map(|a| a.expect("legacy natives have no default params"))
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -5,23 +5,26 @@
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{Destruct, Expr, ParamsDesc, Span, Spanned};
+use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};
 
 use self::{
 	arglike::OptionalContext,
-	builtin::{Builtin, ParamParse, StaticBuiltin},
+	builtin::{Builtin, StaticBuiltin},
 	native::NativeDesc,
 	parse::{parse_default_function_call, parse_function_call},
 };
 use crate::{
-	bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,
-	ContextBuilder, Result, Thunk, Val,
+	bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, params,
+	Context, ContextBuilder, Result, Thunk, Val,
 };
 
 pub mod arglike;
 pub mod builtin;
 pub mod native;
 pub mod parse;
+pub mod prepared;
+
+pub use jrsonnet_parser::function::*;
 
 /// Function callsite location.
 /// Either from other jsonnet code, specified by expression location, or from native (without location).
@@ -66,12 +69,9 @@
 	pub ctx: Context,
 
 	/// Function parameter definition
-	pub params: ParamsDesc,
+	pub params: ExprParams,
 	/// Function body
 	pub body: Rc<Spanned<Expr>>,
-
-	#[educe(PartialEq = false, Debug = false)]
-	pub(crate) params_parse: Vec<ParamParse>,
 }
 impl FuncDesc {
 	/// Create body context, but fill arguments without defaults with lazy error
@@ -139,24 +139,18 @@
 		Self::StaticBuiltin(static_builtin)
 	}
 
-	pub fn params(&self) -> &[ParamParse] {
+	pub fn params(&self) -> FunctionSignature {
 		match self {
 			Self::Id => ID.params(),
 			Self::StaticBuiltin(i) => i.params(),
 			Self::Builtin(i) => i.params(),
-			Self::Normal(p) => &p.params_parse,
-			Self::Thunk(_) => &[],
+			Self::Normal(p) => p.params.signature.clone(),
+			Self::Thunk(_) => FunctionSignature::empty(),
 		}
 	}
 	/// Amount of non-default required arguments
 	pub fn params_len(&self) -> usize {
-		match self {
-			Self::Id => 1,
-			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),
-			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default()).count(),
-			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default()).count(),
-			Self::Thunk(_) => 0,
-		}
+		self.params().iter().filter(|p| !p.has_default()).count()
 	}
 	/// Function name, as defined in code.
 	pub fn name(&self) -> IStr {
@@ -185,8 +179,8 @@
 				evaluate(body_ctx, &func.body)
 			}
 			Self::Thunk(thunk) => {
-				if args.is_empty() {
-					bail!(TooManyArgsFunctionHas(0, vec![],))
+				if !args.is_empty() {
+					bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))
 				}
 				thunk.evaluate()
 			}
@@ -223,12 +217,13 @@
 				if desc.params.len() != 1 {
 					return false;
 				}
-				let param = &desc.params[0];
-				if param.1.is_some() {
+				let param = &desc.params.exprs[0];
+				if param.default.is_some() {
 					return false;
 				}
+
 				#[allow(clippy::infallible_destructuring_match)]
-				let id = match &param.0 {
+				let id = match &param.destruct {
 					Destruct::Full(id) => id,
 					#[cfg(feature = "exp-destruct")]
 					_ => return false,
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,16 +1,15 @@
 use std::mem::replace;
 
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::ParamsDesc;
+use jrsonnet_parser::{function::FunctionSignature, ExprParams};
 use rustc_hash::FxHashMap;
 
-use super::{arglike::ArgsLike, builtin::ParamParse};
+use super::arglike::ArgsLike;
 use crate::{
 	bail,
 	destructure::destruct,
 	error::{ErrorKind::*, Result},
-	evaluate_named,
-	function::builtin::ParamDefault,
+	evaluate_named, evaluate_named_param,
 	gc::WithCapacityExt as _,
 	Context, Pending, Thunk, Val,
 };
@@ -26,19 +25,15 @@
 pub fn parse_function_call(
 	ctx: Context,
 	body_ctx: Context,
-	params: &ParamsDesc,
+	params: &ExprParams,
 	args: &dyn ArgsLike,
 	tailstrict: bool,
 ) -> Result<Context> {
-	let mut passed_args =
-		FxHashMap::with_capacity(params.iter().map(|p| p.0.capacity_hint()).sum());
-	if args.unnamed_len() > params.len() {
+	let mut passed_args = FxHashMap::with_capacity(params.binds_len());
+	if args.unnamed_len() > params.signature.len() {
 		bail!(TooManyArgsFunctionHas(
-			params.len(),
-			params
-				.iter()
-				.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
-				.collect()
+			params.signature.len(),
+			params.signature.clone(),
 		))
 	}
 
@@ -46,9 +41,8 @@
 	let mut filled_positionals = 0;
 
 	args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {
-		let name = params[id].0.clone();
 		destruct(
-			&name,
+			&params.exprs[id].destruct,
 			arg,
 			Pending::new_filled(ctx.clone()),
 			&mut passed_args,
@@ -59,8 +53,8 @@
 
 	args.named_iter(ctx, tailstrict, &mut |name, value| {
 		// FIXME: O(n) for arg existence check
-		if !params.iter().any(|p| p.0.name().as_ref() == Some(name)) {
-			bail!(UnknownFunctionParameter((name as &str).to_owned()));
+		if !params.exprs.iter().any(|p| &p.destruct.name() == name) {
+			bail!(UnknownFunctionParameter(name.clone()));
 		}
 		if passed_args.insert(name.clone(), value).is_some() {
 			bail!(BindingParameterASecondTime(name.clone()));
@@ -73,14 +67,16 @@
 		// Some args are unset, but maybe we have defaults for them
 		// Default values should be created in newly created context
 		let fctx = Context::new_future();
-		let mut defaults = FxHashMap::with_capacity(
-			params.iter().map(|p| p.0.capacity_hint()).sum::<usize>()
-				- filled_named
-				- filled_positionals,
-		);
+		let mut defaults =
+			FxHashMap::with_capacity(params.binds_len() - filled_named - filled_positionals);
 
-		for (idx, param) in params.iter().enumerate().filter(|p| p.1 .1.is_some()) {
-			if let Some(name) = param.0.name() {
+		for (idx, into, default) in params
+			.exprs
+			.iter()
+			.enumerate()
+			.filter_map(|(i, p)| Some((i, &p.destruct, p.default.as_ref()?)))
+		{
+			if let Some(name) = into.name().0 {
 				if passed_args.contains_key(&name) {
 					continue;
 				}
@@ -89,17 +85,17 @@
 			}
 
 			destruct(
-				&param.0,
+				&into,
 				{
 					let ctx = fctx.clone();
-					let name = param.0.name().unwrap_or_else(|| "<destruct>".into());
-					let value = param.1.clone().expect("default exists");
-					Thunk!(move || evaluate_named(ctx.unwrap(), &value, name))
+					let name = into.name();
+					let value = default.clone();
+					Thunk!(move || evaluate_named_param(ctx.unwrap(), &value, name))
 				},
 				fctx.clone(),
 				&mut defaults,
 			)?;
-			if param.0.name().is_some() {
+			if !into.name().is_anonymous() {
 				filled_named += 1;
 			} else {
 				filled_positionals += 1;
@@ -108,20 +104,17 @@
 
 		// Some args still weren't filled
 		if filled_named + filled_positionals != params.len() {
-			for param in params.iter().skip(args.unnamed_len()) {
+			for param in params.exprs.iter().skip(args.unnamed_len()) {
 				let mut found = false;
 				args.named_names(&mut |name| {
-					if Some(name) == param.0.name().as_ref() {
+					if &param.destruct.name() == name {
 						found = true;
 					}
 				});
 				if !found {
 					bail!(FunctionParameterNotBoundInCall(
-						param.0.clone().name(),
-						params
-							.iter()
-							.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
-							.collect()
+						param.destruct.name(),
+						params.signature.clone()
 					));
 				}
 			}
@@ -147,19 +140,13 @@
 /// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
 pub fn parse_builtin_call(
 	ctx: Context,
-	params: &[ParamParse],
+	params: FunctionSignature,
 	args: &dyn ArgsLike,
 	tailstrict: bool,
 ) -> Result<Vec<Option<Thunk<Val>>>> {
 	let mut passed_args: Vec<Option<Thunk<Val>>> = vec![None; params.len()];
 	if args.unnamed_len() > params.len() {
-		bail!(TooManyArgsFunctionHas(
-			params.len(),
-			params
-				.iter()
-				.map(|p| (p.name().as_str().map(IStr::from), p.default()))
-				.collect()
-		))
+		bail!(TooManyArgsFunctionHas(params.len(), params,))
 	}
 
 	let mut filled_args = 0;
@@ -175,7 +162,7 @@
 		let id = params
 			.iter()
 			.position(|p| p.name() == name)
-			.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
+			.ok_or_else(|| UnknownFunctionParameter(name.clone()))?;
 		if replace(&mut passed_args[id], Some(arg)).is_some() {
 			bail!(BindingParameterASecondTime(name.clone()));
 		}
@@ -202,11 +189,8 @@
 				});
 				if !found {
 					bail!(FunctionParameterNotBoundInCall(
-						param.name().as_str().map(IStr::from),
-						params
-							.iter()
-							.map(|p| (p.name().as_str().map(IStr::from), p.default()))
-							.collect()
+						param.name().clone(),
+						params,
 					));
 				}
 			}
@@ -218,36 +202,33 @@
 
 /// Creates Context, which has all argument default values applied
 /// and with unbound values causing error to be returned
-pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Result<Context> {
+pub fn parse_default_function_call(body_ctx: Context, params: &ExprParams) -> Result<Context> {
 	let fctx = Context::new_future();
 
-	let mut bindings = FxHashMap::with_capacity(params.iter().map(|p| p.0.capacity_hint()).sum());
+	let mut bindings = FxHashMap::with_capacity(params.binds_len());
 
-	for param in params.iter() {
-		if let Some(v) = &param.1 {
+	for param in params.exprs.iter() {
+		if let Some(v) = &param.default {
 			destruct(
-				&param.0.clone(),
+				&param.destruct.clone(),
 				{
 					let ctx = fctx.clone();
-					let name = param.0.name().unwrap_or_else(|| "<destruct>".into());
+					let name = param.destruct.name();
 					let value = v.clone();
-					Thunk!(move || evaluate_named(ctx.unwrap(), &value, name))
+					Thunk!(move || evaluate_named_param(ctx.unwrap(), &value, name))
 				},
 				fctx.clone(),
 				&mut bindings,
 			)?;
 		} else {
 			destruct(
-				&param.0,
+				&param.destruct,
 				{
-					let param_name = param.0.name().unwrap_or_else(|| "<destruct>".into());
+					let param_name = param.destruct.name();
 					let params = params.clone();
 					Thunk!(move || Err(FunctionParameterNotBoundInCall(
-						Some(param_name),
-						params
-							.iter()
-							.map(|p| (p.0.name(), ParamDefault::exists(p.1.is_some())))
-							.collect(),
+						param_name,
+						params.signature.clone()
 					)
 					.into()))
 				},
addedcrates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -0,0 +1,165 @@
+use jrsonnet_parser::function::FunctionSignature;
+use jrsonnet_parser::{ExprParams, IStr};
+use rustc_hash::{FxHashMap, FxHashSet};
+
+use crate::destructure::destruct;
+use crate::gc::WithCapacityExt;
+use crate::val::ThunkValue as _;
+use crate::{bail, error::ErrorKind::*, Result};
+use crate::{evaluate_named, evaluate_named_param, Context, ContextBuilder, Pending, Thunk, Val};
+
+pub struct PreparedCall {
+	// Param, named input.
+	named: Vec<(usize, usize)>,
+	defaults: Vec<usize>,
+}
+
+pub fn prepare_call(
+	params: FunctionSignature,
+	unnamed: usize,
+	named: &[IStr],
+) -> Result<PreparedCall> {
+	if unnamed > params.len() {
+		bail!(TooManyArgsFunctionHas(params.len(), params))
+	}
+
+	let expected_defaults = params.len() - unnamed - named.len();
+	let mut ops = PreparedCall {
+		named: Vec::with_capacity(named.len()),
+		defaults: Vec::with_capacity(expected_defaults),
+	};
+
+	// FIXME: bitmask
+	let mut passed: FxHashSet<usize> = (0..unnamed).collect();
+
+	for (input_id, name) in named.iter().enumerate() {
+		// FIXME: O(n) for arg existence check
+		let Some(param_idx) = params.iter().position(|p| p.name() == name) else {
+			bail!(UnknownFunctionParameter(name.clone()));
+		};
+		if !passed.insert(param_idx) {
+			bail!(BindingParameterASecondTime(name.clone()));
+		}
+		ops.named.push((param_idx, input_id));
+	}
+
+	if named.len() + unnamed < params.len() {
+		let mut defaults = 0;
+
+		for (param_id, param) in params
+			.iter()
+			.enumerate()
+			.skip(unnamed)
+			.filter(|p| p.1.has_default())
+		{
+			// Skip already passed parameters
+			if !param.name().is_anonymous() && passed.contains(&param_id) {
+				continue;
+			}
+			defaults += 1;
+
+			ops.defaults.push(param_id);
+		}
+
+		// Some args still weren't filled
+		if defaults != expected_defaults {
+			for param in params.iter().skip(unnamed) {
+				let mut found = false;
+				for name in named {
+					if param.name() == name {
+						found = true;
+					}
+				}
+				if !found {
+					bail!(FunctionParameterNotBoundInCall(
+						param.name().clone(),
+						params
+					));
+				}
+			}
+			unreachable!();
+		}
+	}
+
+	Ok(ops)
+}
+pub fn parse_prepared_function_call(
+	body_ctx: Context,
+	prepared: &PreparedCall,
+	params: &ExprParams,
+	unnamed: &[Thunk<Val>],
+	named: &[Thunk<Val>],
+) -> Result<Context> {
+	let mut passed_args = FxHashMap::with_capacity(params.binds_len());
+
+	let destruct_ctx = Pending::new();
+
+	for (param_idx, unnamed) in unnamed.iter().enumerate() {
+		destruct(
+			&params.exprs[param_idx].destruct,
+			unnamed.clone(),
+			destruct_ctx.clone(),
+			&mut passed_args,
+		)?;
+	}
+
+	for (param_idx, arg_idx) in prepared.named.iter().copied() {
+		destruct(
+			&params.exprs[param_idx].destruct,
+			named[arg_idx].clone(),
+			destruct_ctx.clone(),
+			&mut passed_args,
+		)?;
+	}
+
+	if prepared.defaults.is_empty() {
+		let body_ctx = body_ctx
+			.extend_bindings(passed_args)
+			.into_future(destruct_ctx);
+		Ok(body_ctx)
+	} else {
+		let fctx = Context::new_future();
+		let mut defaults = FxHashMap::with_capacity(params.binds_len() - passed_args.len());
+		for param_idx in prepared.defaults.iter().copied() {
+			// let param = params.0.rc_idx(param_idx);
+			destruct(
+				&params.exprs[param_idx].destruct,
+				{
+					let ctx = fctx.clone();
+					let params = params.clone();
+					Thunk!(move || {
+						let param = &params.exprs[param_idx];
+						let name = param.destruct.name();
+						let value = param.default.as_ref().expect("default exists");
+						evaluate_named_param(ctx.unwrap(), value, name)
+					})
+				},
+				fctx.clone(),
+				&mut defaults,
+			)?;
+		}
+
+		let mut ctx = ContextBuilder::extend(body_ctx);
+		ctx.binds(passed_args);
+		ctx.binds(defaults);
+		Ok(ctx.build().into_future(fctx).into_future(destruct_ctx))
+	}
+}
+pub fn parse_prepared_builtin_call(
+	prepared: &PreparedCall,
+	params: FunctionSignature,
+	unnamed: &[Thunk<Val>],
+	named: &[Thunk<Val>],
+) -> Result<Vec<Option<Thunk<Val>>>> {
+	let mut passed_args = vec![None; params.len()];
+
+	for (param_idx, unnamed) in unnamed.iter().enumerate() {
+		passed_args[param_idx] = Some(unnamed.clone());
+	}
+
+	for (param_idx, arg_idx) in prepared.named.iter().copied() {
+		passed_args[param_idx] = Some(named[arg_idx].clone());
+	}
+
+	Ok(passed_args)
+}
modifiedcrates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -20,6 +20,7 @@
 type NightlyLocalKey<T> = std::thread::LocalKey<T>;
 
 #[cfg(nightly)]
+#[macro_export]
 macro_rules! const_tls {
 	(const $name:ident: $t:ty = $expr:expr;) => {
 		#[thread_local]
@@ -27,6 +28,7 @@
 	};
 }
 #[cfg(not(nightly))]
+#[macro_export]
 macro_rules! const_tls {
 	(const $name:ident: $t:ty = $expr:expr;) => {
 		thread_local! {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -239,7 +239,9 @@
 			cfg_attrs,
 			..
 		} => {
-			let name = name.as_ref().map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
+			let name = name
+				.as_ref()
+				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
 			let default = match optionality {
 				Optionality::Required => quote!(ParamDefault::None),
 				Optionality::Optional => quote!(ParamDefault::Exists),
@@ -251,7 +253,9 @@
 			})
 		}
 		ArgInfo::Lazy { is_option, name } => {
-			let name = name.as_ref().map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
+			let name = name
+				.as_ref()
+				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
 			Some(quote! {
 				[#name => ParamDefault::exists(#is_option)],
 			})
@@ -364,7 +368,7 @@
 		const _: () = {
 			use ::jrsonnet_evaluator::{
 				State, Val,
-				function::{builtin::{Builtin, StaticBuiltin, ParamParse, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},
+				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},
 				Result, Context, typed::Typed,
 				parser::Span, params,
 			};
@@ -380,11 +384,8 @@
 				fn name(&self) -> &str {
 					stringify!(#name)
 				}
-				fn params(&self) -> &[ParamParse] {
-					/// Safety: ParamParse contains IStr, which is thread-local, thus neither Send or Sync
-					/// The result of this transmute can not outlive the thread, thus 'static here is equivalent to the
-					/// nightly-only 'thread
-					PARAMS.with(|p| unsafe { std::mem::transmute::<&[ParamParse], &'static [ParamParse]>(p.as_slice()) })
+				fn params(&self) -> FunctionSignature {
+					PARAMS.with(|p| p.clone())
 				}
 				#[allow(unused_variables)]
 				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
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::Acyclic;8use jrsonnet_interner::IStr;910use crate::source::Source;1112#[derive(Debug, PartialEq, Acyclic)]13pub enum FieldName {14	/// {fixed: 2}15	Fixed(IStr),16	/// {["dyn"+"amic"]: 3}17	Dyn(Spanned<Expr>),18}1920#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]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(Debug, PartialEq, Acyclic)]38pub struct AssertStmt(pub Spanned<Expr>, pub Option<Spanned<Expr>>);3940#[derive(Debug, PartialEq, Acyclic)]41pub struct FieldMember {42	pub name: FieldName,43	pub plus: bool,44	pub params: Option<ParamsDesc>,45	pub visibility: Visibility,46	pub value: Rc<Spanned<Expr>>,47}4849#[derive(Debug, PartialEq, Acyclic)]50pub(crate) enum Member {51	Field(FieldMember),52	BindStmt(BindSpec),53	AssertStmt(AssertStmt),54}5556#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]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, Acyclic)]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, Acyclic)]150pub struct Param(pub Destruct, pub Option<Rc<Spanned<Expr>>>);151152/// Defined function parameters153#[derive(Debug, Clone, PartialEq, Acyclic)]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, Acyclic)]164pub struct ArgsDesc {165	pub unnamed: Vec<Rc<Spanned<Expr>>>,166	pub named: Vec<(IStr, Rc<Spanned<Expr>>)>,167}168impl ArgsDesc {169	pub fn new(unnamed: Vec<Rc<Spanned<Expr>>>, named: Vec<(IStr, Rc<Spanned<Expr>>)>) -> Self {170		Self { unnamed, named }171	}172}173174#[derive(Debug, Clone, PartialEq, Eq, Acyclic)]175pub enum DestructRest {176	/// ...rest177	Keep(IStr),178	/// ...179	Drop,180}181182#[derive(Debug, Clone, PartialEq, Acyclic)]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<Spanned<Expr>>)>,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, PartialEq, Acyclic)]244pub enum BindSpec {245	Field {246		into: Destruct,247		value: Rc<Spanned<Expr>>,248	},249	Function {250		name: IStr,251		params: ParamsDesc,252		value: Rc<Spanned<Expr>>,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, Acyclic)]265pub struct IfSpecData(pub Spanned<Expr>);266267#[derive(Debug, PartialEq, Acyclic)]268pub struct ForSpecData(pub Destruct, pub Spanned<Expr>);269270#[derive(Debug, PartialEq, Acyclic)]271pub enum CompSpec {272	IfSpec(IfSpecData),273	ForSpec(ForSpecData),274}275276#[derive(Debug, PartialEq, Acyclic)]277pub struct ObjComp {278	pub locals: Rc<Vec<BindSpec>>,279	pub field: Rc<FieldMember>,280	pub compspecs: Vec<CompSpec>,281}282283#[derive(Debug, PartialEq, Acyclic)]284pub struct ObjMembers {285	pub locals: Rc<Vec<BindSpec>>,286	pub asserts: Rc<Vec<AssertStmt>>,287	pub fields: Vec<FieldMember>,288}289290#[derive(Debug, PartialEq, Acyclic)]291pub enum ObjBody {292	MemberList(ObjMembers),293	ObjComp(ObjComp),294}295296#[derive(Debug, PartialEq, Eq, Clone, Copy, Acyclic)]297pub enum LiteralType {298	This,299	Super,300	Dollar,301	Null,302	True,303	False,304}305306#[derive(Debug, PartialEq, Acyclic)]307pub struct SliceDesc {308	pub start: Option<Spanned<Expr>>,309	pub end: Option<Spanned<Expr>>,310	pub step: Option<Spanned<Expr>>,311}312313#[derive(Debug, PartialEq, Acyclic)]314pub struct AssertExpr {315	pub assert: AssertStmt,316	pub rest: Spanned<Expr>,317}318319#[derive(Debug, PartialEq, Acyclic)]320pub struct BinaryOp {321	pub lhs: Spanned<Expr>,322	pub op: BinaryOpType,323	pub rhs: Spanned<Expr>,324}325326#[derive(Debug, PartialEq, Acyclic)]327pub enum ImportKind {328	Normal,329	Str,330	Bin,331}332333#[derive(Debug, PartialEq, Acyclic)]334pub struct IfElse {335	pub cond: IfSpecData,336	pub cond_then: Spanned<Expr>,337	pub cond_else: Option<Spanned<Expr>>,338}339340#[derive(Debug, PartialEq, Acyclic)]341pub struct Slice {342	pub value: Spanned<Expr>,343	pub slice: SliceDesc,344}345346/// Syntax base347#[derive(Debug, PartialEq, Acyclic)]348pub enum Expr {349	Literal(LiteralType),350351	/// String value: "hello"352	Str(IStr),353	/// Number: 1, 2.0, 2e+20354	Num(f64),355	/// Variable name: test356	Var(IStr),357358	/// Array of expressions: [1, 2, "Hello"]359	Arr(Rc<Vec<Spanned<Expr>>>),360	/// Array comprehension:361	/// ```jsonnet362	///  ingredients: [363	///    { kind: kind, qty: 4 / 3 }364	///    for kind in [365	///      'Honey Syrup',366	///      'Lemon Juice',367	///      'Farmers Gin',368	///    ]369	///  ],370	/// ```371	ArrComp(Rc<Spanned<Expr>>, Vec<CompSpec>),372373	/// Object: {a: 2}374	Obj(ObjBody),375	/// Object extension: var1 {b: 2}376	ObjExtend(Rc<Spanned<Expr>>, ObjBody),377378	/// -2379	UnaryOp(UnaryOpType, Box<Spanned<Expr>>),380	/// 2 - 2381	BinaryOp(Box<BinaryOp>),382	/// assert 2 == 2 : "Math is broken"383	AssertExpr(Rc<AssertExpr>),384	/// local a = 2; { b: a }385	LocalExpr(Vec<BindSpec>, Box<Spanned<Expr>>),386387	/// import* "hello"388	Import(ImportKind, Box<Spanned<Expr>>),389	/// error "I'm broken"390	ErrorStmt(Box<Spanned<Expr>>),391	/// a(b, c)392	Apply(Box<Spanned<Expr>>, ArgsDesc, bool),393	/// a[b], a.b, a?.b394	Index {395		indexable: Box<Spanned<Expr>>,396		parts: Vec<IndexPart>,397	},398	/// function(x) x399	Function(ParamsDesc, Rc<Spanned<Expr>>),400	/// if true == false then 1 else 2401	IfElse(Box<IfElse>),402	Slice(Box<Slice>),403}404405#[derive(Debug, PartialEq, Acyclic)]406pub struct IndexPart {407	pub value: Spanned<Expr>,408	#[cfg(feature = "exp-null-coaelse")]409	pub null_coaelse: bool,410}411412/// file, begin offset, end offset413#[derive(Clone, PartialEq, Eq, Acyclic)]414#[repr(C)]415pub struct Span(pub Source, pub u32, pub u32);416impl Span {417	pub fn belongs_to(&self, other: &Span) -> bool {418		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2419	}420}421422static_assertions::assert_eq_size!(Span, (usize, usize));423424impl Debug for Span {425	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {426		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)427	}428}429430#[derive(Clone, PartialEq, Acyclic)]431pub struct Spanned<T: Acyclic>(T, Span);432impl<T: Acyclic> Deref for Spanned<T> {433	type Target = T;434	fn deref(&self) -> &Self::Target {435		&self.0436	}437}438impl<T: Acyclic> Spanned<T> {439	#[inline]440	pub fn new(v: T, s: Span) -> Self {441		Self(v, s)442	}443	#[inline]444	pub fn span(&self) -> Span {445		self.1.clone()446	}447}448449impl<T: Debug + Acyclic> Debug for Spanned<T> {450	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {451		let expr = &**self;452		if f.alternate() {453			write!(f, "{:#?}", expr)?;454		} else {455			write!(f, "{:?}", expr)?;456		}457		write!(f, " from {:?}", self.span())?;458		Ok(())459	}460}
after · crates/jrsonnet-parser/src/expr.rs
1use std::{2	fmt::{self, Debug, Display},3	ops::Deref,4	rc::Rc,5};67use jrsonnet_gcmodule::Acyclic;8use jrsonnet_interner::IStr;910use crate::{11	function::{FunctionSignature, ParamDefault, ParamName, ParamParse},12	source::Source,13};1415#[derive(Debug, PartialEq, Acyclic)]16pub enum FieldName {17	/// {fixed: 2}18	Fixed(IStr),19	/// {["dyn"+"amic"]: 3}20	Dyn(Spanned<Expr>),21}2223#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]24#[repr(u8)]25pub enum Visibility {26	/// :27	Normal,28	/// ::29	Hidden,30	/// :::31	Unhide,32}3334impl Visibility {35	pub fn is_visible(&self) -> bool {36		matches!(self, Self::Normal | Self::Unhide)37	}38}3940#[derive(Debug, PartialEq, Acyclic)]41pub struct AssertStmt(pub Spanned<Expr>, pub Option<Spanned<Expr>>);4243#[derive(Debug, PartialEq, Acyclic)]44pub struct FieldMember {45	pub name: FieldName,46	pub plus: bool,47	pub params: Option<ExprParams>,48	pub visibility: Visibility,49	pub value: Rc<Spanned<Expr>>,50}5152#[derive(Debug, PartialEq, Acyclic)]53pub(crate) enum Member {54	Field(FieldMember),55	BindStmt(BindSpec),56	AssertStmt(AssertStmt),57}5859#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]60pub enum UnaryOpType {61	Plus,62	Minus,63	BitNot,64	Not,65}6667impl Display for UnaryOpType {68	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {69		use UnaryOpType::*;70		write!(71			f,72			"{}",73			match self {74				Plus => "+",75				Minus => "-",76				BitNot => "~",77				Not => "!",78			}79		)80	}81}8283#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]84pub enum BinaryOpType {85	Mul,86	Div,8788	/// Implemented as intrinsic, put here for completeness89	Mod,9091	Add,92	Sub,9394	Lhs,95	Rhs,9697	Lt,98	Gt,99	Lte,100	Gte,101102	BitAnd,103	BitOr,104	BitXor,105106	Eq,107	Neq,108109	And,110	Or,111	#[cfg(feature = "exp-null-coaelse")]112	NullCoaelse,113114	// Equialent to std.objectHasEx(a, b, true)115	In,116}117118impl Display for BinaryOpType {119	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120		use BinaryOpType::*;121		write!(122			f,123			"{}",124			match self {125				Mul => "*",126				Div => "/",127				Mod => "%",128				Add => "+",129				Sub => "-",130				Lhs => "<<",131				Rhs => ">>",132				Lt => "<",133				Gt => ">",134				Lte => "<=",135				Gte => ">=",136				BitAnd => "&",137				BitOr => "|",138				BitXor => "^",139				Eq => "==",140				Neq => "!=",141				And => "&&",142				Or => "||",143				In => "in",144				#[cfg(feature = "exp-null-coaelse")]145				NullCoaelse => "??",146			}147		)148	}149}150151/// name, default value152#[derive(Debug, PartialEq, Acyclic)]153pub struct ExprParam {154	pub destruct: Destruct,155	pub default: Option<Rc<Spanned<Expr>>>,156}157158/// Defined function parameters159#[derive(Debug, Clone, PartialEq, Acyclic)]160pub struct ExprParams {161	pub exprs: Rc<Vec<ExprParam>>,162	pub signature: FunctionSignature,163	binds_len: usize,164}165impl ExprParams {166	pub fn len(&self) -> usize {167		self.exprs.len()168	}169	pub fn binds_len(&self) -> usize {170		self.binds_len171	}172	pub fn new(exprs: Vec<ExprParam>) -> Self {173		Self {174			signature: FunctionSignature::new(175				exprs176					.iter()177					.map(|p| {178						ParamParse::new(179							p.destruct.name(),180							ParamDefault::exists(p.default.is_some()),181						)182					})183					.collect(),184			),185			binds_len: exprs.iter().map(|v| v.destruct.binds_len()).sum(),186			exprs: Rc::new(exprs),187		}188	}189}190191#[derive(Debug, PartialEq, Acyclic)]192pub struct ArgsDesc {193	pub unnamed: Vec<Rc<Spanned<Expr>>>,194	pub named: Vec<(IStr, Rc<Spanned<Expr>>)>,195}196impl ArgsDesc {197	pub fn new(unnamed: Vec<Rc<Spanned<Expr>>>, named: Vec<(IStr, Rc<Spanned<Expr>>)>) -> Self {198		Self { unnamed, named }199	}200}201202#[derive(Debug, Clone, PartialEq, Eq, Acyclic)]203pub enum DestructRest {204	/// ...rest205	Keep(IStr),206	/// ...207	Drop,208}209210#[derive(Debug, Clone, PartialEq, Acyclic)]211pub enum Destruct {212	Full(IStr),213	#[cfg(feature = "exp-destruct")]214	Skip,215	#[cfg(feature = "exp-destruct")]216	Array {217		start: Vec<Destruct>,218		rest: Option<DestructRest>,219		end: Vec<Destruct>,220	},221	#[cfg(feature = "exp-destruct")]222	Object {223		fields: Vec<(IStr, Option<Destruct>, Option<Spanned<Expr>>)>,224		rest: Option<DestructRest>,225	},226}227impl Destruct {228	/// Name of destructure, used for function parameter names229	pub fn name(&self) -> ParamName {230		ParamName(match self {231			Self::Full(name) => Some(name.clone()),232			#[cfg(feature = "exp-destruct")]233			_ => None,234		})235	}236	pub fn binds_len(&self) -> usize {237		#[cfg(feature = "exp-destruct")]238		fn cap_rest(rest: &Option<DestructRest>) -> usize {239			match rest {240				Some(DestructRest::Keep(_)) => 1,241				Some(DestructRest::Drop) => 0,242				None => 0,243			}244		}245		match self {246			Self::Full(_) => 1,247			#[cfg(feature = "exp-destruct")]248			Self::Skip => 0,249			#[cfg(feature = "exp-destruct")]250			Self::Array { start, rest, end } => {251				start.iter().map(Destruct::binds_len).sum::<usize>()252					+ end.iter().map(Destruct::binds_len).sum::<usize>()253					+ cap_rest(rest)254			}255			#[cfg(feature = "exp-destruct")]256			Self::Object { fields, rest } => {257				let mut out = 0;258				for (_, into, _) in fields {259					match into {260						Some(v) => out += v.capacity_hint(),261						// Field is destructured to default name262						None => out += 1,263					}264				}265				out + cap_rest(rest)266			}267		}268	}269}270271#[derive(Debug, PartialEq, Acyclic)]272pub enum BindSpec {273	Field {274		into: Destruct,275		value: Rc<Spanned<Expr>>,276	},277	Function {278		name: IStr,279		params: ExprParams,280		value: Rc<Spanned<Expr>>,281	},282}283impl BindSpec {284	pub fn binds_len(&self) -> usize {285		match self {286			BindSpec::Field { into, .. } => into.binds_len(),287			BindSpec::Function { .. } => 1,288		}289	}290}291292#[derive(Debug, PartialEq, Acyclic)]293pub struct IfSpecData(pub Spanned<Expr>);294295#[derive(Debug, PartialEq, Acyclic)]296pub struct ForSpecData(pub Destruct, pub Spanned<Expr>);297298#[derive(Debug, PartialEq, Acyclic)]299pub enum CompSpec {300	IfSpec(IfSpecData),301	ForSpec(ForSpecData),302}303304#[derive(Debug, PartialEq, Acyclic)]305pub struct ObjComp {306	pub locals: Rc<Vec<BindSpec>>,307	pub field: Rc<FieldMember>,308	pub compspecs: Vec<CompSpec>,309}310311#[derive(Debug, PartialEq, Acyclic)]312pub struct ObjMembers {313	pub locals: Rc<Vec<BindSpec>>,314	pub asserts: Rc<Vec<AssertStmt>>,315	pub fields: Vec<FieldMember>,316}317318#[derive(Debug, PartialEq, Acyclic)]319pub enum ObjBody {320	MemberList(ObjMembers),321	ObjComp(ObjComp),322}323324#[derive(Debug, PartialEq, Eq, Clone, Copy, Acyclic)]325pub enum LiteralType {326	This,327	Super,328	Dollar,329	Null,330	True,331	False,332}333334#[derive(Debug, PartialEq, Acyclic)]335pub struct SliceDesc {336	pub start: Option<Spanned<Expr>>,337	pub end: Option<Spanned<Expr>>,338	pub step: Option<Spanned<Expr>>,339}340341#[derive(Debug, PartialEq, Acyclic)]342pub struct AssertExpr {343	pub assert: AssertStmt,344	pub rest: Spanned<Expr>,345}346347#[derive(Debug, PartialEq, Acyclic)]348pub struct BinaryOp {349	pub lhs: Spanned<Expr>,350	pub op: BinaryOpType,351	pub rhs: Spanned<Expr>,352}353354#[derive(Debug, PartialEq, Acyclic)]355pub enum ImportKind {356	Normal,357	Str,358	Bin,359}360361#[derive(Debug, PartialEq, Acyclic)]362pub struct IfElse {363	pub cond: IfSpecData,364	pub cond_then: Spanned<Expr>,365	pub cond_else: Option<Spanned<Expr>>,366}367368#[derive(Debug, PartialEq, Acyclic)]369pub struct Slice {370	pub value: Spanned<Expr>,371	pub slice: SliceDesc,372}373374/// Syntax base375#[derive(Debug, PartialEq, Acyclic)]376pub enum Expr {377	Literal(LiteralType),378379	/// String value: "hello"380	Str(IStr),381	/// Number: 1, 2.0, 2e+20382	Num(f64),383	/// Variable name: test384	Var(IStr),385386	/// Array of expressions: [1, 2, "Hello"]387	Arr(Rc<Vec<Spanned<Expr>>>),388	/// Array comprehension:389	/// ```jsonnet390	///  ingredients: [391	///    { kind: kind, qty: 4 / 3 }392	///    for kind in [393	///      'Honey Syrup',394	///      'Lemon Juice',395	///      'Farmers Gin',396	///    ]397	///  ],398	/// ```399	ArrComp(Rc<Spanned<Expr>>, Vec<CompSpec>),400401	/// Object: {a: 2}402	Obj(ObjBody),403	/// Object extension: var1 {b: 2}404	ObjExtend(Rc<Spanned<Expr>>, ObjBody),405406	/// -2407	UnaryOp(UnaryOpType, Box<Spanned<Expr>>),408	/// 2 - 2409	BinaryOp(Box<BinaryOp>),410	/// assert 2 == 2 : "Math is broken"411	AssertExpr(Rc<AssertExpr>),412	/// local a = 2; { b: a }413	LocalExpr(Vec<BindSpec>, Box<Spanned<Expr>>),414415	/// import* "hello"416	Import(ImportKind, Box<Spanned<Expr>>),417	/// error "I'm broken"418	ErrorStmt(Box<Spanned<Expr>>),419	/// a(b, c)420	Apply(Box<Spanned<Expr>>, ArgsDesc, bool),421	/// a[b], a.b, a?.b422	Index {423		indexable: Box<Spanned<Expr>>,424		parts: Vec<IndexPart>,425	},426	/// function(x) x427	Function(ExprParams, Rc<Spanned<Expr>>),428	/// if true == false then 1 else 2429	IfElse(Box<IfElse>),430	Slice(Box<Slice>),431}432433#[derive(Debug, PartialEq, Acyclic)]434pub struct IndexPart {435	pub value: Spanned<Expr>,436	#[cfg(feature = "exp-null-coaelse")]437	pub null_coaelse: bool,438}439440/// file, begin offset, end offset441#[derive(Clone, PartialEq, Eq, Acyclic)]442#[repr(C)]443pub struct Span(pub Source, pub u32, pub u32);444impl Span {445	pub fn belongs_to(&self, other: &Span) -> bool {446		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2447	}448}449450static_assertions::assert_eq_size!(Span, (usize, usize));451452impl Debug for Span {453	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {454		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)455	}456}457458#[derive(Clone, PartialEq, Acyclic)]459pub struct Spanned<T: Acyclic>(T, Span);460impl<T: Acyclic> Deref for Spanned<T> {461	type Target = T;462	fn deref(&self) -> &Self::Target {463		&self.0464	}465}466impl<T: Acyclic> Spanned<T> {467	#[inline]468	pub fn new(v: T, s: Span) -> Self {469		Self(v, s)470	}471	#[inline]472	pub fn span(&self) -> Span {473		self.1.clone()474	}475}476477impl<T: Debug + Acyclic> Debug for Spanned<T> {478	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {479		let expr = &**self;480		if f.alternate() {481			write!(f, "{:#?}", expr)?;482		} else {483			write!(f, "{:?}", expr)?;484		}485		write!(f, " from {:?}", self.span())?;486		Ok(())487	}488}
addedcrates/jrsonnet-parser/src/function.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-parser/src/function.rs
@@ -0,0 +1,126 @@
+use std::fmt;
+use std::ops::Deref;
+use std::rc::Rc;
+
+use jrsonnet_gcmodule::Acyclic;
+use jrsonnet_interner::IStr;
+
+#[derive(Clone, Acyclic, Debug, PartialEq, Eq)]
+pub struct ParamName(pub Option<IStr>);
+impl ParamName {
+	pub const ANONYMOUS: Self = Self(None);
+	pub fn new(name: IStr) -> Self {
+		Self(Some(name))
+	}
+	pub fn as_str(&self) -> Option<&str> {
+		self.0.as_deref()
+	}
+	pub fn is_anonymous(&self) -> bool {
+		self.0.is_none()
+	}
+}
+impl PartialEq<IStr> for ParamName {
+	fn eq(&self, other: &IStr) -> bool {
+		self.0
+			.as_ref()
+			.map_or(false, |s| s.as_bytes() == other.as_bytes())
+	}
+}
+
+impl fmt::Display for ParamName {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		match &self.0 {
+			Some(v) => write!(f, "{v}"),
+			None => write!(f, "<unnamed>"),
+		}
+	}
+}
+
+#[derive(Clone, Copy, Debug, Acyclic, PartialEq, Eq)]
+pub enum ParamDefault {
+	None,
+	Exists,
+	Literal(&'static str),
+}
+impl ParamDefault {
+	pub const fn exists(is_exists: bool) -> Self {
+		if is_exists {
+			Self::Exists
+		} else {
+			Self::None
+		}
+	}
+}
+impl fmt::Display for ParamDefault {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		match self {
+			ParamDefault::None => Ok(()),
+			ParamDefault::Exists => write!(f, " = <default>"),
+			ParamDefault::Literal(lit) => write!(f, " = {lit}"),
+		}
+	}
+}
+
+#[derive(Clone, Acyclic, Debug, PartialEq, Eq)]
+pub struct ParamParse {
+	name: ParamName,
+	default: ParamDefault,
+}
+impl ParamParse {
+	pub fn new(name: ParamName, default: ParamDefault) -> Self {
+		Self { name, default }
+	}
+	/// Parameter name for named call parsing
+	pub fn name(&self) -> &ParamName {
+		&self.name
+	}
+	pub fn default(&self) -> ParamDefault {
+		self.default
+	}
+	pub fn has_default(&self) -> bool {
+		!matches!(self.default, ParamDefault::None)
+	}
+}
+impl fmt::Display for ParamParse {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		write!(f, "{}{}", self.name, self.default)
+	}
+}
+
+#[derive(Debug, Clone, Acyclic, PartialEq, Eq)]
+pub struct FunctionSignature(Rc<[ParamParse]>);
+impl Deref for FunctionSignature {
+	type Target = [ParamParse];
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+
+thread_local! {
+	static EMPTY_SIGNATURE: FunctionSignature = FunctionSignature::new([].into());
+}
+
+impl FunctionSignature {
+	pub fn new(v: Rc<[ParamParse]>) -> Self {
+		Self(v)
+	}
+	pub fn empty() -> Self {
+		EMPTY_SIGNATURE.with(|p| p.clone())
+	}
+}
+impl fmt::Display for FunctionSignature {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		if self.0.is_empty() {
+			return write!(f, "(/*no arguments*/)");
+		}
+		write!(f, "(")?;
+		for (i, par) in self.0.iter().enumerate() {
+			if i != 0 {
+				write!(f, ", ")?;
+			}
+			write!(f, "{par}")?;
+		}
+		write!(f, ")")
+	}
+}
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -7,9 +7,11 @@
 pub use expr::*;
 pub use jrsonnet_interner::IStr;
 pub use peg;
+pub mod function;
 mod location;
 mod source;
 mod unescape;
+
 pub use location::CodeLocation;
 pub use source::{
 	Source, SourceDefaultIgnoreJpath, SourceDirectory, SourceFifo, SourceFile, SourcePath,
@@ -68,10 +70,10 @@
 		rule keyword(id: &'static str) -> ()
 			= ##parse_string_literal(id) end_of_ident()
 
-		pub rule param(s: &ParserSettings) -> expr::Param = name:destruct(s) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr.map(Rc::new)) }
-		pub rule params(s: &ParserSettings) -> expr::ParamsDesc
-			= params:param(s) ** comma() comma()? { expr::ParamsDesc(Rc::new(params)) }
-			/ { expr::ParamsDesc(Rc::new(Vec::new())) }
+		pub rule param(s: &ParserSettings) -> expr::ExprParam = destruct:destruct(s) expr:(_ "=" _ expr:expr(s){expr})? { expr::ExprParam { destruct, default: expr.map(Rc::new) } }
+		pub rule params(s: &ParserSettings) -> expr::ExprParams
+			= params:param(s) ** comma() comma()? { expr::ExprParams::new(params) }
+			/ { expr::ExprParams::new(Vec::new()) }
 
 		pub rule arg(s: &ParserSettings) -> (Option<IStr>, Rc<Spanned<Expr>>)
 			= name:(quiet! { (s:id() _ "=" !['='] _ {s})? } / expected!("<argument name>")) expr:expr(s) {(name, Rc::new(expr))}
modifiedcrates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snapdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snap
+++ b/crates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snap
@@ -6,26 +6,47 @@
     [
         Function {
             name: "x",
-            params: ParamsDesc(
-                [
-                    Param(
-                        Full(
+            params: ExprParams {
+                exprs: [
+                    ExprParam {
+                        destruct: Full(
                             "foo",
                         ),
-                        Some(
+                        default: Some(
                             Str(
                                 "foo",
                             ) from virtual:<test>:14-19,
                         ),
-                    ),
-                    Param(
-                        Full(
+                    },
+                    ExprParam {
+                        destruct: Full(
                             "bar",
                         ),
-                        None,
-                    ),
+                        default: None,
+                    },
                 ],
-            ),
+                signature: FunctionSignature(
+                    [
+                        ParamParse {
+                            name: ParamName(
+                                Some(
+                                    "foo",
+                                ),
+                            ),
+                            default: Exists,
+                        },
+                        ParamParse {
+                            name: ParamName(
+                                Some(
+                                    "bar",
+                                ),
+                            ),
+                            default: None,
+                        },
+                    ],
+                ),
+                binds_len: 2,
+            },
             value: Literal(
                 Null,
             ) from virtual:<test>:28-32,