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
before · crates/jrsonnet-evaluator/src/error.rs
1use std::{2	cmp::Ordering,3	convert::Infallible,4	fmt::{Debug, Display},5};67use jrsonnet_gcmodule::{Acyclic, Trace};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	function::{builtin::ParamDefault, CallLocation},15	stdlib::format::FormatError,16	typed::TypeLocError,17	val::ConvertNumValueError,18	ObjValue, ResolvePathOwned,19};2021pub(crate) fn format_found(list: &[IStr], what: &str) -> String {22	if list.is_empty() {23		return String::new();24	}25	let mut out = String::new();26	out.push_str("\nThere ");27	if list.len() > 1 {28		out.push_str("are ");29	} else {30		out.push_str("is a ");31	}32	out.push_str(what);33	if list.len() > 1 {34		out.push('s');35	}36	out.push_str(" with similar name");37	if list.len() > 1 {38		out.push('s');39	}40	out.push_str(" present: ");41	for (i, v) in list.iter().enumerate() {42		if i != 0 {43			out.push_str(", ");44		}45		out.push_str(v as &str);46	}47	out48}4950fn format_signature(sig: &FunctionSignature) -> String {51	let mut out = String::new();52	out.push_str("\nFunction has the following signature: ");53	out.push('(');54	if sig.is_empty() {55		out.push_str("/*no arguments*/");56	} else {57		for (i, (name, default)) in sig.iter().enumerate() {58			if i != 0 {59				out.push_str(", ");60			}61			if let Some(name) = name {62				out.push_str(name);63			} else {64				out.push_str("<unnamed>");65			}66			match default {67				ParamDefault::None => {}68				ParamDefault::Exists => out.push_str(" = <default>"),69				ParamDefault::Literal(lit) => {70					out.push_str(" = ");71					out.push_str(lit);72				}73			}74		}75	}76	out.push(')');77	out78}7980const fn format_empty_str(str: &str) -> &str {81	if str.is_empty() {82		"\"\" (empty string)"83	} else {84		str85	}86}8788pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {89	let mut heap = Vec::new();90	for field in v.fields_ex(91		true,92		#[cfg(feature = "exp-preserve-order")]93		false,94	) {95		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());96		if conf < 0.8 {97			continue;98		}99		assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");100101		heap.push((conf, field));102	}103	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));104	heap.into_iter().map(|v| v.1).collect()105}106107type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;108109/// Possible errors110#[allow(missing_docs)]111#[derive(Error, Debug, Clone, Trace)]112#[non_exhaustive]113pub enum ErrorKind {114	#[error("intrinsic not found: {0}")]115	IntrinsicNotFound(IStr),116117	#[error("operator {0} does not operate on type {1}")]118	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),119	#[error("binary operation {1} {0} {2} is not implemented")]120	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),121122	#[error("self/super/$ are only usable inside objects")]123	CantUseSelfSupOutsideOfObject,124	#[error("no super found")]125	NoSuperFound,126127	#[error("for loop can only iterate over arrays")]128	InComprehensionCanOnlyIterateOverArray,129130	#[error("array out of bounds: {0} is not within [0,{1})")]131	ArrayBoundsError(isize, usize),132	#[error("string out of bounds: {0} is not within [0,{1})")]133	StringBoundsError(usize, usize),134135	#[error("assert failed: {}", format_empty_str(.0))]136	AssertionFailed(IStr),137138	#[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]139	VariableIsNotDefined(IStr, Vec<IStr>),140	#[error("duplicate local var: {0}")]141	DuplicateLocalVar(IStr),142143	#[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]144	TypeMismatch(&'static str, Vec<ValType>, ValType),145	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]146	NoSuchField(IStr, Vec<IStr>),147148	#[error("only functions can be called, got {0}")]149	OnlyFunctionsCanBeCalledGot(ValType),150	#[error("parameter {0} is not defined")]151	UnknownFunctionParameter(String),152	#[error("argument {0} is already bound")]153	BindingParameterASecondTime(IStr),154	#[error("too many args, function has {0}{sig}", sig = format_signature(.1))]155	TooManyArgsFunctionHas(usize, FunctionSignature),156	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]157	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),158159	#[error("external variable is not defined: {0}")]160	UndefinedExternalVariable(IStr),161162	#[error("field name should be string, got {0}")]163	FieldMustBeStringGot(ValType),164	#[error("duplicate field name: {}", format_empty_str(.0))]165	DuplicateFieldName(IStr),166167	#[error("attempted to index array with string {}", format_empty_str(.0))]168	AttemptedIndexAnArrayWithString(IStr),169	#[error("{0} index type should be {1}, got {2}")]170	ValueIndexMustBeTypeGot(ValType, ValType, ValType),171	#[error("cant index into {0}")]172	CantIndexInto(ValType),173	#[error("{0} is not indexable")]174	ValueIsNotIndexable(ValType),175176	#[error("super can't be used standalone")]177	StandaloneSuper,178179	#[error("can't resolve {1} from {0}")]180	ImportFileNotFound(SourcePath, ResolvePathOwned),181	#[error("resolved file not found: {:?}", .0)]182	ResolvedFileNotFound(SourcePath),183	#[error("can't import {0}: is a directory")]184	ImportIsADirectory(SourcePath),185	#[error("imported file is not valid utf-8: {0:?}")]186	ImportBadFileUtf8(SourcePath),187	#[error("import io error: {0}")]188	ImportIo(String),189	#[error("tried to import {1} from {0}, but imports are not supported")]190	ImportNotSupported(SourcePath, ResolvePathOwned),191	#[error("can't import from virtual file")]192	CantImportFromVirtualFile,193	#[error(194		"syntax error: {}",195		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225196		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {197			format!(198				"expected {}, got {:?}",199				.error.expected,200				.path.code().chars().nth(error.location.offset)201				.map_or_else(|| "EOF".into(), |c| c.to_string())202			)203		}, |v| v[3..].into())}204	)]205	ImportSyntaxError {206		path: Source,207		#[trace(skip)]208		error: Box<jrsonnet_parser::ParseError>,209	},210211	#[error("runtime error: {}", format_empty_str(.0))]212	RuntimeError(IStr),213	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]214	StackOverflow,215	#[error("infinite recursion detected")]216	InfiniteRecursionDetected,217	#[error("tried to index by fractional value")]218	FractionalIndex,219	#[error("attempted to divide by zero")]220	DivisionByZero,221222	#[error("string manifest output is not an string")]223	StringManifestOutputIsNotAString,224	#[error("stream manifest output is not an array")]225	StreamManifestOutputIsNotAArray,226	#[error("multi manifest output is not an object")]227	MultiManifestOutputIsNotAObject,228229	#[error("cant recurse stream manifest")]230	StreamManifestOutputCannotBeRecursed,231	#[error("stream manifest output cannot consist of raw strings")]232	StreamManifestCannotNestString,233234	#[error("{}", format_empty_str(.0))]235	ImportCallbackError(String),236	#[error("invalid unicode codepoint: {0}")]237	InvalidUnicodeCodepointGot(u32),238239	#[error("convert num value: {0}")]240	ConvertNumValue(#[from] ConvertNumValueError),241242	#[error("format error: {0}")]243	Format(#[from] FormatError),244	#[error("type error: {0}")]245	TypeError(TypeLocError),246247	#[cfg(feature = "anyhow-error")]248	#[error(transparent)]249	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),250}251252#[cfg(feature = "anyhow-error")]253impl From<anyhow::Error> for Error {254	fn from(e: anyhow::Error) -> Self {255		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))256	}257}258259impl From<ErrorKind> for Error {260	fn from(e: ErrorKind) -> Self {261		Self::new(e)262	}263}264265impl From<Infallible> for Error {266	fn from(_value: Infallible) -> Self {267		unreachable!()268	}269}270271/// Single stack trace frame272#[derive(Clone, Debug, Trace)]273pub struct StackTraceElement {274	/// Source of this frame275	/// Some frames only act as description, without attached source276	pub location: Option<Span>,277	/// Frame description278	pub desc: String,279}280#[derive(Debug, Clone, Trace)]281pub struct StackTrace(pub Vec<StackTraceElement>);282283#[derive(Clone, Trace)]284pub struct Error(Box<(ErrorKind, StackTrace)>);285impl Error {286	pub fn new(e: ErrorKind) -> Self {287		Self(Box::new((e, StackTrace(vec![]))))288	}289290	pub const fn error(&self) -> &ErrorKind {291		&(self.0).0292	}293	pub fn error_mut(&mut self) -> &mut ErrorKind {294		&mut (self.0).0295	}296	pub const fn trace(&self) -> &StackTrace {297		&(self.0).1298	}299	pub fn trace_mut(&mut self) -> &mut StackTrace {300		&mut (self.0).1301	}302}303impl Display for Error {304	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {305		writeln!(f, "{}", self.0 .0)?;306		for el in &self.0 .1 .0 {307			write!(f, "\t{}", el.desc)?;308			if let Some(loc) = &el.location {309				write!(f, "at {}", loc.0 .0 .0)?;310				loc.0.map_source_locations(&[loc.1, loc.2]);311			}312			writeln!(f)?;313		}314		Ok(())315	}316}317impl Debug for Error {318	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {319		f.debug_tuple("LocError").field(&self.0).finish()320	}321}322impl std::error::Error for Error {}323324pub trait ErrorSource {325	fn to_location(self) -> Option<Span>;326}327impl<T: Acyclic> ErrorSource for &Spanned<T> {328	fn to_location(self) -> Option<Span> {329		Some(self.span())330	}331}332impl ErrorSource for &Span {333	fn to_location(self) -> Option<Span> {334		Some(self.clone())335	}336}337impl ErrorSource for CallLocation<'_> {338	fn to_location(self) -> Option<Span> {339		self.0.cloned()340	}341}342343pub type Result<V, E = Error> = std::result::Result<V, E>;344pub trait ResultExt: Sized {345	#[must_use]346	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;347	#[must_use]348	fn description(self, msg: &str) -> Self {349		self.with_description(|| msg)350	}351352	#[must_use]353	fn with_description_src<O: Into<String>>(354		self,355		src: impl ErrorSource,356		msg: impl FnOnce() -> O,357	) -> Self;358	#[must_use]359	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {360		self.with_description_src(src, || msg)361	}362}363impl<T> ResultExt for Result<T, Error> {364	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {365		if let Err(e) = &mut self {366			let trace = e.trace_mut();367			trace.0.push(StackTraceElement {368				location: None,369				desc: msg().into(),370			});371		}372		self373	}374375	fn with_description_src<O: Into<String>>(376		mut self,377		src: impl ErrorSource,378		msg: impl FnOnce() -> O,379	) -> Self {380		if let Err(e) = &mut self {381			let trace = e.trace_mut();382			trace.0.push(StackTraceElement {383				location: src.to_location(),384				desc: msg().into(),385			});386		}387		self388	}389}390391#[macro_export]392macro_rules! bail {393	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {394		return Err($w$(::$i)*$(($($tt)*))?.into())395	};396	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {397		return Err($w$(::$i)*$({$($tt)*})?.into())398	};399	($l:literal$(, $($tt:tt)*)?) => {400		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())401	};402}403404#[macro_export]405macro_rules! runtime_error {406	($l:literal$(, $($tt:tt)*)?) => {407		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))408	};409}
after · crates/jrsonnet-evaluator/src/error.rs
1use std::{2	cmp::Ordering,3	convert::Infallible,4	fmt::{self, Debug, Display},5};67use jrsonnet_gcmodule::{Acyclic, Trace};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	function::{CallLocation, FunctionSignature, ParamDefault, ParamName},15	stdlib::format::FormatError,16	typed::TypeLocError,17	val::ConvertNumValueError,18	ObjValue, ResolvePathOwned,19};2021pub(crate) fn format_found(list: &[IStr], what: &str) -> String {22	if list.is_empty() {23		return String::new();24	}25	let mut out = String::new();26	out.push_str("\nThere ");27	if list.len() > 1 {28		out.push_str("are ");29	} else {30		out.push_str("is a ");31	}32	out.push_str(what);33	if list.len() > 1 {34		out.push('s');35	}36	out.push_str(" with similar name");37	if list.len() > 1 {38		out.push('s');39	}40	out.push_str(" present: ");41	for (i, v) in list.iter().enumerate() {42		if i != 0 {43			out.push_str(", ");44		}45		out.push_str(v as &str);46	}47	out48}4950const fn format_empty_str(str: &str) -> &str {51	if str.is_empty() {52		"\"\" (empty string)"53	} else {54		str55	}56}5758pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {59	let mut heap = Vec::new();60	for field in v.fields_ex(61		true,62		#[cfg(feature = "exp-preserve-order")]63		false,64	) {65		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());66		if conf < 0.8 {67			continue;68		}69		assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");7071		heap.push((conf, field));72	}73	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));74	heap.into_iter().map(|v| v.1).collect()75}7677/// Possible errors78#[allow(missing_docs)]79#[derive(Error, Debug, Clone, Trace)]80#[non_exhaustive]81pub enum ErrorKind {82	#[error("intrinsic not found: {0}")]83	IntrinsicNotFound(IStr),8485	#[error("operator {0} does not operate on type {1}")]86	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),87	#[error("binary operation {1} {0} {2} is not implemented")]88	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8990	#[error("self/super/$ are only usable inside objects")]91	CantUseSelfSupOutsideOfObject,92	#[error("no super found")]93	NoSuperFound,9495	#[error("for loop can only iterate over arrays")]96	InComprehensionCanOnlyIterateOverArray,9798	#[error("array out of bounds: {0} is not within [0,{1})")]99	ArrayBoundsError(isize, usize),100	#[error("string out of bounds: {0} is not within [0,{1})")]101	StringBoundsError(usize, usize),102103	#[error("assert failed: {}", format_empty_str(.0))]104	AssertionFailed(IStr),105106	#[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]107	VariableIsNotDefined(IStr, Vec<IStr>),108	#[error("duplicate local var: {0}")]109	DuplicateLocalVar(IStr),110111	#[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]112	TypeMismatch(&'static str, Vec<ValType>, ValType),113	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]114	NoSuchField(IStr, Vec<IStr>),115116	#[error("only functions can be called, got {0}")]117	OnlyFunctionsCanBeCalledGot(ValType),118	#[error("parameter {0} is not defined")]119	UnknownFunctionParameter(IStr),120	#[error("argument {0} is already bound")]121	BindingParameterASecondTime(IStr),122	#[error("too many args, function has {0}\nFunction has the following signature: {1}")]123	TooManyArgsFunctionHas(usize, FunctionSignature),124	#[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]125	FunctionParameterNotBoundInCall(ParamName, FunctionSignature),126127	#[error("external variable is not defined: {0}")]128	UndefinedExternalVariable(IStr),129130	#[error("field name should be string, got {0}")]131	FieldMustBeStringGot(ValType),132	#[error("duplicate field name: {}", format_empty_str(.0))]133	DuplicateFieldName(IStr),134135	#[error("attempted to index array with string {}", format_empty_str(.0))]136	AttemptedIndexAnArrayWithString(IStr),137	#[error("{0} index type should be {1}, got {2}")]138	ValueIndexMustBeTypeGot(ValType, ValType, ValType),139	#[error("cant index into {0}")]140	CantIndexInto(ValType),141	#[error("{0} is not indexable")]142	ValueIsNotIndexable(ValType),143144	#[error("super can't be used standalone")]145	StandaloneSuper,146147	#[error("can't resolve {1} from {0}")]148	ImportFileNotFound(SourcePath, ResolvePathOwned),149	#[error("resolved file not found: {:?}", .0)]150	ResolvedFileNotFound(SourcePath),151	#[error("can't import {0}: is a directory")]152	ImportIsADirectory(SourcePath),153	#[error("imported file is not valid utf-8: {0:?}")]154	ImportBadFileUtf8(SourcePath),155	#[error("import io error: {0}")]156	ImportIo(String),157	#[error("tried to import {1} from {0}, but imports are not supported")]158	ImportNotSupported(SourcePath, ResolvePathOwned),159	#[error("can't import from virtual file")]160	CantImportFromVirtualFile,161	#[error(162		"syntax error: {}",163		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225164		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {165			format!(166				"expected {}, got {:?}",167				.error.expected,168				.path.code().chars().nth(error.location.offset)169				.map_or_else(|| "EOF".into(), |c| c.to_string())170			)171		}, |v| v[3..].into())}172	)]173	ImportSyntaxError {174		path: Source,175		#[trace(skip)]176		error: Box<jrsonnet_parser::ParseError>,177	},178179	#[error("runtime error: {}", format_empty_str(.0))]180	RuntimeError(IStr),181	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]182	StackOverflow,183	#[error("infinite recursion detected")]184	InfiniteRecursionDetected,185	#[error("tried to index by fractional value")]186	FractionalIndex,187	#[error("attempted to divide by zero")]188	DivisionByZero,189190	#[error("string manifest output is not an string")]191	StringManifestOutputIsNotAString,192	#[error("stream manifest output is not an array")]193	StreamManifestOutputIsNotAArray,194	#[error("multi manifest output is not an object")]195	MultiManifestOutputIsNotAObject,196197	#[error("cant recurse stream manifest")]198	StreamManifestOutputCannotBeRecursed,199	#[error("stream manifest output cannot consist of raw strings")]200	StreamManifestCannotNestString,201202	#[error("{}", format_empty_str(.0))]203	ImportCallbackError(String),204	#[error("invalid unicode codepoint: {0}")]205	InvalidUnicodeCodepointGot(u32),206207	#[error("convert num value: {0}")]208	ConvertNumValue(#[from] ConvertNumValueError),209210	#[error("format error: {0}")]211	Format(#[from] FormatError),212	#[error("type error: {0}")]213	TypeError(TypeLocError),214215	#[cfg(feature = "anyhow-error")]216	#[error(transparent)]217	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),218}219220#[cfg(feature = "anyhow-error")]221impl From<anyhow::Error> for Error {222	fn from(e: anyhow::Error) -> Self {223		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))224	}225}226227impl From<ErrorKind> for Error {228	fn from(e: ErrorKind) -> Self {229		Self::new(e)230	}231}232233impl From<Infallible> for Error {234	fn from(_value: Infallible) -> Self {235		unreachable!()236	}237}238239/// Single stack trace frame240#[derive(Clone, Debug, Trace)]241pub struct StackTraceElement {242	/// Source of this frame243	/// Some frames only act as description, without attached source244	pub location: Option<Span>,245	/// Frame description246	pub desc: String,247}248#[derive(Debug, Clone, Trace)]249pub struct StackTrace(pub Vec<StackTraceElement>);250251#[derive(Clone, Trace)]252pub struct Error(Box<(ErrorKind, StackTrace)>);253impl Error {254	pub fn new(e: ErrorKind) -> Self {255		Self(Box::new((e, StackTrace(vec![]))))256	}257258	pub const fn error(&self) -> &ErrorKind {259		&(self.0).0260	}261	pub fn error_mut(&mut self) -> &mut ErrorKind {262		&mut (self.0).0263	}264	pub const fn trace(&self) -> &StackTrace {265		&(self.0).1266	}267	pub fn trace_mut(&mut self) -> &mut StackTrace {268		&mut (self.0).1269	}270}271impl Display for Error {272	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {273		writeln!(f, "{}", self.0 .0)?;274		for el in &self.0 .1 .0 {275			write!(f, "\t{}", el.desc)?;276			if let Some(loc) = &el.location {277				write!(f, "at {}", loc.0 .0 .0)?;278				loc.0.map_source_locations(&[loc.1, loc.2]);279			}280			writeln!(f)?;281		}282		Ok(())283	}284}285impl Debug for Error {286	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {287		f.debug_tuple("LocError").field(&self.0).finish()288	}289}290impl std::error::Error for Error {}291292pub trait ErrorSource {293	fn to_location(self) -> Option<Span>;294}295impl<T: Acyclic> ErrorSource for &Spanned<T> {296	fn to_location(self) -> Option<Span> {297		Some(self.span())298	}299}300impl ErrorSource for &Span {301	fn to_location(self) -> Option<Span> {302		Some(self.clone())303	}304}305impl ErrorSource for CallLocation<'_> {306	fn to_location(self) -> Option<Span> {307		self.0.cloned()308	}309}310311pub type Result<V, E = Error> = std::result::Result<V, E>;312pub trait ResultExt: Sized {313	#[must_use]314	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;315	#[must_use]316	fn description(self, msg: &str) -> Self {317		self.with_description(|| msg)318	}319320	#[must_use]321	fn with_description_src<O: Into<String>>(322		self,323		src: impl ErrorSource,324		msg: impl FnOnce() -> O,325	) -> Self;326	#[must_use]327	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {328		self.with_description_src(src, || msg)329	}330}331impl<T> ResultExt for Result<T, Error> {332	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {333		if let Err(e) = &mut self {334			let trace = e.trace_mut();335			trace.0.push(StackTraceElement {336				location: None,337				desc: msg().into(),338			});339		}340		self341	}342343	fn with_description_src<O: Into<String>>(344		mut self,345		src: impl ErrorSource,346		msg: impl FnOnce() -> O,347	) -> Self {348		if let Err(e) = &mut self {349			let trace = e.trace_mut();350			trace.0.push(StackTraceElement {351				location: src.to_location(),352				desc: msg().into(),353			});354		}355		self356	}357}358359#[macro_export]360macro_rules! bail {361	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {362		return Err($w$(::$i)*$(($($tt)*))?.into())363	};364	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {365		return Err($w$(::$i)*$({$($tt)*})?.into())366	};367	($l:literal$(, $($tt:tt)*)?) => {368		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())369	};370}371372#[macro_export]373macro_rules! runtime_error {374	($l:literal$(, $($tt:tt)*)?) => {375		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))376	};377}
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
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -7,7 +7,10 @@
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_interner::IStr;
 
-use crate::source::Source;
+use crate::{
+	function::{FunctionSignature, ParamDefault, ParamName, ParamParse},
+	source::Source,
+};
 
 #[derive(Debug, PartialEq, Acyclic)]
 pub enum FieldName {
@@ -41,7 +44,7 @@
 pub struct FieldMember {
 	pub name: FieldName,
 	pub plus: bool,
-	pub params: Option<ParamsDesc>,
+	pub params: Option<ExprParams>,
 	pub visibility: Visibility,
 	pub value: Rc<Spanned<Expr>>,
 }
@@ -147,16 +150,41 @@
 
 /// name, default value
 #[derive(Debug, PartialEq, Acyclic)]
-pub struct Param(pub Destruct, pub Option<Rc<Spanned<Expr>>>);
+pub struct ExprParam {
+	pub destruct: Destruct,
+	pub default: Option<Rc<Spanned<Expr>>>,
+}
 
 /// Defined function parameters
 #[derive(Debug, Clone, PartialEq, Acyclic)]
-pub struct ParamsDesc(pub Rc<Vec<Param>>);
-
-impl Deref for ParamsDesc {
-	type Target = Vec<Param>;
-	fn deref(&self) -> &Self::Target {
-		&self.0
+pub struct ExprParams {
+	pub exprs: Rc<Vec<ExprParam>>,
+	pub signature: FunctionSignature,
+	binds_len: usize,
+}
+impl ExprParams {
+	pub fn len(&self) -> usize {
+		self.exprs.len()
+	}
+	pub fn binds_len(&self) -> usize {
+		self.binds_len
+	}
+	pub fn new(exprs: Vec<ExprParam>) -> Self {
+		Self {
+			signature: FunctionSignature::new(
+				exprs
+					.iter()
+					.map(|p| {
+						ParamParse::new(
+							p.destruct.name(),
+							ParamDefault::exists(p.default.is_some()),
+						)
+					})
+					.collect(),
+			),
+			binds_len: exprs.iter().map(|v| v.destruct.binds_len()).sum(),
+			exprs: Rc::new(exprs),
+		}
 	}
 }
 
@@ -198,14 +226,14 @@
 }
 impl Destruct {
 	/// Name of destructure, used for function parameter names
-	pub fn name(&self) -> Option<IStr> {
-		match self {
+	pub fn name(&self) -> ParamName {
+		ParamName(match self {
 			Self::Full(name) => Some(name.clone()),
 			#[cfg(feature = "exp-destruct")]
 			_ => None,
-		}
+		})
 	}
-	pub fn capacity_hint(&self) -> usize {
+	pub fn binds_len(&self) -> usize {
 		#[cfg(feature = "exp-destruct")]
 		fn cap_rest(rest: &Option<DestructRest>) -> usize {
 			match rest {
@@ -220,8 +248,8 @@
 			Self::Skip => 0,
 			#[cfg(feature = "exp-destruct")]
 			Self::Array { start, rest, end } => {
-				start.iter().map(Destruct::capacity_hint).sum::<usize>()
-					+ end.iter().map(Destruct::capacity_hint).sum::<usize>()
+				start.iter().map(Destruct::binds_len).sum::<usize>()
+					+ end.iter().map(Destruct::binds_len).sum::<usize>()
 					+ cap_rest(rest)
 			}
 			#[cfg(feature = "exp-destruct")]
@@ -248,14 +276,14 @@
 	},
 	Function {
 		name: IStr,
-		params: ParamsDesc,
+		params: ExprParams,
 		value: Rc<Spanned<Expr>>,
 	},
 }
 impl BindSpec {
-	pub fn capacity_hint(&self) -> usize {
+	pub fn binds_len(&self) -> usize {
 		match self {
-			BindSpec::Field { into, .. } => into.capacity_hint(),
+			BindSpec::Field { into, .. } => into.binds_len(),
 			BindSpec::Function { .. } => 1,
 		}
 	}
@@ -396,7 +424,7 @@
 		parts: Vec<IndexPart>,
 	},
 	/// function(x) x
-	Function(ParamsDesc, Rc<Spanned<Expr>>),
+	Function(ExprParams, Rc<Spanned<Expr>>),
 	/// if true == false then 1 else 2
 	IfElse(Box<IfElse>),
 	Slice(Box<Slice>),
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,