git.delta.rocks / jrsonnet / refs/commits / 0111266c91b4

difftreelog

perf use prepared call for KeyF

szllnstvYaroslav Bolyukin2026-03-21parent: #5df60b8.patch.diff
in: master

9 files changed

modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -3,8 +3,8 @@
 use jrsonnet_gcmodule::{cc_dyn, Trace, TraceBox};
 use jrsonnet_parser::function::{FunctionSignature, ParamDefault, ParamName, ParamParse};
 
-use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
-use crate::{Context, Result, Val};
+use super::CallLocation;
+use crate::{Result, Thunk, Val};
 
 #[macro_export]
 macro_rules! params {
@@ -34,8 +34,8 @@
 		self.0.params()
 	}
 
-	fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val> {
-		self.0.call(ctx, loc, args)
+	fn call(&self, loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val> {
+		self.0.call(loc, args)
 	}
 
 	fn as_any(&self) -> &dyn Any {
@@ -52,7 +52,7 @@
 	/// Parameter names for named calls
 	fn params(&self) -> FunctionSignature;
 	/// Call the builtin
-	fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val>;
+	fn call(&self, loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val>;
 
 	fn as_any(&self) -> &dyn Any;
 }
@@ -96,11 +96,10 @@
 		self.params.clone()
 	}
 
-	fn call(&self, ctx: Context, _loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val> {
-		let args = parse_builtin_call(ctx, self.params.clone(), args, true)?;
+	fn call(&self, _loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val> {
 		let args = args
 			.into_iter()
-			.map(|a| a.expect("legacy natives have no default params"))
+			.map(|a| a.as_ref().expect("legacy natives have no default params"))
 			.map(|a| a.evaluate())
 			.collect::<Result<Vec<Val>>>()?;
 		self.handler.call(&args)
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/function/mod.rs
1use std::{fmt::Debug, rc::Rc};23pub use arglike::{ArgLike, ArgsLike, TlaArg};4use educe::Educe;5use jrsonnet_gcmodule::{Cc, Trace};6use jrsonnet_interner::IStr;7pub use jrsonnet_macros::builtin;8use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};910use self::{11	arglike::OptionalContext,12	builtin::{Builtin, StaticBuiltin},13	native::NativeDesc,14	parse::{parse_builtin_call, parse_default_function_call, parse_function_call},15	prepared::{parse_prepared_builtin_call, parse_prepared_function_call, PreparedCall},16};17use crate::{18	bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,19	ContextBuilder, Result, Thunk, Val,20};2122pub mod arglike;23pub mod builtin;24pub mod native;25pub mod parse;26mod prepared;2728pub use prepared::PreparedFuncVal;2930pub use jrsonnet_parser::function::*;3132/// Function callsite location.33/// Either from other jsonnet code, specified by expression location, or from native (without location).34#[derive(Clone, Copy)]35pub struct CallLocation<'l>(pub Option<&'l Span>);36impl<'l> CallLocation<'l> {37	/// Construct new location for calls coming from specified jsonnet expression location.38	pub const fn new(loc: &'l Span) -> Self {39		Self(Some(loc))40	}41}42impl CallLocation<'static> {43	/// Construct new location for calls coming from native code.44	pub const fn native() -> Self {45		Self(None)46	}47}4849/// Represents Jsonnet function defined in code.50#[derive(Trace, Educe)]51#[educe(Debug, PartialEq)]52pub struct FuncDesc {53	/// # Example54	///55	/// In expressions like this, deducted to `a`, unspecified otherwise.56	/// ```jsonnet57	/// local a = function() ...58	/// local a() ...59	/// { a: function() ... }60	/// { a() = ... }61	/// ```62	pub name: IStr,63	/// Context, in which this function was evaluated.64	///65	/// # Example66	/// In67	/// ```jsonnet68	/// local a = 2;69	/// function() ...70	/// ```71	/// context will contain `a`.72	pub ctx: Context,7374	/// Function parameter definition75	pub params: ExprParams,76	/// Function body77	pub body: Rc<Spanned<Expr>>,78}79impl FuncDesc {80	/// Create body context, but fill arguments without defaults with lazy error81	pub fn default_body_context(&self) -> Result<Context> {82		parse_default_function_call(self.ctx.clone(), &self.params)83	}8485	/// Create context, with which body code will run86	pub fn call_body_context(87		&self,88		call_ctx: Context,89		args: &dyn ArgsLike,90		tailstrict: bool,91	) -> Result<Context> {92		parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)93	}9495	pub fn evaluate_trivial(&self) -> Option<Val> {96		evaluate_trivial(&self.body)97	}98}99100/// Represents a Jsonnet function value, including plain functions and user-provided builtins.101#[allow(clippy::module_name_repetitions)]102#[derive(Trace, Clone)]103pub enum FuncVal {104	/// Identity function, kept this way for comparsions.105	Id,106	/// Plain function implemented in jsonnet.107	Normal(Cc<FuncDesc>),108	/// Function without arguments works just as a fancy thunk value.109	Thunk(Thunk<Val>),110	/// Standard library function.111	StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),112	/// User-provided function.113	Builtin(BuiltinFunc),114}115116impl Debug for FuncVal {117	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {118		match self {119			Self::Id => f.debug_tuple("Id").finish(),120			Self::Thunk(arg0) => f.debug_tuple("Thunk").field(arg0).finish(),121			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),122			Self::StaticBuiltin(arg0) => {123				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()124			}125			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),126		}127	}128}129130#[allow(clippy::unnecessary_wraps)]131#[builtin]132const fn builtin_id(x: Val) -> Val {133	x134}135static ID: &builtin_id = &builtin_id {};136137impl FuncVal {138	pub fn builtin(builtin: impl Builtin) -> Self {139		Self::Builtin(BuiltinFunc::new(builtin))140	}141	pub fn static_builtin(static_builtin: &'static dyn StaticBuiltin) -> Self {142		Self::StaticBuiltin(static_builtin)143	}144145	pub fn params(&self) -> FunctionSignature {146		match self {147			Self::Id => ID.params(),148			Self::StaticBuiltin(i) => i.params(),149			Self::Builtin(i) => i.params(),150			Self::Normal(p) => p.params.signature.clone(),151			Self::Thunk(_) => FunctionSignature::empty(),152		}153	}154	/// Amount of non-default required arguments155	pub fn params_len(&self) -> usize {156		self.params().iter().filter(|p| !p.has_default()).count()157	}158	/// Function name, as defined in code.159	pub fn name(&self) -> IStr {160		match self {161			Self::Id => "id".into(),162			Self::Normal(normal) => normal.name.clone(),163			Self::StaticBuiltin(builtin) => builtin.name().into(),164			Self::Builtin(builtin) => builtin.name().into(),165			Self::Thunk(_) => "thunk".into(),166		}167	}168	/// Call function using arguments evaluated in specified `call_ctx` [`Context`].169	///170	/// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.171	pub fn evaluate(172		&self,173		call_ctx: Context,174		loc: CallLocation<'_>,175		args: &dyn ArgsLike,176		tailstrict: bool,177	) -> Result<Val> {178		match self {179			Self::Normal(func) => {180				let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;181				evaluate(body_ctx, &func.body)182			}183			Self::Thunk(thunk) => {184				if !args.is_empty() {185					bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))186				}187				thunk.evaluate()188			}189			Self::Id => {190				let args = parse_builtin_call(call_ctx, ID.params(), args, tailstrict)?;191				ID.call(loc, &args)192			}193			Self::StaticBuiltin(b) => {194				let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;195				b.call(loc, &args)196			}197			Self::Builtin(b) => {198				let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;199				b.call(loc, &args)200			}201		}202	}203	pub fn evaluate_simple<A: ArgsLike + OptionalContext>(204		&self,205		args: &A,206		tailstrict: bool,207	) -> Result<Val> {208		self.evaluate(209			ContextBuilder::new().build(),210			CallLocation::native(),211			args,212			tailstrict,213		)214	}215216	pub(crate) fn evaluate_prepared(217		&self,218		prepared: &PreparedCall,219		loc: CallLocation<'_>,220		unnamed: &[Thunk<Val>],221		named: &[Thunk<Val>],222		_tailstrict: bool,223	) -> Result<Val> {224		match self {225			FuncVal::Id => {226				let args = parse_prepared_builtin_call(prepared, ID.params(), unnamed, named)?;227				ID.call(loc, &args)228			}229			FuncVal::Normal(func) => {230				let body_ctx = parse_prepared_function_call(231					func.ctx.clone(),232					prepared,233					&func.params,234					unnamed,235					named,236				)?;237				evaluate(body_ctx, &func.body)238			}239			FuncVal::Thunk(t) => t.evaluate(),240			FuncVal::StaticBuiltin(b) => {241				let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;242				b.call(loc, &args)243			}244			FuncVal::Builtin(b) => {245				let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;246				b.call(loc, &args)247			}248		}249	}250	/// Convert jsonnet function to plain `Fn` value.251	pub fn into_native<D: NativeDesc>(self) -> D::Value {252		D::into_native(self)253	}254255	/// Is this function an indentity function.256	///257	/// Currently only works for builtin `std.id`, aka `Self::Id` value, and `function(x) x`.258	///259	/// This function should only be used for optimization, not for the conditional logic, i.e code should work with syntetic identity function too260	pub fn is_identity(&self) -> bool {261		match self {262			Self::Id => true,263			Self::Normal(desc) => {264				if desc.params.len() != 1 {265					return false;266				}267				let param = &desc.params.exprs[0];268				if param.default.is_some() {269					return false;270				}271272				#[allow(clippy::infallible_destructuring_match)]273				let id = match &param.destruct {274					Destruct::Full(id) => id,275					#[cfg(feature = "exp-destruct")]276					_ => return false,277				};278				**desc.body == Expr::Var(id.clone())279			}280			_ => false,281		}282	}283	/// Identity function value.284	pub const fn identity() -> Self {285		Self::Id286	}287288	pub fn evaluate_trivial(&self) -> Option<Val> {289		match self {290			Self::Normal(n) => n.evaluate_trivial(),291			_ => None,292		}293	}294}295296impl<T> From<T> for FuncVal297where298	T: Builtin,299{300	fn from(value: T) -> Self {301		Self::builtin(value)302	}303}304impl From<&'static dyn StaticBuiltin> for FuncVal {305	fn from(value: &'static dyn StaticBuiltin) -> Self {306		Self::static_builtin(value)307	}308}
modifiedcrates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -1,3 +1,6 @@
+use std::rc::Rc;
+
+use jrsonnet_gcmodule::{Acyclic, Trace};
 use jrsonnet_parser::function::FunctionSignature;
 use jrsonnet_parser::{ExprParams, IStr};
 use rustc_hash::{FxHashMap, FxHashSet};
@@ -7,6 +10,34 @@
 use crate::{bail, error::ErrorKind::*, Result};
 use crate::{evaluate_named_param, Context, ContextBuilder, Pending, Thunk, Val};
 
+use super::{CallLocation, FuncVal};
+
+#[derive(Debug, Trace, Clone)]
+pub struct PreparedFuncVal {
+	fun: FuncVal,
+	prepared: Rc<PreparedCall>,
+}
+
+impl PreparedFuncVal {
+	pub fn new(fun: FuncVal, unnamed: usize, named: &[IStr]) -> Result<Self> {
+		let prepared = prepare_call(fun.params(), unnamed, named)?;
+		Ok(Self {
+			fun,
+			prepared: Rc::new(prepared),
+		})
+	}
+	pub fn call(
+		&self,
+		loc: CallLocation<'_>,
+		unnamed: &[Thunk<Val>],
+		named: &[Thunk<Val>],
+	) -> Result<Val> {
+		self.fun
+			.evaluate_prepared(&self.prepared, loc, unnamed, named, false)
+	}
+}
+
+#[derive(Acyclic, Debug)]
 pub struct PreparedCall {
 	// Param, named input.
 	named: Vec<(usize, usize)>,
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -3,16 +3,32 @@
 use proc_macro2::TokenStream;
 use quote::{quote, quote_spanned};
 use syn::{
-	parenthesized,
-	parse::{Parse, ParseStream},
-	parse_macro_input,
-	punctuated::Punctuated,
-	spanned::Spanned,
-	token::{self, Comma},
-	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
-	LitStr, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
+	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn, LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type, parenthesized, parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, spanned::Spanned, token::{self, Comma}
 };
 
+fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
+where
+	Ident: PartialEq<I>,
+{
+	let attrs = attrs
+		.iter()
+		.filter(|a| a.path().is_ident(&ident))
+		.collect::<Vec<_>>();
+	if attrs.len() > 1 {
+		return Err(Error::new(
+			attrs[1].span(),
+			"this attribute may be specified only once",
+		));
+	} else if attrs.is_empty() {
+		return Ok(false);
+	}
+	let attr = attrs[0];
+
+	match attr.meta {
+		Meta::Path(_) => Ok(true),
+		_ => Ok(false),
+	}
+}
 fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>
 where
 	Ident: PartialEq<I>,
@@ -125,9 +141,13 @@
 	Required,
 	Optional,
 	Default(Expr),
+	TypeDefault,
 }
 
-#[allow(clippy::large_enum_variant, reason = "this macro is not that hot for it to matter")]
+#[allow(
+	clippy::large_enum_variant,
+	reason = "this macro is not that hot for it to matter"
+)]
 enum ArgInfo {
 	Normal {
 		ty: Box<Type>,
@@ -170,7 +190,10 @@
 			_ => {}
 		}
 
-		let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
+		let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {
+			remove_attr(&mut arg.attrs, "default");
+			(Optionality::TypeDefault, ty.clone())
+		} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
 			remove_attr(&mut arg.attrs, "default");
 			(Optionality::Default(default), ty.clone())
 		} else if let Some(ty) = extract_type_from_option(ty)? {
@@ -245,7 +268,7 @@
 				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
 			let default = match optionality {
 				Optionality::Required => quote!(ParamDefault::None),
-				Optionality::Optional => quote!(ParamDefault::Exists),
+				Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),
 				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),
 			};
 			Some(quote! {
@@ -305,6 +328,12 @@
 						let v: #ty = #expr;
 						v
 					},},
+					Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {
+						#eval
+					} else {
+						let v: #ty = Default::default();
+						v
+					},},
 				};
 				quote! {
 					#(#cfg_attrs)*
@@ -371,7 +400,7 @@
 				State, Val,
 				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},
 				Result, Context, typed::Typed,
-				parser::Span, params,
+				parser::Span, params, Thunk,
 			};
 			params!(
 				#(#params_desc)*
@@ -389,9 +418,7 @@
 					PARAMS.with(|p| p.clone())
 				}
 				#[allow(unused_variables)]
-				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
-					let parsed = parse_builtin_call(ctx.clone(), self.params(), args, false)?;
-
+				fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {
 					let result: #result = #name(#(#pass)*);
 					<_ as Typed>::into_result(result)
 				}
addedcrates/jrsonnet-stdlib/src/keyf.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/keyf.rs
@@ -0,0 +1,41 @@
+use jrsonnet_evaluator::function::{CallLocation, FuncVal, PreparedFuncVal};
+use jrsonnet_evaluator::typed::{ComplexValType, Typed, ValType};
+use jrsonnet_evaluator::{Error, Result, Thunk, Val};
+
+#[derive(Default, Clone)]
+pub enum KeyF {
+	#[default]
+	Identity,
+	Prepared(PreparedFuncVal),
+	PrepareFailure(Error),
+}
+impl KeyF {
+	pub fn is_identity(&self) -> bool {
+		matches!(self, Self::Identity)
+	}
+	fn new(val: FuncVal) -> Self {
+		if val.is_identity() {
+			Self::Identity
+		} else {
+			PreparedFuncVal::new(val, 1, &[]).map_or_else(Self::PrepareFailure, Self::Prepared)
+		}
+	}
+	pub fn eval(&self, val: impl Into<Thunk<Val>>) -> Result<Val> {
+		match self {
+			KeyF::Identity => val.into().evaluate(),
+			KeyF::Prepared(p) => p.call(CallLocation::native(), &[val.into()], &[]),
+			KeyF::PrepareFailure(e) => Err(e.clone()),
+		}
+	}
+}
+
+impl Typed for KeyF {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+	fn from_untyped(untyped: Val) -> Result<Self> {
+		FuncVal::from_untyped(untyped).map(Self::new)
+	}
+
+	fn into_untyped(_typed: Self) -> Result<Val> {
+		unreachable!("unused, todo: port split of Typed trait from #193")
+	}
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -50,6 +50,7 @@
 mod sort;
 mod strings;
 mod types;
+mod keyf;
 
 #[allow(clippy::too_many_lines)]
 pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {
modifiedcrates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,28 +1,23 @@
 use std::cmp::Ordering;
 
 use jrsonnet_evaluator::{
-	function::{builtin, FuncVal},
-	operator::evaluate_compare_op,
-	val::ArrValue,
-	Result, Thunk, Val,
+	function::builtin, operator::evaluate_compare_op, val::ArrValue, Result, Thunk, Val,
 };
 use jrsonnet_parser::BinaryOpType;
 
+use crate::keyf::KeyF;
+
 #[builtin]
 #[allow(non_snake_case)]
-pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, keyF: Option<FuncVal>) -> Result<bool> {
+pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, #[default] keyF: KeyF) -> Result<bool> {
 	let mut low = 0;
 	let mut high = arr.len();
 
-	let keyF = keyF
-		.unwrap_or(FuncVal::Id)
-		.into_native::<((Thunk<Val>,), Val)>();
-
-	let x = keyF(x)?;
+	let x = keyF.eval(x)?;
 
 	while low < high {
 		let middle = usize::midpoint(high, low);
-		let comp = keyF(arr.get_lazy(middle).expect("in bounds"))?;
+		let comp = keyF.eval(arr.get_lazy(middle).expect("in bounds"))?;
 		match evaluate_compare_op(&comp, &x, BinaryOpType::Lt)? {
 			Ordering::Less => low = middle + 1,
 			Ordering::Equal => return Ok(true),
@@ -34,14 +29,11 @@
 
 #[builtin]
 #[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_inter(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+pub fn builtin_set_inter(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	let mut a = a.iter_lazy();
 	let mut b = b.iter_lazy();
 
-	let keyF = keyF
-		.unwrap_or(FuncVal::identity())
-		.into_native::<((Thunk<Val>,), Val)>();
-	let keyF = |v| keyF(v);
+	let keyF = |v| keyF.eval(v);
 
 	let mut av = a.next();
 	let mut bv = b.next();
@@ -73,14 +65,11 @@
 
 #[builtin]
 #[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+pub fn builtin_set_diff(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	let mut a = a.iter_lazy();
 	let mut b = b.iter_lazy();
 
-	let keyF = keyF
-		.unwrap_or(FuncVal::identity())
-		.into_native::<((Thunk<Val>,), Val)>();
-	let keyF = |v| keyF(v);
+	let keyF = |v| keyF.eval(v);
 
 	let mut av = a.next();
 	let mut bv = b.next();
@@ -119,14 +108,11 @@
 
 #[builtin]
 #[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_union(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+pub fn builtin_set_union(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	let mut a = a.iter_lazy();
 	let mut b = b.iter_lazy();
 
-	let keyF = keyF
-		.unwrap_or(FuncVal::identity())
-		.into_native::<((Thunk<Val>,), Val)>();
-	let keyF = |v| keyF(v);
+	let keyF = |v| keyF.eval(v);
 
 	let mut av = a.next();
 	let mut bv = b.next();
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -4,14 +4,14 @@
 
 use jrsonnet_evaluator::{
 	bail,
-	function::{builtin, FuncVal},
+	function::builtin,
 	operator::evaluate_compare_op,
 	val::{equals, ArrValue},
 	Result, Thunk, Val,
 };
 use jrsonnet_parser::BinaryOpType;
 
-use crate::eval_on_empty;
+use crate::{eval_on_empty, keyf::KeyF};
 
 #[derive(Copy, Clone)]
 enum SortKeyType {
@@ -70,14 +70,11 @@
 	Ok(values)
 }
 
-fn sort_keyf(values: ArrValue, keyf: FuncVal) -> Result<Vec<Thunk<Val>>> {
+fn sort_keyf(values: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
 	// Slow path, user provided key getter
 	let mut vk = Vec::with_capacity(values.len());
 	for value in values.iter_lazy() {
-		vk.push((
-			value.clone(),
-			keyf.evaluate_simple(&(value.clone(),), false)?,
-		));
+		vk.push((value.clone(), keyf.eval(value)?));
 	}
 	let sort_type = get_sort_type(&vk, |v| &v.1)?;
 	match sort_type {
@@ -112,7 +109,7 @@
 }
 
 /// * `key_getter` - None, if identity sort required
-pub fn sort(values: ArrValue, key_getter: FuncVal) -> Result<ArrValue> {
+pub fn sort(values: ArrValue, key_getter: KeyF) -> Result<ArrValue> {
 	if values.len() <= 1 {
 		return Ok(values);
 	}
@@ -126,11 +123,7 @@
 }
 
 #[builtin]
-pub fn builtin_sort(
-	arr: ArrValue,
-
-	#[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_sort(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	super::sort::sort(arr, keyF)
 }
 
@@ -147,14 +140,14 @@
 	Ok(out)
 }
 
-fn uniq_keyf(arr: ArrValue, keyf: FuncVal) -> Result<Vec<Thunk<Val>>> {
+fn uniq_keyf(arr: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
 	let mut out = Vec::new();
 	let last_value = arr.get_lazy(0).unwrap();
-	let mut last_key = keyf.evaluate_simple(&(last_value.clone(),), false)?;
+	let mut last_key = keyf.eval(last_value.clone())?;
 	out.push(last_value);
 
 	for next in arr.iter_lazy().skip(1) {
-		let next_key = keyf.evaluate_simple(&(next.clone(),), false)?;
+		let next_key = keyf.eval(next.clone())?;
 		if !equals(&last_key, &next_key)? {
 			out.push(next.clone());
 		}
@@ -165,11 +158,7 @@
 
 #[builtin]
 #[allow(non_snake_case)]
-pub fn builtin_uniq(
-	arr: ArrValue,
-
-	#[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_uniq(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	if arr.len() <= 1 {
 		return Ok(arr);
 	}
@@ -184,11 +173,7 @@
 
 #[builtin]
 #[allow(non_snake_case)]
-pub fn builtin_set(
-	arr: ArrValue,
-
-	#[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_set(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
 	if arr.len() <= 1 {
 		return Ok(arr);
 	}
@@ -201,24 +186,16 @@
 		let arr = sort_keyf(arr, keyF.clone())?;
 		let arr = uniq_keyf(ArrValue::lazy(arr), keyF)?;
 		Ok(ArrValue::lazy(arr))
-	}
-}
-
-fn eval_keyf(val: Val, key_f: Option<&FuncVal>) -> Result<Val> {
-	if let Some(key_f) = key_f {
-		key_f.evaluate_simple(&(val,), false)
-	} else {
-		Ok(val)
 	}
 }
 
-fn array_top1(arr: ArrValue, key_f: Option<&FuncVal>, ordering: Ordering) -> Result<Val> {
+fn array_top1(arr: ArrValue, keyf: KeyF, ordering: Ordering) -> Result<Val> {
 	let mut iter = arr.iter();
 	let mut min = iter.next().expect("not empty")?;
-	let mut min_key = eval_keyf(min.clone(), key_f)?;
+	let mut min_key = keyf.eval(Thunk::evaluated(min.clone()))?;
 	for item in iter {
 		let cur = item?;
-		let cur_key = eval_keyf(cur.clone(), key_f)?;
+		let cur_key = keyf.eval(Thunk::evaluated(cur.clone()))?;
 		if evaluate_compare_op(&cur_key, &min_key, BinaryOpType::Lt)? == ordering {
 			min = cur;
 			min_key = cur_key;
@@ -230,22 +207,22 @@
 #[builtin]
 pub fn builtin_min_array(
 	arr: ArrValue,
-	keyF: Option<FuncVal>,
+	#[default] keyF: KeyF,
 	onEmpty: Option<Thunk<Val>>,
 ) -> Result<Val> {
 	if arr.is_empty() {
 		return eval_on_empty(onEmpty);
 	}
-	array_top1(arr, keyF.as_ref(), Ordering::Less)
+	array_top1(arr, keyF, Ordering::Less)
 }
 #[builtin]
 pub fn builtin_max_array(
 	arr: ArrValue,
-	keyF: Option<FuncVal>,
+	#[default] keyF: KeyF,
 	onEmpty: Option<Thunk<Val>>,
 ) -> Result<Val> {
 	if arr.is_empty() {
 		return eval_on_empty(onEmpty);
 	}
-	array_top1(arr, keyF.as_ref(), Ordering::Greater)
+	array_top1(arr, keyF, Ordering::Greater)
 }
modifiedtests/tests/builtin.rsdiffbeforeafterboth
--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -18,8 +18,7 @@
 #[test]
 fn basic_function() -> Result<()> {
 	let a: a = a {};
-	let v =
-		u32::from_untyped(a.call(ContextBuilder::new().build(), CallLocation::native(), &())?)?;
+	let v = u32::from_untyped(a.call(CallLocation::native(), &[])?)?;
 
 	ensure_eq!(v, 1);
 	Ok(())