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

difftreelog

refactor use PreparedFunction for NativeFn

kutrystyYaroslav Bolyukin2026-03-21parent: #0111266.patch.diff
in: master

9 files changed

modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -1,14 +1,15 @@
 use std::{
 	any::Any,
 	fmt::{self},
-	num::NonZeroU32, rc::Rc,
+	num::NonZeroU32,
+	rc::Rc,
 };
 
 use jrsonnet_gcmodule::{cc_dyn, Cc};
 use jrsonnet_interner::IBytes;
 use jrsonnet_parser::{Expr, Spanned};
 
-use crate::{function::FuncVal, Context, Result, Thunk, Val};
+use crate::{typed::NativeFn, Context, Result, Thunk, Val};
 
 mod spec;
 pub use spec::{ArrayLike, *};
@@ -61,13 +62,13 @@
 	}
 
 	#[must_use]
-	pub fn map(self, mapper: FuncVal) -> Self {
-		Self::new(<MappedArray<false>>::new(self, mapper))
+	pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {
+		Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))
 	}
 
 	#[must_use]
-	pub fn map_with_index(self, mapper: FuncVal) -> Self {
-		Self::new(<MappedArray<true>>::new(self, mapper))
+	pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {
+		Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))
 	}
 
 	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/arr/spec.rs
1use std::rc::Rc;2use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace};34use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::{IBytes, IStr};6use jrsonnet_parser::{Expr, Spanned};78use super::ArrValue;9use crate::typed::NativeFn;10use crate::val::NumValue;11use crate::{12	error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,13	Error, ObjValue, Result, Thunk, Val,14};1516pub trait ArrayLike: Any + Trace + Debug {17	fn len(&self) -> usize;18	fn is_empty(&self) -> bool {19		self.len() == 020	}21	fn get(&self, index: usize) -> Result<Option<Val>>;22	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;23	fn get_cheap(&self, index: usize) -> Option<Val>;2425	fn is_cheap(&self) -> bool;26}2728#[derive(Debug, Trace)]29pub struct SliceArray {30	pub(crate) inner: ArrValue,31	pub(crate) from: u32,32	pub(crate) to: u32,33	pub(crate) step: u32,34}3536impl SliceArray {37	fn map_idx(&self, index: usize) -> usize {38		self.from as usize + self.step as usize * index39	}40}41impl ArrayLike for SliceArray {42	fn len(&self) -> usize {43		(self.to - self.from).div_ceil(self.step) as usize44	}4546	fn get(&self, index: usize) -> Result<Option<Val>> {47		self.inner.get(self.map_idx(index))48	}4950	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {51		self.inner.get_lazy(self.map_idx(index))52	}5354	fn get_cheap(&self, index: usize) -> Option<Val> {55		self.inner.get_cheap(self.map_idx(index))56	}57	fn is_cheap(&self) -> bool {58		self.inner.is_cheap()59	}60}6162#[derive(Trace, Debug)]63pub struct CharArray(pub Vec<char>);64impl ArrayLike for CharArray {65	fn len(&self) -> usize {66		self.0.len()67	}6869	fn get(&self, index: usize) -> Result<Option<Val>> {70		Ok(self.get_cheap(index))71	}7273	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {74		self.get_cheap(index).map(Thunk::evaluated)75	}7677	fn get_cheap(&self, index: usize) -> Option<Val> {78		self.0.get(index).map(|v| Val::string(*v))79	}80	fn is_cheap(&self) -> bool {81		true82	}83}8485#[derive(Trace, Debug)]86pub struct BytesArray(pub IBytes);87impl ArrayLike for BytesArray {88	fn len(&self) -> usize {89		self.0.len()90	}9192	fn get(&self, index: usize) -> Result<Option<Val>> {93		Ok(self.get_cheap(index))94	}9596	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {97		self.get_cheap(index).map(Thunk::evaluated)98	}99100	fn get_cheap(&self, index: usize) -> Option<Val> {101		self.0.get(index).map(|v| Val::Num((*v).into()))102	}103	fn is_cheap(&self) -> bool {104		true105	}106}107108#[derive(Debug, Trace, Clone)]109enum ArrayThunk {110	Computed(Val),111	Errored(Error),112	Waiting,113	Pending,114}115116#[derive(Debug, Trace, Clone)]117pub struct ExprArray {118	ctx: Context,119	src: Rc<Vec<Spanned<Expr>>>,120	cached: Cc<RefCell<Vec<ArrayThunk>>>,121}122impl ExprArray {123	pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {124		Self {125			ctx,126			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),127			src,128		}129	}130}131impl ArrayLike for ExprArray {132	fn len(&self) -> usize {133		self.cached.borrow().len()134	}135	fn get(&self, index: usize) -> Result<Option<Val>> {136		if index >= self.len() {137			return Ok(None);138		}139		match &self.cached.borrow()[index] {140			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),141			ArrayThunk::Errored(e) => return Err(e.clone()),142			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),143			ArrayThunk::Waiting => {}144		}145146		let ArrayThunk::Waiting =147			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)148		else {149			unreachable!()150		};151152		let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {153			Ok(v) => v,154			Err(e) => {155				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());156				return Err(e);157			}158		};159		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());160		Ok(Some(new_value))161	}162	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {163		#[derive(Trace)]164		struct ExprArrThunk {165			expr: ExprArray,166			index: usize,167		}168		impl ThunkValue for ExprArrThunk {169			type Output = Val;170171			fn get(&self) -> Result<Self::Output> {172				self.expr173					.get(self.index)174					.transpose()175					.expect("index checked")176			}177		}178179		if index >= self.len() {180			return None;181		}182		match &self.cached.borrow()[index] {183			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),184			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),185			ArrayThunk::Waiting | ArrayThunk::Pending => {}186		}187188		Some(Thunk::new(ExprArrThunk {189			expr: self.clone(),190			index,191		}))192	}193	fn get_cheap(&self, _index: usize) -> Option<Val> {194		None195	}196	fn is_cheap(&self) -> bool {197		false198	}199}200201#[derive(Trace, Debug)]202pub struct ExtendedArray {203	pub a: ArrValue,204	pub b: ArrValue,205	split: usize,206	len: usize,207}208impl ExtendedArray {209	pub fn new(a: ArrValue, b: ArrValue) -> Self {210		let a_len = a.len();211		let b_len = b.len();212		Self {213			a,214			b,215			split: a_len,216			len: a_len.checked_add(b_len).expect("too large array value"),217		}218	}219}220221struct WithExactSize<I>(I, usize);222impl<I, T> Iterator for WithExactSize<I>223where224	I: Iterator<Item = T>,225{226	type Item = T;227228	fn next(&mut self) -> Option<Self::Item> {229		self.0.next()230	}231	fn nth(&mut self, n: usize) -> Option<Self::Item> {232		self.0.nth(n)233	}234	fn size_hint(&self) -> (usize, Option<usize>) {235		(self.1, Some(self.1))236	}237}238impl<I> DoubleEndedIterator for WithExactSize<I>239where240	I: DoubleEndedIterator,241{242	fn next_back(&mut self) -> Option<Self::Item> {243		self.0.next_back()244	}245	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {246		self.0.nth_back(n)247	}248}249impl<I> ExactSizeIterator for WithExactSize<I>250where251	I: Iterator,252{253	fn len(&self) -> usize {254		self.1255	}256}257impl ArrayLike for ExtendedArray {258	fn get(&self, index: usize) -> Result<Option<Val>> {259		if self.split > index {260			self.a.get(index)261		} else {262			self.b.get(index - self.split)263		}264	}265	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {266		if self.split > index {267			self.a.get_lazy(index)268		} else {269			self.b.get_lazy(index - self.split)270		}271	}272273	fn len(&self) -> usize {274		self.len275	}276277	fn get_cheap(&self, index: usize) -> Option<Val> {278		if self.split > index {279			self.a.get_cheap(index)280		} else {281			self.b.get_cheap(index - self.split)282		}283	}284	fn is_cheap(&self) -> bool {285		self.a.is_cheap() && self.b.is_cheap()286	}287}288289#[derive(Trace, Debug)]290pub struct LazyArray(pub Vec<Thunk<Val>>);291impl ArrayLike for LazyArray {292	fn len(&self) -> usize {293		self.0.len()294	}295	fn get(&self, index: usize) -> Result<Option<Val>> {296		let Some(v) = self.0.get(index) else {297			return Ok(None);298		};299		v.evaluate().map(Some)300	}301	fn get_cheap(&self, _index: usize) -> Option<Val> {302		None303	}304	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {305		self.0.get(index).cloned()306	}307	fn is_cheap(&self) -> bool {308		false309	}310}311312#[derive(Trace, Debug)]313pub struct EagerArray(pub Vec<Val>);314impl ArrayLike for EagerArray {315	fn len(&self) -> usize {316		self.0.len()317	}318319	fn get(&self, index: usize) -> Result<Option<Val>> {320		Ok(self.0.get(index).cloned())321	}322323	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {324		self.0.get(index).cloned().map(Thunk::evaluated)325	}326327	fn get_cheap(&self, index: usize) -> Option<Val> {328		self.0.get(index).cloned()329	}330	fn is_cheap(&self) -> bool {331		true332	}333}334335/// Inclusive range type336#[derive(Debug, Trace, PartialEq, Eq)]337pub struct RangeArray {338	start: i32,339	end: i32,340}341impl RangeArray {342	pub fn empty() -> Self {343		Self::new_exclusive(0, 0)344	}345	pub fn new_exclusive(start: i32, end: i32) -> Self {346		end.checked_sub(1)347			.map_or_else(Self::empty, |end| Self { start, end })348	}349	pub fn new_inclusive(start: i32, end: i32) -> Self {350		Self { start, end }351	}352	fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {353		WithExactSize(354			self.start..=self.end,355			(self.end as usize)356				.wrapping_sub(self.start as usize)357				.wrapping_add(1),358		)359	}360}361362impl ArrayLike for RangeArray {363	fn len(&self) -> usize {364		self.range().len()365	}366	fn is_empty(&self) -> bool {367		self.range().len() == 0368	}369370	fn get(&self, index: usize) -> Result<Option<Val>> {371		Ok(self.get_cheap(index))372	}373374	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {375		self.get_cheap(index).map(Thunk::evaluated)376	}377378	fn get_cheap(&self, index: usize) -> Option<Val> {379		self.range().nth(index).map(|i| Val::Num(i.into()))380	}381	fn is_cheap(&self) -> bool {382		true383	}384}385386#[derive(Debug, Trace)]387pub struct ReverseArray(pub ArrValue);388impl ArrayLike for ReverseArray {389	fn len(&self) -> usize {390		self.0.len()391	}392393	fn get(&self, index: usize) -> Result<Option<Val>> {394		self.0.get(self.0.len() - index - 1)395	}396397	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {398		self.0.get_lazy(self.0.len() - index - 1)399	}400401	fn get_cheap(&self, index: usize) -> Option<Val> {402		self.0.get_cheap(self.0.len() - index - 1)403	}404	fn is_cheap(&self) -> bool {405		self.0.is_cheap()406	}407}408409#[derive(Trace, Clone, Debug)]410pub enum ArrayMapper {411	Plain(NativeFn!((Val) -> Val)),412	WithIndex(NativeFn!((u32, Val) -> Val)),413}414415#[derive(Trace, Debug, Clone)]416pub struct MappedArray {417	inner: ArrValue,418	cached: Cc<RefCell<Vec<ArrayThunk>>>,419	mapper: ArrayMapper,420}421impl MappedArray {422	pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {423		let len = inner.len();424		Self {425			inner,426			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),427			mapper,428		}429	}430	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {431		match &self.mapper {432			ArrayMapper::Plain(f) => f.call(value),433			ArrayMapper::WithIndex(f) => f.call(index as u32, value),434		}435	}436}437impl ArrayLike for MappedArray {438	fn len(&self) -> usize {439		self.cached.borrow().len()440	}441442	fn get(&self, index: usize) -> Result<Option<Val>> {443		if index >= self.len() {444			return Ok(None);445		}446		match &self.cached.borrow()[index] {447			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),448			ArrayThunk::Errored(e) => return Err(e.clone()),449			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),450			ArrayThunk::Waiting => {}451		}452453		let ArrayThunk::Waiting =454			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)455		else {456			unreachable!()457		};458459		let val = self460			.inner461			.get(index)462			.transpose()463			.expect("index checked")464			.and_then(|r| self.evaluate(index, r));465466		let new_value = match val {467			Ok(v) => v,468			Err(e) => {469				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());470				return Err(e);471			}472		};473		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());474		Ok(Some(new_value))475	}476	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {477		#[derive(Trace)]478		struct MappedArrayThunk {479			arr: MappedArray,480			index: usize,481		}482		impl ThunkValue for MappedArrayThunk {483			type Output = Val;484485			fn get(&self) -> Result<Self::Output> {486				self.arr.get(self.index).transpose().expect("index checked")487			}488		}489490		if index >= self.len() {491			return None;492		}493		match &self.cached.borrow()[index] {494			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),495			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),496			ArrayThunk::Waiting | ArrayThunk::Pending => {}497		}498499		Some(Thunk::new(MappedArrayThunk {500			arr: self.clone(),501			index,502		}))503	}504505	fn get_cheap(&self, _index: usize) -> Option<Val> {506		None507	}508	fn is_cheap(&self) -> bool {509		false510	}511}512513#[derive(Trace, Debug)]514pub struct RepeatedArray {515	data: ArrValue,516	repeats: usize,517	total_len: usize,518}519impl RepeatedArray {520	pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {521		let total_len = data.len().checked_mul(repeats)?;522		Some(Self {523			data,524			repeats,525			total_len,526		})527	}528}529530impl ArrayLike for RepeatedArray {531	fn len(&self) -> usize {532		self.total_len533	}534535	fn get(&self, index: usize) -> Result<Option<Val>> {536		if index > self.total_len {537			return Ok(None);538		}539		self.data.get(index % self.data.len())540	}541542	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {543		if index > self.total_len {544			return None;545		}546		self.data.get_lazy(index % self.data.len())547	}548549	fn get_cheap(&self, index: usize) -> Option<Val> {550		if index > self.total_len {551			return None;552		}553		self.data.get_cheap(index % self.data.len())554	}555	fn is_cheap(&self) -> bool {556		self.data.is_cheap()557	}558}559560#[derive(Trace, Debug)]561pub struct PickObjectValues {562	obj: ObjValue,563	keys: Vec<IStr>,564}565566impl PickObjectValues {567	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {568		Self { obj, keys }569	}570}571572impl ArrayLike for PickObjectValues {573	fn len(&self) -> usize {574		self.keys.len()575	}576577	fn get(&self, index: usize) -> Result<Option<Val>> {578		let Some(key) = self.keys.get(index) else {579			return Ok(None);580		};581		Ok(Some(self.obj.get_or_bail(key.clone())?))582	}583584	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {585		let key = self.keys.get(index)?;586		Some(self.obj.get_lazy_or_bail(key.clone()))587	}588589	fn get_cheap(&self, _index: usize) -> Option<Val> {590		None591	}592593	fn is_cheap(&self) -> bool {594		false595	}596}597598#[derive(Trace, Debug)]599pub struct PickObjectKeyValues {600	obj: ObjValue,601	keys: Vec<IStr>,602}603604impl PickObjectKeyValues {605	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {606		Self { obj, keys }607	}608}609610#[derive(Typed)]611pub struct KeyValue {612	key: IStr,613	value: Thunk<Val>,614}615616impl ArrayLike for PickObjectKeyValues {617	fn len(&self) -> usize {618		self.keys.len()619	}620621	fn get(&self, index: usize) -> Result<Option<Val>> {622		let Some(key) = self.keys.get(index) else {623			return Ok(None);624		};625		Ok(Some(626			KeyValue::into_untyped(KeyValue {627				key: key.clone(),628				value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),629			})630			.expect("convertible"),631		))632	}633634	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {635		let key = self.keys.get(index)?;636		// Nothing can fail in the key part, yet value is still637		// lazy-evaluated638		Some(Thunk::evaluated(639			KeyValue::into_untyped(KeyValue {640				key: key.clone(),641				value: self.obj.get_lazy_or_bail(key.clone()),642			})643			.expect("convertible"),644		))645	}646647	fn get_cheap(&self, _index: usize) -> Option<Val> {648		None649	}650651	fn is_cheap(&self) -> bool {652		false653	}654}
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -8,15 +8,13 @@
 use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};
 
 use self::{
-	arglike::OptionalContext,
 	builtin::{Builtin, StaticBuiltin},
-	native::NativeDesc,
 	parse::{parse_builtin_call, parse_default_function_call, parse_function_call},
 	prepared::{parse_prepared_builtin_call, parse_prepared_function_call, PreparedCall},
 };
 use crate::{
 	bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,
-	ContextBuilder, Result, Thunk, Val,
+	Result, Thunk, Val,
 };
 
 pub mod arglike;
@@ -199,18 +197,6 @@
 				b.call(loc, &args)
 			}
 		}
-	}
-	pub fn evaluate_simple<A: ArgsLike + OptionalContext>(
-		&self,
-		args: &A,
-		tailstrict: bool,
-	) -> Result<Val> {
-		self.evaluate(
-			ContextBuilder::new().build(),
-			CallLocation::native(),
-			args,
-			tailstrict,
-		)
 	}
 
 	pub(crate) fn evaluate_prepared(
@@ -246,10 +232,6 @@
 				b.call(loc, &args)
 			}
 		}
-	}
-	/// Convert jsonnet function to plain `Fn` value.
-	pub fn into_native<D: NativeDesc>(self) -> D::Value {
-		D::into_native(self)
 	}
 
 	/// Is this function an indentity function.
modifiedcrates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -1,43 +1,2 @@
-use super::{
-	arglike::{ArgLike, OptionalContext},
-	FuncVal,
-};
-use crate::{typed::Typed, Result};
-
-pub trait NativeDesc {
-	type Value;
-	fn into_native(val: FuncVal) -> Self::Value;
-}
-macro_rules! impl_native_desc {
-	($($gen:ident)*) => {
-		impl<$($gen,)* O> NativeDesc for (($($gen,)*), O)
-		where
-			$($gen: ArgLike + OptionalContext,)*
-			O: Typed,
-		{
-			type Value = Box<dyn Fn($($gen,)*) -> Result<O>>;
-
-			#[allow(non_snake_case)]
-			fn into_native(val: FuncVal) -> Self::Value {
-				Box::new(move |$($gen),*| {
-					let val = val.evaluate_simple(
-						&($($gen,)*),
-						false,
-					)?;
-					O::from_untyped(val)
-				})
-			}
-		}
-	};
-	($($cur:ident)* @ $c:ident $($rest:ident)*) => {
-		impl_native_desc!($($cur)*);
-		impl_native_desc!($($cur)* $c @ $($rest)*);
-	};
-	($($cur:ident)* @) => {
-		impl_native_desc!($($cur)*);
-	}
-}
-
-impl_native_desc! {
-	@ A B C D E F G H I J K L
-}
+use super::PreparedFuncVal;
+use crate::{typed::Typed, CallLocation, Result, Thunk};
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -8,7 +8,7 @@
 use crate::{
 	arr::{ArrValue, BytesArray},
 	bail,
-	function::{native::NativeDesc, FuncDesc, FuncVal},
+	function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
 	typed::CheckType,
 	val::{IndexableVal, NumValue, StrValue, ThunkMapper},
 	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
@@ -675,30 +675,65 @@
 	}
 }
 
-pub struct NativeFn<D: NativeDesc>(D::Value);
-impl<D: NativeDesc> Deref for NativeFn<D> {
-	type Target = D::Value;
+#[derive(Debug, Trace, Clone)]
+pub struct NativeFn<D: 'static>(pub(crate) PreparedFuncVal, PhantomData<D>);
+macro_rules! impl_native_desc {
+	($i:expr; $($gen:ident)*) => {
+		impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
+		where
+			$($gen: Typed,)*
+			O: Typed,
+		{
+			pub fn call(
+				&self,
+				$($gen: $gen,)*
+			) -> Result<O> {
+				let val = self.0.call(
+					CallLocation::native(),
+					&[$(Typed::into_lazy_untyped($gen),)*],
+					&[],
+				)?;
+				O::from_untyped(val)
+			}
+		}
+		impl<$($gen,)* O> Typed for NativeFn<($($gen,)* O,)> {
+			const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+
+			fn into_untyped(_typed: Self) -> Result<Val> {
+				bail!("can only convert functions from jsonnet to native")
+			}
 
-	fn deref(&self) -> &Self::Target {
-		&self.0
+			fn from_untyped(untyped: Val) -> Result<Self> {
+				let func = FuncVal::from_untyped(untyped)?;
+				Ok(Self(
+					PreparedFuncVal::new(func, $i, &[])?,
+					PhantomData,
+				))
+			}
+		}
+	};
+	($i:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {
+		impl_native_desc!($i; $($cur)*);
+		impl_native_desc!($i + 1; $($cur)* $c @ $($rest)*);
+	};
+	($i:expr; $($cur:ident)* @) => {
+		impl_native_desc!($i; $($cur)*);
 	}
 }
-impl<D: NativeDesc> Typed for NativeFn<D> {
-	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
 
-	fn into_untyped(_typed: Self) -> Result<Val> {
-		bail!("can only convert functions from jsonnet to native")
-	}
+impl_native_desc! {
+	0; @ A B C D E F G H I J K L
+}
 
-	fn from_untyped(untyped: Val) -> Result<Self> {
-		Ok(Self(
-			untyped
-				.as_func()
-				.expect("shape is checked")
-				.into_native::<D>(),
-		))
+mod native_macro {
+	#[macro_export]
+	macro_rules! NativeFn {
+		(($($t:ty),* $(,)?) -> $res:ty) => {
+			NativeFn<($($t,)* $res)>
+		}
 	}
 }
+pub use crate::NativeFn;
 
 impl Typed for NumValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -3,7 +3,14 @@
 use proc_macro2::TokenStream;
 use quote::{quote, quote_spanned};
 use syn::{
-	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}
+	parenthesized,
+	parse::{Parse, ParseStream},
+	parse_macro_input,
+	punctuated::Punctuated,
+	spanned::Spanned,
+	token::{self, Comma},
+	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
+	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
 };
 
 fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -23,7 +23,8 @@
 		return Ok(ArrValue::empty());
 	}
 	func.evaluate_trivial().map_or_else(
-		|| Ok(ArrValue::range_exclusive(0, *sz).map(func)),
+		// TODO: Different mapped array impl avoiding allocating unnecessary vals
+		|| Ok(ArrValue::range_exclusive(0, *sz).map(Typed::from_untyped(Val::Func(func))?)),
 		|trivial| {
 			let mut out = Vec::with_capacity(*sz as usize);
 			for _ in 0..*sz {
@@ -58,19 +59,22 @@
 }
 
 #[builtin]
-pub fn builtin_map(func: FuncVal, arr: IndexableVal) -> ArrValue {
+pub fn builtin_map(func: NativeFn!((Val) -> Val), arr: IndexableVal) -> ArrValue {
 	let arr = arr.to_array();
 	arr.map(func)
 }
 
 #[builtin]
-pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {
+pub fn builtin_map_with_index(func: NativeFn!((u32, Val) -> Val), arr: IndexableVal) -> ArrValue {
 	let arr = arr.to_array();
 	arr.map_with_index(func)
 }
 
 #[builtin]
-pub fn builtin_map_with_key(func: FuncVal, obj: ObjValue) -> Result<ObjValue> {
+pub fn builtin_map_with_key(
+	func: NativeFn!((IStr, Val) -> Val),
+	obj: ObjValue,
+) -> Result<ObjValue> {
 	let mut out = ObjValueBuilder::new();
 	for (k, v) in obj.iter(
 		// Makes sense mapped object should be ordered the same way, should not break anything when the output is not ordered (the default).
@@ -80,15 +84,14 @@
 		true,
 	) {
 		let v = v?;
-		out.field(k.clone())
-			.value(func.evaluate_simple(&(k, v), false)?);
+		out.field(k.clone()).value(func.call(k, v)?);
 	}
 	Ok(out.build())
 }
 
 #[builtin]
 pub fn builtin_flatmap(
-	func: NativeFn<((Either![String, Val],), Val)>,
+	func: NativeFn!((Either![String, Val]) -> Val),
 	arr: IndexableVal,
 ) -> Result<IndexableVal> {
 	use std::fmt::Write;
@@ -96,9 +99,9 @@
 		IndexableVal::Str(str) => {
 			let mut out = String::new();
 			for c in str.chars() {
-				match func(Either2::A(c.to_string()))? {
+				match func.call(Either2::A(c.to_string()))? {
 					Val::Str(o) => write!(out, "{o}").unwrap(),
-					Val::Null => {},
+					Val::Null => {}
 					_ => bail!("in std.join all items should be strings"),
 				}
 			}
@@ -108,13 +111,13 @@
 			let mut out = Vec::new();
 			for el in a.iter() {
 				let el = el?;
-				match func(Either2::B(el))? {
+				match func.call(Either2::B(el))? {
 					Val::Arr(o) => {
 						for oe in o.iter() {
 							out.push(oe?);
 						}
 					}
-					Val::Null => {},
+					Val::Null => {}
 					_ => bail!("in std.join all items should be arrays"),
 				}
 			}
@@ -123,32 +126,38 @@
 	}
 }
 
+type FilterFunc = NativeFn!((Val) -> bool);
+
 #[builtin]
-pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
-	arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))
+pub fn builtin_filter(func: FilterFunc, arr: ArrValue) -> Result<ArrValue> {
+	arr.filter(|val| func.call(val.clone()))
 }
 
 #[builtin]
 pub fn builtin_filter_map(
-	filter_func: FuncVal,
-	map_func: FuncVal,
+	filter_func: FilterFunc,
+	map_func: NativeFn!((Val) -> Val),
 	arr: ArrValue,
 ) -> Result<ArrValue> {
 	Ok(builtin_filter(filter_func, arr)?.map(map_func))
 }
 
 #[builtin]
-pub fn builtin_foldl(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {
+pub fn builtin_foldl(
+	func: NativeFn!((Val, Either![Val, char]) -> Val),
+	arr: Either![ArrValue, IStr],
+	init: Val,
+) -> Result<Val> {
 	let mut acc = init;
 	match arr {
 		Either2::A(arr) => {
 			for i in arr.iter() {
-				acc = func.evaluate_simple(&(acc, i?), false)?;
+				acc = func.call(acc, Either2::A(i?))?;
 			}
 		}
 		Either2::B(arr) => {
-			for i in arr.chars() {
-				acc = func.evaluate_simple(&(acc, Val::string(i)), false)?;
+			for c in arr.chars() {
+				acc = func.call(acc, Either2::B(c))?;
 			}
 		}
 	}
@@ -156,17 +165,21 @@
 }
 
 #[builtin]
-pub fn builtin_foldr(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {
+pub fn builtin_foldr(
+	func: NativeFn!((Either![Val, char], Val) -> Val),
+	arr: Either![ArrValue, IStr],
+	init: Val,
+) -> Result<Val> {
 	let mut acc = init;
 	match arr {
 		Either2::A(arr) => {
 			for i in arr.iter().rev() {
-				acc = func.evaluate_simple(&(i?, acc), false)?;
+				acc = func.call(Either2::A(i?), acc)?;
 			}
 		}
 		Either2::B(arr) => {
-			for i in arr.chars().rev() {
-				acc = func.evaluate_simple(&(Val::string(i), acc), false)?;
+			for c in arr.chars().rev() {
+				acc = func.call(Either2::B(c), acc)?;
 			}
 		}
 	}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -38,6 +38,7 @@
 mod compat;
 mod encoding;
 mod hash;
+mod keyf;
 mod manifest;
 mod math;
 mod misc;
@@ -50,7 +51,6 @@
 mod sort;
 mod strings;
 mod types;
-mod keyf;
 
 #[allow(clippy::too_many_lines)]
 pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {
deletedtests/tests/as_native.rsdiffbeforeafterboth
--- a/tests/tests/as_native.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use jrsonnet_evaluator::{FileImportResolver, Result, State, trace::PathResolver};
-use jrsonnet_stdlib::ContextInitializer;
-
-mod common;
-
-#[test]
-fn as_native() -> Result<()> {
-	let mut s = State::builder();
-	s.context_initializer(ContextInitializer::new(PathResolver::new_cwd_fallback()))
-		.import_resolver(FileImportResolver::default());
-	let s = s.build();
-
-	let val = s.evaluate_snippet("snip".to_owned(), r"function(a, b) a + b")?;
-	let func = val.as_func().expect("this is function");
-
-	let native = func.into_native::<((u32, u32), u32)>();
-
-	ensure_eq!(native(1, 2)?, 3);
-	ensure_eq!(native(3, 4)?, 7);
-
-	Ok(())
-}