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

difftreelog

refactor split Typed into FromUntyped and IntoUntyped

ysonnywlYaroslav Bolyukin2026-03-22parent: #8667194.patch.diff
in: master

20 files changed

modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -6,7 +6,7 @@
 use jrsonnet_evaluator::{
 	error::{Error, ErrorKind},
 	function::builtin::{NativeCallback, NativeCallbackHandler},
-	typed::Typed,
+	typed::FromUntyped as _,
 	IStr, Val,
 };
 
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -11,10 +11,6 @@
 workspace = true
 
 [features]
-default = [
-    "exp-regex",
-]
-
 experimental = [
     "exp-preserve-order",
     "exp-destruct",
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -5,11 +5,11 @@
 	rc::Rc,
 };
 
-use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};
+use jrsonnet_gcmodule::{cc_dyn, Cc};
 use jrsonnet_interner::IBytes;
 use jrsonnet_parser::{Expr, Spanned};
 
-use crate::{function::NativeFn, typed::Typed, Context, Result, Thunk, Val};
+use crate::{function::NativeFn, Context, Result, Thunk, Val};
 
 mod spec;
 pub use spec::{ArrayLike, *};
@@ -241,4 +241,3 @@
 		self.0.is_cheap()
 	}
 }
-
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -8,8 +8,11 @@
 use super::ArrValue;
 use crate::function::NativeFn;
 use crate::{
-	error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,
-	Error, ObjValue, Result, Thunk, Val,
+	error::ErrorKind::InfiniteRecursionDetected,
+	evaluate,
+	typed::{IntoUntyped, Typed},
+	val::ThunkValue,
+	Context, Error, ObjValue, Result, Thunk, Val,
 };
 
 pub trait ArrayLike: Any + Trace + Debug {
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -20,7 +20,7 @@
 	function::{CallLocation, FuncDesc, FuncVal},
 	gc::WithCapacityExt as _,
 	in_frame,
-	typed::Typed,
+	typed::{FromUntyped, IntoUntyped as _, Typed},
 	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
 	with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
 	ResultExt, SupThis, Unbound, Val,
@@ -620,7 +620,7 @@
 			}
 		}
 		Slice(slice) => {
-			fn parse_idx<T: Typed>(
+			fn parse_idx<T: Typed + FromUntyped>(
 				loc: CallLocation<'_>,
 				ctx: Context,
 				expr: Option<&Spanned<Expr>>,
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -8,7 +8,7 @@
 	error::ErrorKind::*,
 	evaluate,
 	stdlib::std_format,
-	typed::Typed,
+	typed::IntoUntyped as _,
 	val::{equals, StrValue},
 	Context, Result, Val,
 };
modifiedcrates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -3,7 +3,11 @@
 use jrsonnet_gcmodule::Trace;
 
 use super::PreparedFuncVal;
-use crate::{bail, function::FuncVal, typed::Typed, CallLocation, Result, Val};
+use crate::{
+	function::FuncVal,
+	typed::{FromUntyped, IntoUntyped, Typed},
+	CallLocation, Result, Val,
+};
 use jrsonnet_types::{ComplexValType, ValType};
 
 #[derive(Debug, Trace, Clone)]
@@ -12,8 +16,8 @@
 	($i:expr; $($gen:ident)*) => {
 		impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
 		where
-			$($gen: Typed,)*
-			O: Typed,
+			$($gen: Typed + IntoUntyped,)*
+			O: Typed + FromUntyped,
 		{
 			#[allow(non_snake_case, clippy::too_many_arguments)]
 			pub fn call(
@@ -22,7 +26,7 @@
 			) -> Result<O> {
 				let val = self.0.call(
 					CallLocation::native(),
-					&[$(Typed::into_lazy_untyped($gen),)*],
+					&[$(IntoUntyped::into_lazy_untyped($gen),)*],
 					&[],
 				)?;
 				O::from_untyped(val)
@@ -30,11 +34,9 @@
 		}
 		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")
-			}
+		}
 
+		impl<$($gen,)* O> FromUntyped for NativeFn<($($gen,)* O,)> {
 			fn from_untyped(untyped: Val) -> Result<Self> {
 				let func = FuncVal::from_untyped(untyped)?;
 				Ok(Self(
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -9,7 +9,7 @@
 use crate::{
 	bail,
 	error::{format_found, suggest_object_fields, ErrorKind::*},
-	typed::Typed,
+	typed::FromUntyped,
 	Error, ObjValue, Result, Val,
 };
 
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,6 +1,6 @@
 use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};
 
-use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::{IBytes, IStr};
 pub use jrsonnet_macros::Typed;
 use jrsonnet_types::{ComplexValType, ValType};
@@ -8,17 +8,17 @@
 use crate::{
 	arr::{ArrValue, BytesArray},
 	bail,
-	function::{FuncDesc, FuncVal},
+	function::FuncVal,
 	typed::CheckType,
 	val::{IndexableVal, NumValue, StrValue, ThunkMapper},
 	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
 };
 
 #[derive(Trace)]
-struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);
-impl<K> ThunkMapper<Val> for FromUntyped<K>
+struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);
+impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>
 where
-	K: Typed + Trace,
+	K: Typed + FromUntyped + Trace,
 {
 	type Output = K;
 
@@ -26,12 +26,29 @@
 		K::from_untyped(from)
 	}
 }
-impl<K: Trace> Default for FromUntyped<K> {
+impl<K: Trace> Default for ThunkFromUntyped<K> {
 	fn default() -> Self {
 		Self(PhantomData)
 	}
 }
+#[derive(Trace)]
+struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);
+impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>
+where
+	K: Typed + Trace + IntoUntyped,
+{
+	type Output = Val;
 
+	fn map(self, from: K) -> Result<Self::Output> {
+		K::into_untyped(from)
+	}
+}
+impl<K: Trace> Default for ThunkIntoUntyped<K> {
+	fn default() -> Self {
+		Self(PhantomData)
+	}
+}
+
 pub trait TypedObj: Typed {
 	fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;
 	fn parse(obj: &ObjValue) -> Result<Self>;
@@ -44,31 +61,41 @@
 
 pub trait Typed: Sized {
 	const TYPE: &'static ComplexValType;
+}
+pub trait IntoUntyped: Typed {
+	// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
+	fn provides_lazy() -> bool {
+		false
+	}
 	fn into_untyped(typed: Self) -> Result<Val>;
 	fn into_lazy_untyped(typed: Self) -> Thunk<Val> {
 		Thunk::from(Self::into_untyped(typed))
 	}
+}
+pub trait IntoUntypedResult: Typed {
+	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
+	/// This method returns identity in impl Typed for Result, and should not be overriden
+	#[doc(hidden)]
+	fn into_untyped_result(typed: Self) -> Result<Val>;
+}
+impl<T> IntoUntypedResult for T
+where
+	T: IntoUntyped,
+{
+	fn into_untyped_result(typed: Self) -> Result<Val> {
+		T::into_untyped(typed)
+	}
+}
+
+pub trait FromUntyped: Typed {
 	fn from_untyped(untyped: Val) -> Result<Self>;
 	fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {
 		Self::from_untyped(lazy.evaluate()?)
 	}
 
-	// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
-	fn provides_lazy() -> bool {
-		false
-	}
-
 	// Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible
 	fn wants_lazy() -> bool {
 		false
-	}
-
-	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
-	/// This method returns identity in impl Typed for Result, and should not be overriden
-	#[doc(hidden)]
-	fn into_result(typed: Self) -> Result<Val> {
-		let value = Self::into_untyped(typed)?;
-		Ok(value)
 	}
 }
 
@@ -77,38 +104,30 @@
 	T: Typed + Trace + Clone,
 {
 	const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);
+}
 
+impl<T> IntoUntyped for Thunk<T>
+where
+	T: Typed + IntoUntyped + Trace + Clone,
+{
 	fn into_untyped(typed: Self) -> Result<Val> {
 		T::into_untyped(typed.evaluate()?)
-	}
-
-	fn from_untyped(untyped: Val) -> Result<Self> {
-		Self::from_lazy_untyped(Thunk::evaluated(untyped))
 	}
-
 	fn provides_lazy() -> bool {
 		true
 	}
 
 	fn into_lazy_untyped(inner: Self) -> Thunk<Val> {
-		#[derive(Trace)]
-		struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);
-		impl<K> ThunkMapper<K> for IntoUntyped<K>
-		where
-			K: Typed + Trace,
-		{
-			type Output = Val;
+		inner.map(<ThunkIntoUntyped<T>>::default())
+	}
+}
 
-			fn map(self, from: K) -> Result<Self::Output> {
-				K::into_untyped(from)
-			}
-		}
-		impl<K: Trace> Default for IntoUntyped<K> {
-			fn default() -> Self {
-				Self(PhantomData)
-			}
-		}
-		inner.map(<IntoUntyped<T>>::default())
+impl<T> FromUntyped for Thunk<T>
+where
+	T: Typed + FromUntyped + Trace + Clone,
+{
+	fn from_untyped(untyped: Val) -> Result<Self> {
+		Self::from_lazy_untyped(Thunk::evaluated(untyped))
 	}
 
 	fn wants_lazy() -> bool {
@@ -116,7 +135,7 @@
 	}
 
 	fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {
-		Ok(inner.map(<FromUntyped<T>>::default()))
+		Ok(inner.map(<ThunkFromUntyped<T>>::default()))
 	}
 }
 
@@ -128,6 +147,8 @@
 		impl Typed for $ty {
 			const TYPE: &'static ComplexValType =
 				&ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));
+		}
+		impl FromUntyped for $ty {
 			fn from_untyped(value: Val) -> Result<Self> {
 				<Self as Typed>::TYPE.check(&value)?;
 				match value {
@@ -145,6 +166,8 @@
 					_ => unreachable!(),
 				}
 			}
+		}
+		impl IntoUntyped for $ty {
 			fn into_untyped(value: Self) -> Result<Val> {
 				Ok(Val::Num(value.into()))
 			}
@@ -183,7 +206,9 @@
 					Some(MIN as f64),
 					Some(MAX as f64),
 				);
+		}
 
+		impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {
 			fn from_untyped(value: Val) -> Result<Self> {
 				<Self as Typed>::TYPE.check(&value)?;
 				match value {
@@ -201,7 +226,9 @@
 					_ => unreachable!(),
 				}
 			}
+		}
 
+		impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {
 			#[allow(clippy::cast_lossless)]
 			fn into_untyped(value: Self) -> Result<Val> {
 				Ok(Val::try_num(value.0)?)
@@ -220,11 +247,13 @@
 
 impl Typed for f64 {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
-
+}
+impl IntoUntyped for f64 {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::try_num(value)?)
 	}
-
+}
+impl FromUntyped for f64 {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -237,11 +266,13 @@
 pub struct PositiveF64(pub f64);
 impl Typed for PositiveF64 {
 	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
-
+}
+impl IntoUntyped for PositiveF64 {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::try_num(value.0)?)
 	}
-
+}
+impl FromUntyped for PositiveF64 {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -253,11 +284,13 @@
 impl Typed for usize {
 	const TYPE: &'static ComplexValType =
 		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));
-
+}
+impl IntoUntyped for usize {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::try_num(value)?)
 	}
-
+}
+impl FromUntyped for usize {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -276,11 +309,13 @@
 
 impl Typed for IStr {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for IStr {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::string(value))
 	}
-
+}
+impl FromUntyped for IStr {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -292,11 +327,13 @@
 
 impl Typed for String {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for String {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::string(value))
 	}
-
+}
+impl FromUntyped for String {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -308,11 +345,13 @@
 
 impl Typed for StrValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for StrValue {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Str(value))
 	}
-
+}
+impl FromUntyped for StrValue {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -324,11 +363,13 @@
 
 impl Typed for char {
 	const TYPE: &'static ComplexValType = &ComplexValType::Char;
-
+}
+impl IntoUntyped for char {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::string(value))
 	}
-
+}
+impl FromUntyped for char {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -338,12 +379,14 @@
 	}
 }
 
+// TODO: View into vec using ArrayLike?
 impl<T> Typed for Vec<T>
 where
 	T: Typed,
 {
 	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
-
+}
+impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Arr(
 			value
@@ -352,7 +395,8 @@
 				.collect::<Result<ArrValue>>()?,
 		))
 	}
-
+}
+impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {
 	fn from_untyped(value: Val) -> Result<Self> {
 		let Val::Arr(a) = value else {
 			<Self as Typed>::TYPE.check(&value)?;
@@ -369,9 +413,19 @@
 	}
 }
 
-impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {
+// TODO: View into BTreeMap using ObjectCore?
+impl<K, V> Typed for BTreeMap<K, V>
+where
+	K: Typed + Ord,
+	V: Typed,
+{
 	const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);
-
+}
+impl<K, V> IntoUntyped for BTreeMap<K, V>
+where
+	K: Typed + Ord + IntoUntyped,
+	V: Typed + IntoUntyped,
+{
 	fn into_untyped(typed: Self) -> Result<Val> {
 		let mut out = ObjValueBuilder::with_capacity(typed.len());
 		for (k, v) in typed {
@@ -383,7 +437,12 @@
 		}
 		Ok(Val::Obj(out.build()))
 	}
-
+}
+impl<K, V> FromUntyped for BTreeMap<K, V>
+where
+	K: FromUntyped + Ord,
+	V: FromUntyped,
+{
 	fn from_untyped(value: Val) -> Result<Self> {
 		Self::TYPE.check(&value)?;
 		let obj = value.as_obj().expect("typecheck should fail");
@@ -416,32 +475,27 @@
 
 impl Typed for Val {
 	const TYPE: &'static ComplexValType = &ComplexValType::Any;
-
+}
+impl IntoUntyped for Val {
 	fn into_untyped(typed: Self) -> Result<Val> {
 		Ok(typed)
 	}
+}
+impl FromUntyped for Val {
 	fn from_untyped(untyped: Val) -> Result<Self> {
 		Ok(untyped)
 	}
 }
 
-// Hack
 #[doc(hidden)]
 impl<T> Typed for Result<T>
 where
 	T: Typed,
 {
 	const TYPE: &'static ComplexValType = &ComplexValType::Any;
-
-	fn into_untyped(_typed: Self) -> Result<Val> {
-		panic!("do not use this conversion")
-	}
-
-	fn from_untyped(_untyped: Val) -> Result<Self> {
-		panic!("do not use this conversion")
-	}
-
-	fn into_result(typed: Self) -> Result<Val> {
+}
+impl<T: IntoUntyped> IntoUntypedResult for Result<T> {
+	fn into_untyped_result(typed: Self) -> Result<Val> {
 		typed.map(T::into_untyped)?
 	}
 }
@@ -450,11 +504,13 @@
 impl Typed for IBytes {
 	const TYPE: &'static ComplexValType =
 		&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
-
+}
+impl IntoUntyped for IBytes {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Arr(ArrValue::bytes(value)))
 	}
-
+}
+impl FromUntyped for IBytes {
 	fn from_untyped(value: Val) -> Result<Self> {
 		let Val::Arr(a) = &value else {
 			<Self as Typed>::TYPE.check(&value)?;
@@ -477,11 +533,13 @@
 pub struct M1;
 impl Typed for M1 {
 	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
-
+}
+impl IntoUntyped for M1 {
 	fn into_untyped(_: Self) -> Result<Val> {
 		Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
 	}
-
+}
+impl FromUntyped for M1 {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		Ok(Self)
@@ -499,13 +557,22 @@
 			$($id: Typed,)*
 		{
 			const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);
-
+		}
+		impl<$($id),*> IntoUntyped for $name<$($id),*>
+		where
+			$($id: Typed + IntoUntyped,)*
+		{
 			fn into_untyped(value: Self) -> Result<Val> {
 				match value {$(
 					$name::$id(v) => $id::into_untyped(v)
 				),*}
 			}
+		}
 
+		impl<$($id),*> FromUntyped for $name<$($id),*>
+		where
+			$($id: Typed + FromUntyped,)*
+		{
 			fn from_untyped(value: Val) -> Result<Self> {
 				$(
 					if $id::TYPE.check(&value).is_ok() {
@@ -544,11 +611,13 @@
 
 impl Typed for ArrValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
-
+}
+impl IntoUntyped for ArrValue {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Arr(value))
 	}
-
+}
+impl FromUntyped for ArrValue {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -560,32 +629,17 @@
 
 impl Typed for FuncVal {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
+}
+impl IntoUntyped for FuncVal {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Func(value))
 	}
-
-	fn from_untyped(value: Val) -> Result<Self> {
-		<Self as Typed>::TYPE.check(&value)?;
-		match value {
-			Val::Func(a) => Ok(a),
-			_ => unreachable!(),
-		}
-	}
 }
-
-impl Typed for Cc<FuncDesc> {
-	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
-	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Func(FuncVal::Normal(value)))
-	}
-
+impl FromUntyped for FuncVal {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Func(FuncVal::Normal(desc)) => Ok(desc),
-			Val::Func(_) => bail!("expected normal function, not builtin"),
+			Val::Func(a) => Ok(a),
 			_ => unreachable!(),
 		}
 	}
@@ -593,11 +647,13 @@
 
 impl Typed for ObjValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
-
+}
+impl IntoUntyped for ObjValue {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Obj(value))
 	}
-
+}
+impl FromUntyped for ObjValue {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -609,11 +665,13 @@
 
 impl Typed for bool {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
-
+}
+impl IntoUntyped for bool {
 	fn into_untyped(value: Self) -> Result<Val> {
 		Ok(Val::Bool(value))
 	}
-
+}
+impl FromUntyped for bool {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
@@ -622,19 +680,22 @@
 		}
 	}
 }
+
 impl Typed for IndexableVal {
 	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[
 		&ComplexValType::Simple(ValType::Arr),
 		&ComplexValType::Simple(ValType::Str),
 	]);
-
+}
+impl IntoUntyped for IndexableVal {
 	fn into_untyped(value: Self) -> Result<Val> {
 		match value {
 			Self::Str(s) => Ok(Val::string(s)),
 			Self::Arr(a) => Ok(Val::Arr(a)),
 		}
 	}
-
+}
+impl FromUntyped for IndexableVal {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		value.into_indexable()
@@ -644,11 +705,13 @@
 pub struct Null;
 impl Typed for Null {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
-
+}
+impl IntoUntyped for Null {
 	fn into_untyped(_: Self) -> Result<Val> {
 		Ok(Val::Null)
 	}
-
+}
+impl FromUntyped for Null {
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		Ok(Self)
@@ -661,11 +724,19 @@
 {
 	const TYPE: &'static ComplexValType =
 		&ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);
-
+}
+impl<T> IntoUntyped for Option<T>
+where
+	T: Typed + IntoUntyped,
+{
 	fn into_untyped(typed: Self) -> Result<Val> {
 		typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))
 	}
-
+}
+impl<T> FromUntyped for Option<T>
+where
+	T: Typed + FromUntyped,
+{
 	fn from_untyped(untyped: Val) -> Result<Self> {
 		if matches!(untyped, Val::Null) {
 			Ok(None)
@@ -677,11 +748,13 @@
 
 impl Typed for NumValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
-
+}
+impl IntoUntyped for NumValue {
 	fn into_untyped(typed: Self) -> Result<Val> {
 		Ok(Val::Num(typed))
 	}
-
+}
+impl FromUntyped for NumValue {
 	fn from_untyped(untyped: Val) -> Result<Self> {
 		Self::TYPE.check(&untyped)?;
 		match untyped {
modifiedcrates/jrsonnet-interner/src/names.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/names.rs
+++ b/crates/jrsonnet-interner/src/names.rs
@@ -0,0 +1 @@
+
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-macros/src/lib.rs
1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6	parenthesized,7	parse::{Parse, ParseStream},8	parse_macro_input,9	punctuated::Punctuated,10	spanned::Spanned,11	token::{self, Comma},12	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516use self::typed::derive_typed_inner;1718mod typed;19mod names;2021fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>22where23	Ident: PartialEq<I>,24{25	let attrs = attrs26		.iter()27		.filter(|a| a.path().is_ident(&ident))28		.collect::<Vec<_>>();29	if attrs.len() > 1 {30		return Err(Error::new(31			attrs[1].span(),32			"this attribute may be specified only once",33		));34	} else if attrs.is_empty() {35		return Ok(false);36	}37	let attr = attrs[0];3839	match attr.meta {40		Meta::Path(_) => Ok(true),41		_ => Ok(false),42	}43}44fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>45where46	Ident: PartialEq<I>,47{48	let attrs = attrs49		.iter()50		.filter(|a| a.path().is_ident(&ident))51		.collect::<Vec<_>>();52	if attrs.len() > 1 {53		return Err(Error::new(54			attrs[1].span(),55			"this attribute may be specified only once",56		));57	} else if attrs.is_empty() {58		return Ok(None);59	}60	let attr = attrs[0];61	let attr = attr.parse_args::<A>()?;6263	Ok(Some(attr))64}65fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)66where67	Ident: PartialEq<I>,68{69	attrs.retain(|a| !a.path().is_ident(&ident));70}7172fn path_is(path: &Path, needed: &str) -> bool {73	path.leading_colon.is_none()74		&& !path.segments.is_empty()75		&& path.segments.iter().last().unwrap().ident == needed76}7778fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {79	match ty {80		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {81			let args = &path.path.segments.iter().last().unwrap().arguments;82			Some(args)83		}84		_ => None,85	}86}8788fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {89	let Some(args) = type_is_path(ty, "Option") else {90		return Ok(None);91	};92	// It should have only on angle-bracketed param ("<String>"):93	let PathArguments::AngleBracketed(params) = args else {94		return Err(Error::new(args.span(), "missing option generic"));95	};96	let generic_arg = params.args.iter().next().unwrap();97	// This argument must be a type:98	let GenericArgument::Type(ty) = generic_arg else {99		return Err(Error::new(100			generic_arg.span(),101			"option generic should be a type",102		));103	};104	Ok(Some(ty))105}106107struct Field {108	attrs: Vec<Attribute>,109	name: Ident,110	_colon: Token![:],111	ty: Type,112}113impl Parse for Field {114	fn parse(input: ParseStream) -> syn::Result<Self> {115		Ok(Self {116			attrs: input.call(Attribute::parse_outer)?,117			name: input.parse()?,118			_colon: input.parse()?,119			ty: input.parse()?,120		})121	}122}123124mod kw {125	syn::custom_keyword!(fields);126	syn::custom_keyword!(rename);127	syn::custom_keyword!(alias);128	syn::custom_keyword!(flatten);129	syn::custom_keyword!(add);130	syn::custom_keyword!(hide);131	syn::custom_keyword!(ok);132}133134struct BuiltinAttrs {135	fields: Vec<Field>,136}137impl Parse for BuiltinAttrs {138	fn parse(input: ParseStream) -> syn::Result<Self> {139		if input.is_empty() {140			return Ok(Self { fields: Vec::new() });141		}142		input.parse::<kw::fields>()?;143		let fields;144		parenthesized!(fields in input);145		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;146		Ok(Self {147			fields: p.into_iter().collect(),148		})149	}150}151152enum Optionality {153	Required,154	Optional,155	Default(Expr),156	TypeDefault,157}158159#[allow(160	clippy::large_enum_variant,161	reason = "this macro is not that hot for it to matter"162)]163enum ArgInfo {164	Normal {165		ty: Box<Type>,166		optionality: Optionality,167		name: Option<String>,168		cfg_attrs: Vec<Attribute>,169	},170	Lazy {171		is_option: bool,172		name: Option<String>,173	},174	Context,175	Location,176	This,177}178179impl ArgInfo {180	fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {181		let FnArg::Typed(arg) = arg else {182			unreachable!()183		};184		let ident = match &arg.pat as &Pat {185			Pat::Ident(i) => Some(i.ident.clone()),186			_ => None,187		};188		let ty = &arg.ty;189		if type_is_path(ty, "Context").is_some() {190			return Ok(Self::Context);191		} else if type_is_path(ty, "CallLocation").is_some() {192			return Ok(Self::Location);193		} else if type_is_path(ty, "Thunk").is_some() {194			return Ok(Self::Lazy {195				is_option: false,196				name: ident.map(|v| v.to_string()),197			});198		}199200		match ty as &Type {201			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),202			_ => {}203		}204205		let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {206			remove_attr(&mut arg.attrs, "default");207			(Optionality::TypeDefault, ty.clone())208		} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {209			remove_attr(&mut arg.attrs, "default");210			(Optionality::Default(default), ty.clone())211		} else if let Some(ty) = extract_type_from_option(ty)? {212			if type_is_path(ty, "Thunk").is_some() {213				return Ok(Self::Lazy {214					is_option: true,215					name: ident.map(|v| v.to_string()),216				});217			}218219			(Optionality::Optional, Box::new(ty.clone()))220		} else {221			(Optionality::Required, ty.clone())222		};223224		let cfg_attrs = arg225			.attrs226			.iter()227			.filter(|a| a.path().is_ident("cfg"))228			.cloned()229			.collect();230231		Ok(Self::Normal {232			ty,233			optionality,234			name: ident.map(|v| v.to_string()),235			cfg_attrs,236		})237	}238}239240#[proc_macro_attribute]241pub fn builtin(242	attr: proc_macro::TokenStream,243	item: proc_macro::TokenStream,244) -> proc_macro::TokenStream {245	let attr = parse_macro_input!(attr as BuiltinAttrs);246	let item_fn = parse_macro_input!(item as ItemFn);247248	match builtin_inner(attr, item_fn) {249		Ok(v) => v.into(),250		Err(e) => e.into_compile_error().into(),251	}252}253254#[allow(clippy::too_many_lines)]255fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {256	let ReturnType::Type(_, result) = &fun.sig.output else {257		return Err(Error::new(258			fun.sig.span(),259			"builtin should return something",260		));261	};262263	let name = fun.sig.ident.to_string();264	let args = fun265		.sig266		.inputs267		.iter_mut()268		.map(|arg| ArgInfo::parse(&name, arg))269		.collect::<Result<Vec<_>>>()?;270271	let params_desc = args.iter().filter_map(|a| match a {272		ArgInfo::Normal {273			optionality,274			name,275			cfg_attrs,276			..277		} => {278			let name = name279				.as_ref()280				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});281			let default = match optionality {282				Optionality::Required => quote!(ParamDefault::None),283				Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),284				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),285			};286			Some(quote! {287				#(#cfg_attrs)*288				[#name => #default],289			})290		}291		ArgInfo::Lazy { is_option, name } => {292			let name = name293				.as_ref()294				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});295			Some(quote! {296				[#name => ParamDefault::exists(#is_option)],297			})298		}299		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,300	});301302	let mut id = 0usize;303	let pass = args304		.iter()305		.map(|a| match a {306			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {307				let cid = id;308				id += 1;309				(quote! {#cid}, a)310			}311			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {312				(quote! {compile_error!("should not use id")}, a)313			}314		})315		.map(|(id, a)| match a {316			ArgInfo::Normal {317				ty,318				optionality,319				name,320				cfg_attrs,321			} => {322				let name = name.as_ref().map_or("<unnamed>", String::as_str);323				let eval = quote! {jrsonnet_evaluator::in_description_frame(324					|| format!("argument <{}> evaluation", #name),325					|| <#ty>::from_untyped(value.evaluate()?),326				)?};327				let value = match optionality {328					Optionality::Required => quote! {{329						let value = parsed[#id].as_ref().expect("args shape is checked");330						#eval331					},},332					Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {333						Some(#eval)334					} else {335						None336					},},337					Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {338						#eval339					} else {340						let v: #ty = #expr;341						v342					},},343					Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {344						#eval345					} else {346						let v: #ty = Default::default();347						v348					},},349				};350				quote! {351					#(#cfg_attrs)*352					#value353				}354			}355			ArgInfo::Lazy { is_option, .. } => {356				if *is_option {357					quote! {if let Some(value) = &parsed[#id] {358						Some(value.clone())359					} else {360						None361					},}362				} else {363					quote! {364						parsed[#id].as_ref().expect("args shape is correct").clone(),365					}366				}367			}368			ArgInfo::Context => quote! {ctx.clone(),},369			ArgInfo::Location => quote! {location,},370			ArgInfo::This => quote! {self,},371		});372373	let fields = attr.fields.iter().map(|field| {374		let attrs = &field.attrs;375		let name = &field.name;376		let ty = &field.ty;377		quote! {378			#(#attrs)*379			pub #name: #ty,380		}381	});382383	let name = &fun.sig.ident;384	let vis = &fun.vis;385	let static_ext = if attr.fields.is_empty() {386		quote! {387			impl #name {388				pub const INST: &'static dyn StaticBuiltin = &#name {};389			}390			impl StaticBuiltin for #name {}391		}392	} else {393		quote! {}394	};395	let static_derive_copy = if attr.fields.is_empty() {396		quote! {, Copy}397	} else {398		quote! {}399	};400401	Ok(quote! {402		#fun403404		#[doc(hidden)]405		#[allow(non_camel_case_types)]406		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]407		#vis struct #name {408			#(#fields)*409		}410		const _: () = {411			use ::jrsonnet_evaluator::{412				State, Val,413				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},414				Result, Context, typed::Typed,415				parser::Span, params, Thunk,416			};417			params!(418				#(#params_desc)*419			);420421			#static_ext422			impl Builtin for #name423			where424				Self: 'static425			{426				fn name(&self) -> &str {427					stringify!(#name)428				}429				fn params(&self) -> FunctionSignature {430					PARAMS.with(|p| p.clone())431				}432				#[allow(unused_variables)]433				fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {434					let result: #result = #name(#(#pass)*);435					<_ as Typed>::into_result(result)436				}437				fn as_any(&self) -> &dyn ::std::any::Any {438					self439				}440			}441		};442	})443}444445#[proc_macro_derive(Typed, attributes(typed))]446pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {447	let input = parse_macro_input!(item as DeriveInput);448449	match derive_typed_inner(input) {450		Ok(v) => v.into(),451		Err(e) => e.to_compile_error().into(),452	}453}454455struct FormatInput {456	formatting: LitStr,457	arguments: Vec<Expr>,458}459impl Parse for FormatInput {460	fn parse(input: ParseStream) -> Result<Self> {461		let formatting = input.parse()?;462		let mut arguments = Vec::new();463464		while input.peek(Token![,]) {465			input.parse::<Token![,]>()?;466			if input.is_empty() {467				// Trailing comma468				break;469			}470			let expr = input.parse()?;471			arguments.push(expr);472		}473474		if !input.is_empty() {475			return Err(syn::Error::new(input.span(), "unexpected trailing input"));476		}477478		Ok(Self {479			formatting,480			arguments,481		})482	}483}484fn is_format_str(i: &str) -> bool {485	let mut is_plain = true;486	// -1 = {487	// +1 = }488	let mut is_bracket = 0i8;489	for ele in i.chars() {490		match ele {491			'{' if is_bracket == -1 => {492				is_bracket = 0;493			}494			'}' if is_bracket == -1 => {495				is_plain = false;496				break;497			}498			'}' if is_bracket == 1 => {499				is_bracket = 0;500			}501			'{' if is_bracket == 1 => {502				is_plain = false;503				break;504			}505			'{' => {506				is_bracket = -1;507			}508			'}' => {509				is_bracket = 1;510			}511			_ if is_bracket != 0 => {512				is_plain = false;513				break;514			}515			_ => {}516		}517	}518	!is_plain || is_bracket != 0519}520impl FormatInput {521	fn expand(self) -> TokenStream {522		let format = self.formatting;523		if is_format_str(&format.value()) {524			let args = self.arguments;525			quote! {526				::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))527			}528		} else {529			if let Some(first) = self.arguments.first() {530				return syn::Error::new(531					first.span(),532					"string has no formatting codes, it should not have the arguments",533				)534				.into_compile_error();535			}536			quote! {537				::jrsonnet_evaluator::IStr::from(#format)538			}539		}540	}541}542543/// `IStr` formatting helper544///545/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`546/// This macro looks for formatting codes in the input string, and uses547/// `format!()` only when necessary548#[proc_macro]549pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {550	let input = parse_macro_input!(input as FormatInput);551	input.expand().into()552}553554/// Create Thunk using closure syntax555#[proc_macro]556#[allow(non_snake_case)]557pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {558	let input = parse_macro_input!(input as ExprClosure);559560	let span = input.inputs.span();561	let move_check = input.capture.is_none().then(|| {562		quote_spanned! {span => {563			compile_error!("Thunk! needs to be called with move closure");564		}}565	});566567	let (env, closure, args) = syn_dissect_closure::split_env(input);568569	let trace_check = args.iter().map(|el| {570		let span = el.span();571		quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}572	});573574	quote! {{575		#move_check576		#(#trace_check)*577		::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))578	}}.into()579}
after · crates/jrsonnet-macros/src/lib.rs
1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6	parenthesized,7	parse::{Parse, ParseStream},8	parse_macro_input,9	punctuated::Punctuated,10	spanned::Spanned,11	token::Comma,12	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516use self::typed::derive_typed_inner;1718mod names;19mod typed;2021fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>22where23	Ident: PartialEq<I>,24{25	let attrs = attrs26		.iter()27		.filter(|a| a.path().is_ident(&ident))28		.collect::<Vec<_>>();29	if attrs.len() > 1 {30		return Err(Error::new(31			attrs[1].span(),32			"this attribute may be specified only once",33		));34	} else if attrs.is_empty() {35		return Ok(false);36	}37	let attr = attrs[0];3839	match attr.meta {40		Meta::Path(_) => Ok(true),41		_ => Ok(false),42	}43}44fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>45where46	Ident: PartialEq<I>,47{48	let attrs = attrs49		.iter()50		.filter(|a| a.path().is_ident(&ident))51		.collect::<Vec<_>>();52	if attrs.len() > 1 {53		return Err(Error::new(54			attrs[1].span(),55			"this attribute may be specified only once",56		));57	} else if attrs.is_empty() {58		return Ok(None);59	}60	let attr = attrs[0];61	let attr = attr.parse_args::<A>()?;6263	Ok(Some(attr))64}65fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)66where67	Ident: PartialEq<I>,68{69	attrs.retain(|a| !a.path().is_ident(&ident));70}7172fn path_is(path: &Path, needed: &str) -> bool {73	path.leading_colon.is_none()74		&& !path.segments.is_empty()75		&& path.segments.iter().last().unwrap().ident == needed76}7778fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {79	match ty {80		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {81			let args = &path.path.segments.iter().last().unwrap().arguments;82			Some(args)83		}84		_ => None,85	}86}8788fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {89	let Some(args) = type_is_path(ty, "Option") else {90		return Ok(None);91	};92	// It should have only on angle-bracketed param ("<String>"):93	let PathArguments::AngleBracketed(params) = args else {94		return Err(Error::new(args.span(), "missing option generic"));95	};96	let generic_arg = params.args.iter().next().unwrap();97	// This argument must be a type:98	let GenericArgument::Type(ty) = generic_arg else {99		return Err(Error::new(100			generic_arg.span(),101			"option generic should be a type",102		));103	};104	Ok(Some(ty))105}106107struct Field {108	attrs: Vec<Attribute>,109	name: Ident,110	_colon: Token![:],111	ty: Type,112}113impl Parse for Field {114	fn parse(input: ParseStream) -> syn::Result<Self> {115		Ok(Self {116			attrs: input.call(Attribute::parse_outer)?,117			name: input.parse()?,118			_colon: input.parse()?,119			ty: input.parse()?,120		})121	}122}123124mod kw {125	syn::custom_keyword!(fields);126	syn::custom_keyword!(rename);127	syn::custom_keyword!(alias);128	syn::custom_keyword!(flatten);129	syn::custom_keyword!(add);130	syn::custom_keyword!(hide);131	syn::custom_keyword!(ok);132}133134struct BuiltinAttrs {135	fields: Vec<Field>,136}137impl Parse for BuiltinAttrs {138	fn parse(input: ParseStream) -> syn::Result<Self> {139		if input.is_empty() {140			return Ok(Self { fields: Vec::new() });141		}142		input.parse::<kw::fields>()?;143		let fields;144		parenthesized!(fields in input);145		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;146		Ok(Self {147			fields: p.into_iter().collect(),148		})149	}150}151152enum Optionality {153	Required,154	Optional,155	Default(Expr),156	TypeDefault,157}158159#[allow(160	clippy::large_enum_variant,161	reason = "this macro is not that hot for it to matter"162)]163enum ArgInfo {164	Normal {165		ty: Box<Type>,166		optionality: Optionality,167		name: Option<String>,168		cfg_attrs: Vec<Attribute>,169	},170	Lazy {171		is_option: bool,172		name: Option<String>,173	},174	Context,175	Location,176	This,177}178179impl ArgInfo {180	fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {181		let FnArg::Typed(arg) = arg else {182			unreachable!()183		};184		let ident = match &arg.pat as &Pat {185			Pat::Ident(i) => Some(i.ident.clone()),186			_ => None,187		};188		let ty = &arg.ty;189		if type_is_path(ty, "Context").is_some() {190			return Ok(Self::Context);191		} else if type_is_path(ty, "CallLocation").is_some() {192			return Ok(Self::Location);193		} else if type_is_path(ty, "Thunk").is_some() {194			return Ok(Self::Lazy {195				is_option: false,196				name: ident.map(|v| v.to_string()),197			});198		}199200		match ty as &Type {201			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),202			_ => {}203		}204205		let (optionality, ty) = if try_parse_attr_noargs(&arg.attrs, "default")? {206			remove_attr(&mut arg.attrs, "default");207			(Optionality::TypeDefault, ty.clone())208		} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {209			remove_attr(&mut arg.attrs, "default");210			(Optionality::Default(default), ty.clone())211		} else if let Some(ty) = extract_type_from_option(ty)? {212			if type_is_path(ty, "Thunk").is_some() {213				return Ok(Self::Lazy {214					is_option: true,215					name: ident.map(|v| v.to_string()),216				});217			}218219			(Optionality::Optional, Box::new(ty.clone()))220		} else {221			(Optionality::Required, ty.clone())222		};223224		let cfg_attrs = arg225			.attrs226			.iter()227			.filter(|a| a.path().is_ident("cfg"))228			.cloned()229			.collect();230231		Ok(Self::Normal {232			ty,233			optionality,234			name: ident.map(|v| v.to_string()),235			cfg_attrs,236		})237	}238}239240#[proc_macro_attribute]241pub fn builtin(242	attr: proc_macro::TokenStream,243	item: proc_macro::TokenStream,244) -> proc_macro::TokenStream {245	let attr = parse_macro_input!(attr as BuiltinAttrs);246	let item_fn = parse_macro_input!(item as ItemFn);247248	match builtin_inner(attr, item_fn) {249		Ok(v) => v.into(),250		Err(e) => e.into_compile_error().into(),251	}252}253254#[allow(clippy::too_many_lines)]255fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {256	let ReturnType::Type(_, result) = &fun.sig.output else {257		return Err(Error::new(258			fun.sig.span(),259			"builtin should return something",260		));261	};262263	let name = fun.sig.ident.to_string();264	let args = fun265		.sig266		.inputs267		.iter_mut()268		.map(|arg| ArgInfo::parse(&name, arg))269		.collect::<Result<Vec<_>>>()?;270271	let params_desc = args.iter().filter_map(|a| match a {272		ArgInfo::Normal {273			optionality,274			name,275			cfg_attrs,276			..277		} => {278			let name = name279				.as_ref()280				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});281			let default = match optionality {282				Optionality::Required => quote!(ParamDefault::None),283				Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),284				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),285			};286			Some(quote! {287				#(#cfg_attrs)*288				[#name => #default],289			})290		}291		ArgInfo::Lazy { is_option, name } => {292			let name = name293				.as_ref()294				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});295			Some(quote! {296				[#name => ParamDefault::exists(#is_option)],297			})298		}299		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,300	});301302	let mut id = 0usize;303	let pass = args304		.iter()305		.map(|a| match a {306			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {307				let cid = id;308				id += 1;309				(quote! {#cid}, a)310			}311			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {312				(quote! {compile_error!("should not use id")}, a)313			}314		})315		.map(|(id, a)| match a {316			ArgInfo::Normal {317				ty,318				optionality,319				name,320				cfg_attrs,321			} => {322				let name = name.as_ref().map_or("<unnamed>", String::as_str);323				let eval = quote! {jrsonnet_evaluator::in_description_frame(324					|| format!("argument <{}> evaluation", #name),325					|| <#ty as FromUntyped>::from_untyped(value.evaluate()?),326				)?};327				let value = match optionality {328					Optionality::Required => quote! {{329						let value = parsed[#id].as_ref().expect("args shape is checked");330						#eval331					},},332					Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {333						Some(#eval)334					} else {335						None336					},},337					Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {338						#eval339					} else {340						let v: #ty = #expr;341						v342					},},343					Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {344						#eval345					} else {346						let v: #ty = Default::default();347						v348					},},349				};350				quote! {351					#(#cfg_attrs)*352					#value353				}354			}355			ArgInfo::Lazy { is_option, .. } => {356				if *is_option {357					quote! {if let Some(value) = &parsed[#id] {358						Some(value.clone())359					} else {360						None361					},}362				} else {363					quote! {364						parsed[#id].as_ref().expect("args shape is correct").clone(),365					}366				}367			}368			ArgInfo::Context => quote! {ctx.clone(),},369			ArgInfo::Location => quote! {location,},370			ArgInfo::This => quote! {self,},371		});372373	let fields = attr.fields.iter().map(|field| {374		let attrs = &field.attrs;375		let name = &field.name;376		let ty = &field.ty;377		quote! {378			#(#attrs)*379			pub #name: #ty,380		}381	});382383	let name = &fun.sig.ident;384	let vis = &fun.vis;385	let static_ext = if attr.fields.is_empty() {386		quote! {387			impl #name {388				pub const INST: &'static dyn StaticBuiltin = &#name {};389			}390			impl StaticBuiltin for #name {}391		}392	} else {393		quote! {}394	};395	let static_derive_copy = if attr.fields.is_empty() {396		quote! {, Copy}397	} else {398		quote! {}399	};400401	Ok(quote! {402		#fun403404		#[doc(hidden)]405		#[allow(non_camel_case_types)]406		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]407		#vis struct #name {408			#(#fields)*409		}410		const _: () = {411			use ::jrsonnet_evaluator::{412				State, Val,413				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},414				Result, Context, typed::{Typed, FromUntyped, IntoUntypedResult},415				parser::Span, params, Thunk,416			};417			params!(418				#(#params_desc)*419			);420421			#static_ext422			impl Builtin for #name423			where424				Self: 'static425			{426				fn name(&self) -> &str {427					stringify!(#name)428				}429				fn params(&self) -> FunctionSignature {430					PARAMS.with(|p| p.clone())431				}432				#[allow(unused_variables)]433				fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {434					let result: #result = #name(#(#pass)*);435					<_ as IntoUntypedResult>::into_untyped_result(result)436				}437				fn as_any(&self) -> &dyn ::std::any::Any {438					self439				}440			}441		};442	})443}444445#[proc_macro_derive(Typed, attributes(typed))]446pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {447	let input = parse_macro_input!(item as DeriveInput);448449	match derive_typed_inner(input) {450		Ok(v) => v.into(),451		Err(e) => e.to_compile_error().into(),452	}453}454455struct FormatInput {456	formatting: LitStr,457	arguments: Vec<Expr>,458}459impl Parse for FormatInput {460	fn parse(input: ParseStream) -> Result<Self> {461		let formatting = input.parse()?;462		let mut arguments = Vec::new();463464		while input.peek(Token![,]) {465			input.parse::<Token![,]>()?;466			if input.is_empty() {467				// Trailing comma468				break;469			}470			let expr = input.parse()?;471			arguments.push(expr);472		}473474		if !input.is_empty() {475			return Err(syn::Error::new(input.span(), "unexpected trailing input"));476		}477478		Ok(Self {479			formatting,480			arguments,481		})482	}483}484fn is_format_str(i: &str) -> bool {485	let mut is_plain = true;486	// -1 = {487	// +1 = }488	let mut is_bracket = 0i8;489	for ele in i.chars() {490		match ele {491			'{' if is_bracket == -1 => {492				is_bracket = 0;493			}494			'}' if is_bracket == -1 => {495				is_plain = false;496				break;497			}498			'}' if is_bracket == 1 => {499				is_bracket = 0;500			}501			'{' if is_bracket == 1 => {502				is_plain = false;503				break;504			}505			'{' => {506				is_bracket = -1;507			}508			'}' => {509				is_bracket = 1;510			}511			_ if is_bracket != 0 => {512				is_plain = false;513				break;514			}515			_ => {}516		}517	}518	!is_plain || is_bracket != 0519}520impl FormatInput {521	fn expand(self) -> TokenStream {522		let format = self.formatting;523		if is_format_str(&format.value()) {524			let args = self.arguments;525			quote! {526				::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))527			}528		} else {529			if let Some(first) = self.arguments.first() {530				return syn::Error::new(531					first.span(),532					"string has no formatting codes, it should not have the arguments",533				)534				.into_compile_error();535			}536			quote! {537				::jrsonnet_evaluator::IStr::from(#format)538			}539		}540	}541}542543/// `IStr` formatting helper544///545/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`546/// This macro looks for formatting codes in the input string, and uses547/// `format!()` only when necessary548#[proc_macro]549pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {550	let input = parse_macro_input!(input as FormatInput);551	input.expand().into()552}553554/// Create Thunk using closure syntax555#[proc_macro]556#[allow(non_snake_case)]557pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {558	let input = parse_macro_input!(input as ExprClosure);559560	let span = input.inputs.span();561	let move_check = input.capture.is_none().then(|| {562		quote_spanned! {span => {563			compile_error!("Thunk! needs to be called with move closure");564		}}565	});566567	let (env, closure, args) = syn_dissect_closure::split_env(input);568569	let trace_check = args.iter().map(|el| {570		let span = el.span();571		quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}572	});573574	quote! {{575		#move_check576		#(#trace_check)*577		::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))578	}}.into()579}
modifiedcrates/jrsonnet-macros/src/names.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/names.rs
+++ b/crates/jrsonnet-macros/src/names.rs
@@ -1,6 +1,5 @@
 use proc_macro2::TokenStream;
 use quote::quote;
-use std::cell::RefCell;
 
 #[derive(Default)]
 pub struct Names {
modifiedcrates/jrsonnet-macros/src/typed.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/typed.rs
+++ b/crates/jrsonnet-macros/src/typed.rs
@@ -178,7 +178,7 @@
 					None
 				};
 
-				__value.map(<#ty as Typed>::from_untyped).transpose()?
+				__value.map(<#ty as FromUntyped>::from_untyped).transpose()?
 			},
 		}
 	}
@@ -219,7 +219,7 @@
 					return Err(ErrorKind::NoSuchField(__names[#error_text].clone(), vec![]).into());
 				};
 
-				<#ty as Typed>::from_untyped(__value)?
+				<#ty as FromUntyped>::from_untyped(__value)?
 			},
 		}
 	}
@@ -258,14 +258,14 @@
 						out.field(__names[#name].clone())
 							#hide
 							#add
-							.try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;
+							.try_thunk(<#ty as IntoUntyped>::into_lazy_untyped(value))?;
 					}
 				} else {
 					quote! {
 						out.field(__names[#name].clone())
 							#hide
 							#add
-							.try_value(<#ty as Typed>::into_untyped(value)?)?;
+							.try_value(<#ty as IntoUntyped>::into_untyped(value)?)?;
 					}
 				};
 				if self.is_option {
@@ -313,18 +313,21 @@
 				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[
 					#(#fields,)*
 				]);
+			}
 
+			impl #impl_generics FromUntyped for #ident #ty_generics #where_clause {
 				fn from_untyped(value: Val) -> JrResult<Self> {
 					let obj = value.as_obj().expect("shape is correct");
 					Self::parse(&obj)
 				}
+			}
 
+			impl #impl_generics IntoUntyped for #ident #ty_generics #where_clause {
 				fn into_untyped(value: Self) -> JrResult<Val> {
 					let mut out = ObjValueBuilder::with_capacity(#capacity);
 					value.serialize(&mut out)?;
 					Ok(Val::Obj(out.build()))
 				}
-
 			}
 		}
 	};
@@ -344,7 +347,7 @@
 	Ok(quote! {
 		const _: () = {
 			use ::jrsonnet_evaluator::{
-				typed::{ComplexValType, Typed, TypedObj, CheckType},
+				typed::{ComplexValType, Typed, IntoUntyped, FromUntyped, TypedObj, CheckType},
 				Val, State,
 				error::{ErrorKind, Result as JrResult},
 				ObjValueBuilder, ObjValue, IStr,
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -4,7 +4,7 @@
 	bail,
 	function::{builtin, FuncVal, NativeFn},
 	runtime_error,
-	typed::{BoundedI32, BoundedUsize, Either2, Typed},
+	typed::{BoundedI32, BoundedUsize, Either2, FromUntyped},
 	val::{equals, ArrValue, IndexableVal},
 	Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
 };
@@ -24,7 +24,7 @@
 	}
 	func.evaluate_trivial().map_or_else(
 		// TODO: Different mapped array impl avoiding allocating unnecessary vals
-		|| Ok(ArrValue::range_exclusive(0, *sz).map(Typed::from_untyped(Val::Func(func))?)),
+		|| Ok(ArrValue::range_exclusive(0, *sz).map(FromUntyped::from_untyped(Val::Func(func))?)),
 		|trivial| {
 			let mut out = Vec::with_capacity(*sz as usize);
 			for _ in 0..*sz {
modifiedcrates/jrsonnet-stdlib/src/keyf.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/keyf.rs
+++ b/crates/jrsonnet-stdlib/src/keyf.rs
@@ -1,5 +1,5 @@
 use jrsonnet_evaluator::function::{CallLocation, FuncVal, PreparedFuncVal};
-use jrsonnet_evaluator::typed::{ComplexValType, Typed, ValType};
+use jrsonnet_evaluator::typed::{ComplexValType, FromUntyped, Typed, ValType};
 use jrsonnet_evaluator::{Error, Result, Thunk, Val};
 
 #[derive(Default, Clone)]
@@ -31,11 +31,9 @@
 
 impl Typed for KeyF {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl FromUntyped for KeyF {
 	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/manifest/ini.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/ini.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/ini.rs
@@ -2,7 +2,7 @@
 
 use jrsonnet_evaluator::{
 	manifest::{ManifestFormat, ToStringFormat},
-	typed::Typed,
+	typed::{FromUntyped, Typed},
 	ObjValue, Result, ResultExt, Val,
 };
 use jrsonnet_parser::IStr;
modifiedcrates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,7 +1,7 @@
 use jrsonnet_evaluator::{
 	bail, in_description_frame,
 	manifest::{ManifestFormat, ToStringFormat},
-	typed::{ComplexValType, Either2, Typed, ValType},
+	typed::{ComplexValType, Either2, FromUntyped, Typed, ValType},
 	val::ArrValue,
 	Either, ObjValue, Result, ResultExt, Val,
 };
@@ -32,11 +32,8 @@
 }
 impl Typed for JSONMLValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
-
-	fn into_untyped(_typed: Self) -> Result<Val> {
-		unreachable!("not used, reserved for parseXML?")
-	}
-
+}
+impl FromUntyped for JSONMLValue {
 	fn from_untyped(untyped: Val) -> Result<Self> {
 		let val = <Either![ArrValue, String]>::from_untyped(untyped)
 			.description("parsing JSONML value (an array or string)")?;
@@ -73,7 +70,7 @@
 			children: in_description_frame(
 				|| "parsing children".to_owned(),
 				|| {
-					Typed::from_untyped(Val::Arr(arr.slice(
+					FromUntyped::from_untyped(Val::Arr(arr.slice(
 						Some(if has_attrs { 2 } else { 1 }),
 						None,
 						None,
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -4,7 +4,7 @@
 	bail,
 	error::{ErrorKind::*, Result},
 	function::builtin,
-	typed::{Either2, Typed, M1},
+	typed::{Either2, FromUntyped, M1},
 	val::{ArrValue, IndexableVal},
 	Either, IStr, Val,
 };
modifiedtests/tests/builtin.rsdiffbeforeafterboth
--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -5,7 +5,7 @@
 	function::{CallLocation, FuncVal, builtin, builtin::Builtin},
 	parser::Source,
 	trace::PathResolver,
-	typed::Typed,
+	typed::FromUntyped,
 };
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_stdlib::ContextInitializer as StdContextInitializer;
modifiedtests/tests/typed_obj.rsdiffbeforeafterboth
--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -2,7 +2,11 @@
 
 use std::fmt::Debug;
 
-use jrsonnet_evaluator::{Result, State, trace::PathResolver, typed::Typed};
+use jrsonnet_evaluator::{
+	Result, State,
+	trace::PathResolver,
+	typed::{FromUntyped, IntoUntyped, Typed},
+};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone, Typed, PartialEq, Debug)]
@@ -11,7 +15,9 @@
 	b: u16,
 }
 
-fn test_roundtrip<T: Typed + PartialEq + Debug + Clone>(value: T) -> Result<()> {
+fn test_roundtrip<T: Typed + PartialEq + Debug + Clone + FromUntyped + IntoUntyped>(
+	value: T,
+) -> Result<()> {
 	let untyped = T::into_untyped(value.clone())?;
 	let value2 = T::from_untyped(untyped.clone())?;
 	ensure_eq!(value, value2);