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
before · crates/jrsonnet-evaluator/src/typed/conversions.rs
1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9	arr::{ArrValue, BytesArray},10	bail,11	function::{FuncDesc, FuncVal},12	typed::CheckType,13	val::{IndexableVal, NumValue, StrValue, ThunkMapper},14	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,15};1617#[derive(Trace)]18struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for FromUntyped<K>20where21	K: Typed + Trace,22{23	type Output = K;2425	fn map(self, from: Val) -> Result<Self::Output> {26		K::from_untyped(from)27	}28}29impl<K: Trace> Default for FromUntyped<K> {30	fn default() -> Self {31		Self(PhantomData)32	}33}3435pub trait TypedObj: Typed {36	fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;37	fn parse(obj: &ObjValue) -> Result<Self>;38	fn into_object(self) -> Result<ObjValue> {39		let mut builder = ObjValueBuilder::new();40		self.serialize(&mut builder)?;41		Ok(builder.build())42	}43}4445pub trait Typed: Sized {46	const TYPE: &'static ComplexValType;47	fn into_untyped(typed: Self) -> Result<Val>;48	fn into_lazy_untyped(typed: Self) -> Thunk<Val> {49		Thunk::from(Self::into_untyped(typed))50	}51	fn from_untyped(untyped: Val) -> Result<Self>;52	fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {53		Self::from_untyped(lazy.evaluate()?)54	}5556	// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`57	fn provides_lazy() -> bool {58		false59	}6061	// Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible62	fn wants_lazy() -> bool {63		false64	}6566	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result67	/// This method returns identity in impl Typed for Result, and should not be overriden68	#[doc(hidden)]69	fn into_result(typed: Self) -> Result<Val> {70		let value = Self::into_untyped(typed)?;71		Ok(value)72	}73}7475impl<T> Typed for Thunk<T>76where77	T: Typed + Trace + Clone,78{79	const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8081	fn into_untyped(typed: Self) -> Result<Val> {82		T::into_untyped(typed.evaluate()?)83	}8485	fn from_untyped(untyped: Val) -> Result<Self> {86		Self::from_lazy_untyped(Thunk::evaluated(untyped))87	}8889	fn provides_lazy() -> bool {90		true91	}9293	fn into_lazy_untyped(inner: Self) -> Thunk<Val> {94		#[derive(Trace)]95		struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);96		impl<K> ThunkMapper<K> for IntoUntyped<K>97		where98			K: Typed + Trace,99		{100			type Output = Val;101102			fn map(self, from: K) -> Result<Self::Output> {103				K::into_untyped(from)104			}105		}106		impl<K: Trace> Default for IntoUntyped<K> {107			fn default() -> Self {108				Self(PhantomData)109			}110		}111		inner.map(<IntoUntyped<T>>::default())112	}113114	fn wants_lazy() -> bool {115		true116	}117118	fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {119		Ok(inner.map(<FromUntyped<T>>::default()))120	}121}122123pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;124pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;125126macro_rules! impl_int {127	($($ty:ty)*) => {$(128		impl Typed for $ty {129			const TYPE: &'static ComplexValType =130				&ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));131			fn from_untyped(value: Val) -> Result<Self> {132				<Self as Typed>::TYPE.check(&value)?;133				match value {134					Val::Num(n) => {135						let n = n.get();136						#[allow(clippy::float_cmp)]137						if n.trunc() != n {138							bail!(139								"cannot convert number with fractional part to {}",140								stringify!($ty)141							)142						}143						Ok(n as Self)144					}145					_ => unreachable!(),146				}147			}148			fn into_untyped(value: Self) -> Result<Val> {149				Ok(Val::Num(value.into()))150			}151		}152	)*};153}154155impl_int!(i8 u8 i16 u16 i32 u32);156157macro_rules! impl_bounded_int {158	($($name:ident = $ty:ty)*) => {$(159		#[derive(Clone, Copy)]160		pub struct $name<const MIN: $ty, const MAX: $ty>($ty);161		impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {162			pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {163				if value >= MIN && value <= MAX {164					Some(Self(value))165				} else {166					None167				}168			}169			pub const fn value(self) -> $ty {170				self.0171			}172		}173		impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {174			type Target = $ty;175			fn deref(&self) -> &Self::Target {176				&self.0177			}178		}179180		impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {181			const TYPE: &'static ComplexValType =182				&ComplexValType::BoundedNumber(183					Some(MIN as f64),184					Some(MAX as f64),185				);186187			fn from_untyped(value: Val) -> Result<Self> {188				<Self as Typed>::TYPE.check(&value)?;189				match value {190					Val::Num(n) => {191						let n = n.get();192						#[allow(clippy::float_cmp)]193						if n.trunc() != n {194							bail!(195								"cannot convert number with fractional part to {}",196								stringify!($ty)197							)198						}199						Ok(Self(n as $ty))200					}201					_ => unreachable!(),202				}203			}204205			#[allow(clippy::cast_lossless)]206			fn into_untyped(value: Self) -> Result<Val> {207				Ok(Val::try_num(value.0)?)208			}209		}210	)*};211}212213impl_bounded_int!(214	BoundedI8 = i8215	BoundedI16 = i16216	BoundedI32 = i32217	BoundedI64 = i64218	BoundedUsize = usize219);220221impl Typed for f64 {222	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);223224	fn into_untyped(value: Self) -> Result<Val> {225		Ok(Val::try_num(value)?)226	}227228	fn from_untyped(value: Val) -> Result<Self> {229		<Self as Typed>::TYPE.check(&value)?;230		match value {231			Val::Num(n) => Ok(n.get()),232			_ => unreachable!(),233		}234	}235}236237pub struct PositiveF64(pub f64);238impl Typed for PositiveF64 {239	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);240241	fn into_untyped(value: Self) -> Result<Val> {242		Ok(Val::try_num(value.0)?)243	}244245	fn from_untyped(value: Val) -> Result<Self> {246		<Self as Typed>::TYPE.check(&value)?;247		match value {248			Val::Num(n) => Ok(Self(n.get())),249			_ => unreachable!(),250		}251	}252}253impl Typed for usize {254	const TYPE: &'static ComplexValType =255		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));256257	fn into_untyped(value: Self) -> Result<Val> {258		Ok(Val::try_num(value)?)259	}260261	fn from_untyped(value: Val) -> Result<Self> {262		<Self as Typed>::TYPE.check(&value)?;263		match value {264			Val::Num(n) => {265				let n = n.get();266				#[allow(clippy::float_cmp)]267				if n.trunc() != n {268					bail!("cannot convert number with fractional part to usize")269				}270				Ok(n as Self)271			}272			_ => unreachable!(),273		}274	}275}276277impl Typed for IStr {278	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);279280	fn into_untyped(value: Self) -> Result<Val> {281		Ok(Val::string(value))282	}283284	fn from_untyped(value: Val) -> Result<Self> {285		<Self as Typed>::TYPE.check(&value)?;286		match value {287			Val::Str(s) => Ok(s.into_flat()),288			_ => unreachable!(),289		}290	}291}292293impl Typed for String {294	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);295296	fn into_untyped(value: Self) -> Result<Val> {297		Ok(Val::string(value))298	}299300	fn from_untyped(value: Val) -> Result<Self> {301		<Self as Typed>::TYPE.check(&value)?;302		match value {303			Val::Str(s) => Ok(s.to_string()),304			_ => unreachable!(),305		}306	}307}308309impl Typed for StrValue {310	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);311312	fn into_untyped(value: Self) -> Result<Val> {313		Ok(Val::Str(value))314	}315316	fn from_untyped(value: Val) -> Result<Self> {317		<Self as Typed>::TYPE.check(&value)?;318		match value {319			Val::Str(s) => Ok(s),320			_ => unreachable!(),321		}322	}323}324325impl Typed for char {326	const TYPE: &'static ComplexValType = &ComplexValType::Char;327328	fn into_untyped(value: Self) -> Result<Val> {329		Ok(Val::string(value))330	}331332	fn from_untyped(value: Val) -> Result<Self> {333		<Self as Typed>::TYPE.check(&value)?;334		match value {335			Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),336			_ => unreachable!(),337		}338	}339}340341impl<T> Typed for Vec<T>342where343	T: Typed,344{345	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);346347	fn into_untyped(value: Self) -> Result<Val> {348		Ok(Val::Arr(349			value350				.into_iter()351				.map(T::into_untyped)352				.collect::<Result<ArrValue>>()?,353		))354	}355356	fn from_untyped(value: Val) -> Result<Self> {357		let Val::Arr(a) = value else {358			<Self as Typed>::TYPE.check(&value)?;359			unreachable!("typecheck should fail")360		};361		a.iter()362			.enumerate()363			.map(|(i, r)| {364				r.and_then(|t| {365					T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))366				})367			})368			.collect::<Result<Self>>()369	}370}371372impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {373	const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);374375	fn into_untyped(typed: Self) -> Result<Val> {376		let mut out = ObjValueBuilder::with_capacity(typed.len());377		for (k, v) in typed {378			let Some(key) = K::into_untyped(k)?.as_str() else {379				bail!("map key should serialize to string");380			};381			let value = V::into_untyped(v)?;382			out.field(key).value(value);383		}384		Ok(Val::Obj(out.build()))385	}386387	fn from_untyped(value: Val) -> Result<Self> {388		Self::TYPE.check(&value)?;389		let obj = value.as_obj().expect("typecheck should fail");390391		let mut out = Self::new();392		if V::wants_lazy() {393			for key in obj.fields_ex(394				false,395				#[cfg(feature = "exp-preserve-order")]396				false,397			) {398				let value = obj.get_lazy(key.clone()).expect("field exists");399				let value = V::from_lazy_untyped(value)?;400				let key = K::from_untyped(Val::Str(key.into()))?;401				let _ = out.insert(key, value);402			}403		} else {404			for (key, value) in obj.iter(405				#[cfg(feature = "exp-preserve-order")]406				false,407			) {408				let key = K::from_untyped(Val::Str(key.into()))?;409				let value = V::from_untyped(value?)?;410				let _ = out.insert(key, value);411			}412		}413		Ok(out)414	}415}416417impl Typed for Val {418	const TYPE: &'static ComplexValType = &ComplexValType::Any;419420	fn into_untyped(typed: Self) -> Result<Val> {421		Ok(typed)422	}423	fn from_untyped(untyped: Val) -> Result<Self> {424		Ok(untyped)425	}426}427428// Hack429#[doc(hidden)]430impl<T> Typed for Result<T>431where432	T: Typed,433{434	const TYPE: &'static ComplexValType = &ComplexValType::Any;435436	fn into_untyped(_typed: Self) -> Result<Val> {437		panic!("do not use this conversion")438	}439440	fn from_untyped(_untyped: Val) -> Result<Self> {441		panic!("do not use this conversion")442	}443444	fn into_result(typed: Self) -> Result<Val> {445		typed.map(T::into_untyped)?446	}447}448449/// Specialization450impl Typed for IBytes {451	const TYPE: &'static ComplexValType =452		&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));453454	fn into_untyped(value: Self) -> Result<Val> {455		Ok(Val::Arr(ArrValue::bytes(value)))456	}457458	fn from_untyped(value: Val) -> Result<Self> {459		let Val::Arr(a) = &value else {460			<Self as Typed>::TYPE.check(&value)?;461			unreachable!()462		};463		if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {464			return Ok(bytes.0.as_slice().into());465		}466		<Self as Typed>::TYPE.check(&value)?;467		// Any::downcast_ref::<ByteArray>(&a);468		let mut out = Vec::with_capacity(a.len());469		for e in a.iter() {470			let r = e?;471			out.push(u8::from_untyped(r)?);472		}473		Ok(out.as_slice().into())474	}475}476477pub struct M1;478impl Typed for M1 {479	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));480481	fn into_untyped(_: Self) -> Result<Val> {482		Ok(Val::Num(NumValue::new(-1.0).expect("finite")))483	}484485	fn from_untyped(value: Val) -> Result<Self> {486		<Self as Typed>::TYPE.check(&value)?;487		Ok(Self)488	}489}490491macro_rules! decl_either {492	($($name: ident, $($id: ident)*);*) => {$(493		#[derive(Clone)]494		pub enum $name<$($id),*> {495			$($id($id)),*496		}497		impl<$($id),*> Typed for $name<$($id),*>498		where499			$($id: Typed,)*500		{501			const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);502503			fn into_untyped(value: Self) -> Result<Val> {504				match value {$(505					$name::$id(v) => $id::into_untyped(v)506				),*}507			}508509			fn from_untyped(value: Val) -> Result<Self> {510				$(511					if $id::TYPE.check(&value).is_ok() {512						$id::from_untyped(value).map(Self::$id)513					} else514				)* {515					<Self as Typed>::TYPE.check(&value)?;516					unreachable!()517				}518			}519		}520	)*}521}522decl_either!(523	Either1, A;524	Either2, A B;525	Either3, A B C;526	Either4, A B C D;527	Either5, A B C D E;528	Either6, A B C D E F;529	Either7, A B C D E F G530);531#[macro_export]532macro_rules! Either {533	($a:ty) => {$crate::typed::Either1<$a>};534	($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};535	($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};536	($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};537	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};538	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};539	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};540}541pub use Either;542543pub type MyType = Either![u32, f64, String];544545impl Typed for ArrValue {546	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);547548	fn into_untyped(value: Self) -> Result<Val> {549		Ok(Val::Arr(value))550	}551552	fn from_untyped(value: Val) -> Result<Self> {553		<Self as Typed>::TYPE.check(&value)?;554		match value {555			Val::Arr(a) => Ok(a),556			_ => unreachable!(),557		}558	}559}560561impl Typed for FuncVal {562	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);563564	fn into_untyped(value: Self) -> Result<Val> {565		Ok(Val::Func(value))566	}567568	fn from_untyped(value: Val) -> Result<Self> {569		<Self as Typed>::TYPE.check(&value)?;570		match value {571			Val::Func(a) => Ok(a),572			_ => unreachable!(),573		}574	}575}576577impl Typed for Cc<FuncDesc> {578	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);579580	fn into_untyped(value: Self) -> Result<Val> {581		Ok(Val::Func(FuncVal::Normal(value)))582	}583584	fn from_untyped(value: Val) -> Result<Self> {585		<Self as Typed>::TYPE.check(&value)?;586		match value {587			Val::Func(FuncVal::Normal(desc)) => Ok(desc),588			Val::Func(_) => bail!("expected normal function, not builtin"),589			_ => unreachable!(),590		}591	}592}593594impl Typed for ObjValue {595	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);596597	fn into_untyped(value: Self) -> Result<Val> {598		Ok(Val::Obj(value))599	}600601	fn from_untyped(value: Val) -> Result<Self> {602		<Self as Typed>::TYPE.check(&value)?;603		match value {604			Val::Obj(a) => Ok(a),605			_ => unreachable!(),606		}607	}608}609610impl Typed for bool {611	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);612613	fn into_untyped(value: Self) -> Result<Val> {614		Ok(Val::Bool(value))615	}616617	fn from_untyped(value: Val) -> Result<Self> {618		<Self as Typed>::TYPE.check(&value)?;619		match value {620			Val::Bool(a) => Ok(a),621			_ => unreachable!(),622		}623	}624}625impl Typed for IndexableVal {626	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[627		&ComplexValType::Simple(ValType::Arr),628		&ComplexValType::Simple(ValType::Str),629	]);630631	fn into_untyped(value: Self) -> Result<Val> {632		match value {633			Self::Str(s) => Ok(Val::string(s)),634			Self::Arr(a) => Ok(Val::Arr(a)),635		}636	}637638	fn from_untyped(value: Val) -> Result<Self> {639		<Self as Typed>::TYPE.check(&value)?;640		value.into_indexable()641	}642}643644pub struct Null;645impl Typed for Null {646	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);647648	fn into_untyped(_: Self) -> Result<Val> {649		Ok(Val::Null)650	}651652	fn from_untyped(value: Val) -> Result<Self> {653		<Self as Typed>::TYPE.check(&value)?;654		Ok(Self)655	}656}657658impl<T> Typed for Option<T>659where660	T: Typed,661{662	const TYPE: &'static ComplexValType =663		&ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);664665	fn into_untyped(typed: Self) -> Result<Val> {666		typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))667	}668669	fn from_untyped(untyped: Val) -> Result<Self> {670		if matches!(untyped, Val::Null) {671			Ok(None)672		} else {673			T::from_untyped(untyped).map(Some)674		}675	}676}677678impl Typed for NumValue {679	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);680681	fn into_untyped(typed: Self) -> Result<Val> {682		Ok(Val::Num(typed))683	}684685	fn from_untyped(untyped: Val) -> Result<Self> {686		Self::TYPE.check(&untyped)?;687		match untyped {688			Val::Num(v) => Ok(v),689			_ => unreachable!(),690		}691	}692}
after · crates/jrsonnet-evaluator/src/typed/conversions.rs
1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9	arr::{ArrValue, BytesArray},10	bail,11	function::FuncVal,12	typed::CheckType,13	val::{IndexableVal, NumValue, StrValue, ThunkMapper},14	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,15};1617#[derive(Trace)]18struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>20where21	K: Typed + FromUntyped + Trace,22{23	type Output = K;2425	fn map(self, from: Val) -> Result<Self::Output> {26		K::from_untyped(from)27	}28}29impl<K: Trace> Default for ThunkFromUntyped<K> {30	fn default() -> Self {31		Self(PhantomData)32	}33}34#[derive(Trace)]35struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);36impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>37where38	K: Typed + Trace + IntoUntyped,39{40	type Output = Val;4142	fn map(self, from: K) -> Result<Self::Output> {43		K::into_untyped(from)44	}45}46impl<K: Trace> Default for ThunkIntoUntyped<K> {47	fn default() -> Self {48		Self(PhantomData)49	}50}5152pub trait TypedObj: Typed {53	fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;54	fn parse(obj: &ObjValue) -> Result<Self>;55	fn into_object(self) -> Result<ObjValue> {56		let mut builder = ObjValueBuilder::new();57		self.serialize(&mut builder)?;58		Ok(builder.build())59	}60}6162pub trait Typed: Sized {63	const TYPE: &'static ComplexValType;64}65pub trait IntoUntyped: Typed {66	// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`67	fn provides_lazy() -> bool {68		false69	}70	fn into_untyped(typed: Self) -> Result<Val>;71	fn into_lazy_untyped(typed: Self) -> Thunk<Val> {72		Thunk::from(Self::into_untyped(typed))73	}74}75pub trait IntoUntypedResult: Typed {76	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result77	/// This method returns identity in impl Typed for Result, and should not be overriden78	#[doc(hidden)]79	fn into_untyped_result(typed: Self) -> Result<Val>;80}81impl<T> IntoUntypedResult for T82where83	T: IntoUntyped,84{85	fn into_untyped_result(typed: Self) -> Result<Val> {86		T::into_untyped(typed)87	}88}8990pub trait FromUntyped: Typed {91	fn from_untyped(untyped: Val) -> Result<Self>;92	fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {93		Self::from_untyped(lazy.evaluate()?)94	}9596	// Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible97	fn wants_lazy() -> bool {98		false99	}100}101102impl<T> Typed for Thunk<T>103where104	T: Typed + Trace + Clone,105{106	const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);107}108109impl<T> IntoUntyped for Thunk<T>110where111	T: Typed + IntoUntyped + Trace + Clone,112{113	fn into_untyped(typed: Self) -> Result<Val> {114		T::into_untyped(typed.evaluate()?)115	}116	fn provides_lazy() -> bool {117		true118	}119120	fn into_lazy_untyped(inner: Self) -> Thunk<Val> {121		inner.map(<ThunkIntoUntyped<T>>::default())122	}123}124125impl<T> FromUntyped for Thunk<T>126where127	T: Typed + FromUntyped + Trace + Clone,128{129	fn from_untyped(untyped: Val) -> Result<Self> {130		Self::from_lazy_untyped(Thunk::evaluated(untyped))131	}132133	fn wants_lazy() -> bool {134		true135	}136137	fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {138		Ok(inner.map(<ThunkFromUntyped<T>>::default()))139	}140}141142pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;143pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;144145macro_rules! impl_int {146	($($ty:ty)*) => {$(147		impl Typed for $ty {148			const TYPE: &'static ComplexValType =149				&ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));150		}151		impl FromUntyped for $ty {152			fn from_untyped(value: Val) -> Result<Self> {153				<Self as Typed>::TYPE.check(&value)?;154				match value {155					Val::Num(n) => {156						let n = n.get();157						#[allow(clippy::float_cmp)]158						if n.trunc() != n {159							bail!(160								"cannot convert number with fractional part to {}",161								stringify!($ty)162							)163						}164						Ok(n as Self)165					}166					_ => unreachable!(),167				}168			}169		}170		impl IntoUntyped for $ty {171			fn into_untyped(value: Self) -> Result<Val> {172				Ok(Val::Num(value.into()))173			}174		}175	)*};176}177178impl_int!(i8 u8 i16 u16 i32 u32);179180macro_rules! impl_bounded_int {181	($($name:ident = $ty:ty)*) => {$(182		#[derive(Clone, Copy)]183		pub struct $name<const MIN: $ty, const MAX: $ty>($ty);184		impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {185			pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {186				if value >= MIN && value <= MAX {187					Some(Self(value))188				} else {189					None190				}191			}192			pub const fn value(self) -> $ty {193				self.0194			}195		}196		impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {197			type Target = $ty;198			fn deref(&self) -> &Self::Target {199				&self.0200			}201		}202203		impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {204			const TYPE: &'static ComplexValType =205				&ComplexValType::BoundedNumber(206					Some(MIN as f64),207					Some(MAX as f64),208				);209		}210211		impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {212			fn from_untyped(value: Val) -> Result<Self> {213				<Self as Typed>::TYPE.check(&value)?;214				match value {215					Val::Num(n) => {216						let n = n.get();217						#[allow(clippy::float_cmp)]218						if n.trunc() != n {219							bail!(220								"cannot convert number with fractional part to {}",221								stringify!($ty)222							)223						}224						Ok(Self(n as $ty))225					}226					_ => unreachable!(),227				}228			}229		}230231		impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {232			#[allow(clippy::cast_lossless)]233			fn into_untyped(value: Self) -> Result<Val> {234				Ok(Val::try_num(value.0)?)235			}236		}237	)*};238}239240impl_bounded_int!(241	BoundedI8 = i8242	BoundedI16 = i16243	BoundedI32 = i32244	BoundedI64 = i64245	BoundedUsize = usize246);247248impl Typed for f64 {249	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);250}251impl IntoUntyped for f64 {252	fn into_untyped(value: Self) -> Result<Val> {253		Ok(Val::try_num(value)?)254	}255}256impl FromUntyped for f64 {257	fn from_untyped(value: Val) -> Result<Self> {258		<Self as Typed>::TYPE.check(&value)?;259		match value {260			Val::Num(n) => Ok(n.get()),261			_ => unreachable!(),262		}263	}264}265266pub struct PositiveF64(pub f64);267impl Typed for PositiveF64 {268	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);269}270impl IntoUntyped for PositiveF64 {271	fn into_untyped(value: Self) -> Result<Val> {272		Ok(Val::try_num(value.0)?)273	}274}275impl FromUntyped for PositiveF64 {276	fn from_untyped(value: Val) -> Result<Self> {277		<Self as Typed>::TYPE.check(&value)?;278		match value {279			Val::Num(n) => Ok(Self(n.get())),280			_ => unreachable!(),281		}282	}283}284impl Typed for usize {285	const TYPE: &'static ComplexValType =286		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));287}288impl IntoUntyped for usize {289	fn into_untyped(value: Self) -> Result<Val> {290		Ok(Val::try_num(value)?)291	}292}293impl FromUntyped for usize {294	fn from_untyped(value: Val) -> Result<Self> {295		<Self as Typed>::TYPE.check(&value)?;296		match value {297			Val::Num(n) => {298				let n = n.get();299				#[allow(clippy::float_cmp)]300				if n.trunc() != n {301					bail!("cannot convert number with fractional part to usize")302				}303				Ok(n as Self)304			}305			_ => unreachable!(),306		}307	}308}309310impl Typed for IStr {311	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);312}313impl IntoUntyped for IStr {314	fn into_untyped(value: Self) -> Result<Val> {315		Ok(Val::string(value))316	}317}318impl FromUntyped for IStr {319	fn from_untyped(value: Val) -> Result<Self> {320		<Self as Typed>::TYPE.check(&value)?;321		match value {322			Val::Str(s) => Ok(s.into_flat()),323			_ => unreachable!(),324		}325	}326}327328impl Typed for String {329	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);330}331impl IntoUntyped for String {332	fn into_untyped(value: Self) -> Result<Val> {333		Ok(Val::string(value))334	}335}336impl FromUntyped for String {337	fn from_untyped(value: Val) -> Result<Self> {338		<Self as Typed>::TYPE.check(&value)?;339		match value {340			Val::Str(s) => Ok(s.to_string()),341			_ => unreachable!(),342		}343	}344}345346impl Typed for StrValue {347	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);348}349impl IntoUntyped for StrValue {350	fn into_untyped(value: Self) -> Result<Val> {351		Ok(Val::Str(value))352	}353}354impl FromUntyped for StrValue {355	fn from_untyped(value: Val) -> Result<Self> {356		<Self as Typed>::TYPE.check(&value)?;357		match value {358			Val::Str(s) => Ok(s),359			_ => unreachable!(),360		}361	}362}363364impl Typed for char {365	const TYPE: &'static ComplexValType = &ComplexValType::Char;366}367impl IntoUntyped for char {368	fn into_untyped(value: Self) -> Result<Val> {369		Ok(Val::string(value))370	}371}372impl FromUntyped for char {373	fn from_untyped(value: Val) -> Result<Self> {374		<Self as Typed>::TYPE.check(&value)?;375		match value {376			Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),377			_ => unreachable!(),378		}379	}380}381382// TODO: View into vec using ArrayLike?383impl<T> Typed for Vec<T>384where385	T: Typed,386{387	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);388}389impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {390	fn into_untyped(value: Self) -> Result<Val> {391		Ok(Val::Arr(392			value393				.into_iter()394				.map(T::into_untyped)395				.collect::<Result<ArrValue>>()?,396		))397	}398}399impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {400	fn from_untyped(value: Val) -> Result<Self> {401		let Val::Arr(a) = value else {402			<Self as Typed>::TYPE.check(&value)?;403			unreachable!("typecheck should fail")404		};405		a.iter()406			.enumerate()407			.map(|(i, r)| {408				r.and_then(|t| {409					T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))410				})411			})412			.collect::<Result<Self>>()413	}414}415416// TODO: View into BTreeMap using ObjectCore?417impl<K, V> Typed for BTreeMap<K, V>418where419	K: Typed + Ord,420	V: Typed,421{422	const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);423}424impl<K, V> IntoUntyped for BTreeMap<K, V>425where426	K: Typed + Ord + IntoUntyped,427	V: Typed + IntoUntyped,428{429	fn into_untyped(typed: Self) -> Result<Val> {430		let mut out = ObjValueBuilder::with_capacity(typed.len());431		for (k, v) in typed {432			let Some(key) = K::into_untyped(k)?.as_str() else {433				bail!("map key should serialize to string");434			};435			let value = V::into_untyped(v)?;436			out.field(key).value(value);437		}438		Ok(Val::Obj(out.build()))439	}440}441impl<K, V> FromUntyped for BTreeMap<K, V>442where443	K: FromUntyped + Ord,444	V: FromUntyped,445{446	fn from_untyped(value: Val) -> Result<Self> {447		Self::TYPE.check(&value)?;448		let obj = value.as_obj().expect("typecheck should fail");449450		let mut out = Self::new();451		if V::wants_lazy() {452			for key in obj.fields_ex(453				false,454				#[cfg(feature = "exp-preserve-order")]455				false,456			) {457				let value = obj.get_lazy(key.clone()).expect("field exists");458				let value = V::from_lazy_untyped(value)?;459				let key = K::from_untyped(Val::Str(key.into()))?;460				let _ = out.insert(key, value);461			}462		} else {463			for (key, value) in obj.iter(464				#[cfg(feature = "exp-preserve-order")]465				false,466			) {467				let key = K::from_untyped(Val::Str(key.into()))?;468				let value = V::from_untyped(value?)?;469				let _ = out.insert(key, value);470			}471		}472		Ok(out)473	}474}475476impl Typed for Val {477	const TYPE: &'static ComplexValType = &ComplexValType::Any;478}479impl IntoUntyped for Val {480	fn into_untyped(typed: Self) -> Result<Val> {481		Ok(typed)482	}483}484impl FromUntyped for Val {485	fn from_untyped(untyped: Val) -> Result<Self> {486		Ok(untyped)487	}488}489490#[doc(hidden)]491impl<T> Typed for Result<T>492where493	T: Typed,494{495	const TYPE: &'static ComplexValType = &ComplexValType::Any;496}497impl<T: IntoUntyped> IntoUntypedResult for Result<T> {498	fn into_untyped_result(typed: Self) -> Result<Val> {499		typed.map(T::into_untyped)?500	}501}502503/// Specialization504impl Typed for IBytes {505	const TYPE: &'static ComplexValType =506		&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));507}508impl IntoUntyped for IBytes {509	fn into_untyped(value: Self) -> Result<Val> {510		Ok(Val::Arr(ArrValue::bytes(value)))511	}512}513impl FromUntyped for IBytes {514	fn from_untyped(value: Val) -> Result<Self> {515		let Val::Arr(a) = &value else {516			<Self as Typed>::TYPE.check(&value)?;517			unreachable!()518		};519		if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {520			return Ok(bytes.0.as_slice().into());521		}522		<Self as Typed>::TYPE.check(&value)?;523		// Any::downcast_ref::<ByteArray>(&a);524		let mut out = Vec::with_capacity(a.len());525		for e in a.iter() {526			let r = e?;527			out.push(u8::from_untyped(r)?);528		}529		Ok(out.as_slice().into())530	}531}532533pub struct M1;534impl Typed for M1 {535	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));536}537impl IntoUntyped for M1 {538	fn into_untyped(_: Self) -> Result<Val> {539		Ok(Val::Num(NumValue::new(-1.0).expect("finite")))540	}541}542impl FromUntyped for M1 {543	fn from_untyped(value: Val) -> Result<Self> {544		<Self as Typed>::TYPE.check(&value)?;545		Ok(Self)546	}547}548549macro_rules! decl_either {550	($($name: ident, $($id: ident)*);*) => {$(551		#[derive(Clone)]552		pub enum $name<$($id),*> {553			$($id($id)),*554		}555		impl<$($id),*> Typed for $name<$($id),*>556		where557			$($id: Typed,)*558		{559			const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);560		}561		impl<$($id),*> IntoUntyped for $name<$($id),*>562		where563			$($id: Typed + IntoUntyped,)*564		{565			fn into_untyped(value: Self) -> Result<Val> {566				match value {$(567					$name::$id(v) => $id::into_untyped(v)568				),*}569			}570		}571572		impl<$($id),*> FromUntyped for $name<$($id),*>573		where574			$($id: Typed + FromUntyped,)*575		{576			fn from_untyped(value: Val) -> Result<Self> {577				$(578					if $id::TYPE.check(&value).is_ok() {579						$id::from_untyped(value).map(Self::$id)580					} else581				)* {582					<Self as Typed>::TYPE.check(&value)?;583					unreachable!()584				}585			}586		}587	)*}588}589decl_either!(590	Either1, A;591	Either2, A B;592	Either3, A B C;593	Either4, A B C D;594	Either5, A B C D E;595	Either6, A B C D E F;596	Either7, A B C D E F G597);598#[macro_export]599macro_rules! Either {600	($a:ty) => {$crate::typed::Either1<$a>};601	($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};602	($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};603	($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};604	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};605	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};606	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};607}608pub use Either;609610pub type MyType = Either![u32, f64, String];611612impl Typed for ArrValue {613	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);614}615impl IntoUntyped for ArrValue {616	fn into_untyped(value: Self) -> Result<Val> {617		Ok(Val::Arr(value))618	}619}620impl FromUntyped for ArrValue {621	fn from_untyped(value: Val) -> Result<Self> {622		<Self as Typed>::TYPE.check(&value)?;623		match value {624			Val::Arr(a) => Ok(a),625			_ => unreachable!(),626		}627	}628}629630impl Typed for FuncVal {631	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);632}633impl IntoUntyped for FuncVal {634	fn into_untyped(value: Self) -> Result<Val> {635		Ok(Val::Func(value))636	}637}638impl FromUntyped for FuncVal {639	fn from_untyped(value: Val) -> Result<Self> {640		<Self as Typed>::TYPE.check(&value)?;641		match value {642			Val::Func(a) => Ok(a),643			_ => unreachable!(),644		}645	}646}647648impl Typed for ObjValue {649	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);650}651impl IntoUntyped for ObjValue {652	fn into_untyped(value: Self) -> Result<Val> {653		Ok(Val::Obj(value))654	}655}656impl FromUntyped for ObjValue {657	fn from_untyped(value: Val) -> Result<Self> {658		<Self as Typed>::TYPE.check(&value)?;659		match value {660			Val::Obj(a) => Ok(a),661			_ => unreachable!(),662		}663	}664}665666impl Typed for bool {667	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);668}669impl IntoUntyped for bool {670	fn into_untyped(value: Self) -> Result<Val> {671		Ok(Val::Bool(value))672	}673}674impl FromUntyped for bool {675	fn from_untyped(value: Val) -> Result<Self> {676		<Self as Typed>::TYPE.check(&value)?;677		match value {678			Val::Bool(a) => Ok(a),679			_ => unreachable!(),680		}681	}682}683684impl Typed for IndexableVal {685	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[686		&ComplexValType::Simple(ValType::Arr),687		&ComplexValType::Simple(ValType::Str),688	]);689}690impl IntoUntyped for IndexableVal {691	fn into_untyped(value: Self) -> Result<Val> {692		match value {693			Self::Str(s) => Ok(Val::string(s)),694			Self::Arr(a) => Ok(Val::Arr(a)),695		}696	}697}698impl FromUntyped for IndexableVal {699	fn from_untyped(value: Val) -> Result<Self> {700		<Self as Typed>::TYPE.check(&value)?;701		value.into_indexable()702	}703}704705pub struct Null;706impl Typed for Null {707	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);708}709impl IntoUntyped for Null {710	fn into_untyped(_: Self) -> Result<Val> {711		Ok(Val::Null)712	}713}714impl FromUntyped for Null {715	fn from_untyped(value: Val) -> Result<Self> {716		<Self as Typed>::TYPE.check(&value)?;717		Ok(Self)718	}719}720721impl<T> Typed for Option<T>722where723	T: Typed,724{725	const TYPE: &'static ComplexValType =726		&ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);727}728impl<T> IntoUntyped for Option<T>729where730	T: Typed + IntoUntyped,731{732	fn into_untyped(typed: Self) -> Result<Val> {733		typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))734	}735}736impl<T> FromUntyped for Option<T>737where738	T: Typed + FromUntyped,739{740	fn from_untyped(untyped: Val) -> Result<Self> {741		if matches!(untyped, Val::Null) {742			Ok(None)743		} else {744			T::from_untyped(untyped).map(Some)745		}746	}747}748749impl Typed for NumValue {750	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);751}752impl IntoUntyped for NumValue {753	fn into_untyped(typed: Self) -> Result<Val> {754		Ok(Val::Num(typed))755	}756}757impl FromUntyped for NumValue {758	fn from_untyped(untyped: Val) -> Result<Self> {759		Self::TYPE.check(&untyped)?;760		match untyped {761			Val::Num(v) => Ok(v),762			_ => unreachable!(),763		}764	}765}
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
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -8,15 +8,15 @@
 	parse_macro_input,
 	punctuated::Punctuated,
 	spanned::Spanned,
-	token::{self, Comma},
+	token::Comma,
 	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
 	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
 };
 
 use self::typed::derive_typed_inner;
 
+mod names;
 mod typed;
-mod names;
 
 fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
 where
@@ -202,7 +202,7 @@
 			_ => {}
 		}
 
-		let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {
+		let (optionality, ty) = if try_parse_attr_noargs(&arg.attrs, "default")? {
 			remove_attr(&mut arg.attrs, "default");
 			(Optionality::TypeDefault, ty.clone())
 		} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
@@ -322,7 +322,7 @@
 				let name = name.as_ref().map_or("<unnamed>", String::as_str);
 				let eval = quote! {jrsonnet_evaluator::in_description_frame(
 					|| format!("argument <{}> evaluation", #name),
-					|| <#ty>::from_untyped(value.evaluate()?),
+					|| <#ty as FromUntyped>::from_untyped(value.evaluate()?),
 				)?};
 				let value = match optionality {
 					Optionality::Required => quote! {{
@@ -411,7 +411,7 @@
 			use ::jrsonnet_evaluator::{
 				State, Val,
 				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},
-				Result, Context, typed::Typed,
+				Result, Context, typed::{Typed, FromUntyped, IntoUntypedResult},
 				parser::Span, params, Thunk,
 			};
 			params!(
@@ -432,7 +432,7 @@
 				#[allow(unused_variables)]
 				fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {
 					let result: #result = #name(#(#pass)*);
-					<_ as Typed>::into_result(result)
+					<_ as IntoUntypedResult>::into_untyped_result(result)
 				}
 				fn as_any(&self) -> &dyn ::std::any::Any {
 					self
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);