git.delta.rocks / jrsonnet / refs/commits / 364fdf96177a

difftreelog

perf inline trivial IntoUntyped

zpzozrxmYaroslav Bolyukin2026-04-25parent: #4944c9e.patch.diff
in: master

1 file changed

modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/typed/conversions.rs
1use std::{any::TypeId, collections::BTreeMap, marker::PhantomData, mem::transmute, ops::Deref};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,9	arr::ArrValue,10	bail,11	function::FuncVal,12	typed::CheckType,13	val::{IndexableVal, NumValue, StrValue, ThunkMapper},14};1516#[doc(hidden)]17pub mod __typed_macro_prelude {18	pub use ::jrsonnet_evaluator::{19		IStr, ObjValue, ObjValueBuilder, State, Val,20		error::{ErrorKind, Result as JrResult},21		typed::{22			CheckType, ComplexValType, FromUntyped, IntoUntyped, ParseTypedObj, SerializeTypedObj,23			Typed,24		},25	};26}27pub use jrsonnet_macros::{FromUntyped, IntoUntyped, Typed};2829#[derive(Trace)]30struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);31impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>32where33	K: Typed + FromUntyped + Trace,34{35	type Output = K;3637	fn map(self, from: Val) -> Result<Self::Output> {38		K::from_untyped(from)39	}40}41impl<K: Trace> Default for ThunkFromUntyped<K> {42	fn default() -> Self {43		Self(PhantomData)44	}45}46#[derive(Trace)]47struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);48impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>49where50	K: Typed + Trace + IntoUntyped,51{52	type Output = Val;5354	fn map(self, from: K) -> Result<Self::Output> {55		K::into_untyped(from)56	}57}58impl<K: Trace> Default for ThunkIntoUntyped<K> {59	fn default() -> Self {60		Self(PhantomData)61	}62}6364#[diagnostic::on_unimplemented(65	note = "don't implement `ParseTypedObj` directly, it is automatically provided by `FromUntyped` derive"66)]67pub trait ParseTypedObj: Typed {68	fn parse(obj: &ObjValue) -> Result<Self>;69}7071#[diagnostic::on_unimplemented(72	note = "don't implement `SerializeTypedObj` directly, it is automatically provided by `IntoUntyped` derive"73)]74pub trait SerializeTypedObj: Typed {75	fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;76	fn into_object(self) -> Result<ObjValue> {77		let mut builder = ObjValueBuilder::new();78		self.serialize(&mut builder)?;79		Ok(builder.build())80	}81}8283pub trait Typed: Sized {84	const TYPE: &'static ComplexValType;85}86impl<T> Typed for &T87where88	T: Typed,89{90	const TYPE: &'static ComplexValType = <&T as Typed>::TYPE;91}92pub trait IntoUntyped: Typed {93	// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`94	fn provides_lazy() -> bool {95		false96	}97	fn into_untyped(typed: Self) -> Result<Val>;98	fn into_lazy_untyped(typed: Self) -> Thunk<Val> {99		Thunk::from(Self::into_untyped(typed))100	}101}102103pub trait IntoUntypedResult: Typed {104	/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result105	/// This method returns identity in impl Typed for Result, and should not be overriden106	#[doc(hidden)]107	fn into_untyped_result(typed: Self) -> Result<Val>;108}109impl<T> IntoUntypedResult for T110where111	T: IntoUntyped,112{113	fn into_untyped_result(typed: Self) -> Result<Val> {114		T::into_untyped(typed)115	}116}117118pub trait FromUntyped: Typed {119	fn from_untyped(untyped: Val) -> Result<Self>;120	fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {121		Self::from_untyped(lazy.evaluate()?)122	}123124	// Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible125	fn wants_lazy() -> bool {126		false127	}128}129130impl<T> Typed for Thunk<T>131where132	T: Typed + Trace + Clone,133{134	const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);135}136137fn try_cast_thunk_val<T: 'static>(typed: Thunk<T>) -> Result<Thunk<Val>, Thunk<T>> {138	if TypeId::of::<T>() == TypeId::of::<Val>() {139		// SAFETY: We know that it is exactly the same type, and we discard the original after that140		// to avoid double-free.141		let transmuted = unsafe { transmute::<Thunk<T>, Thunk<Val>>(typed) };142		Ok(transmuted)143	} else {144		Err(typed)145	}146}147impl<T> IntoUntyped for Thunk<T>148where149	T: IntoUntyped + Trace + Clone,150{151	fn into_untyped(typed: Self) -> Result<Val> {152		T::into_untyped(typed.evaluate()?)153	}154	fn provides_lazy() -> bool {155		true156	}157158	fn into_lazy_untyped(inner: Self) -> Thunk<Val> {159		// Avoid lazy mapping160		let inner = match try_cast_thunk_val(inner) {161			Ok(v) => return v,162			Err(e) => e,163		};164		inner.map(<ThunkIntoUntyped<T>>::default())165	}166}167impl<T> IntoUntyped for &Thunk<T>168where169	T: IntoUntyped + Trace + Clone,170{171	fn into_untyped(typed: Self) -> Result<Val> {172		T::into_untyped(typed.evaluate()?)173	}174	fn provides_lazy() -> bool {175		true176	}177178	fn into_lazy_untyped(inner: Self) -> Thunk<Val> {179		// Avoid lazy mapping180		let inner = match try_cast_thunk_val(inner.clone()) {181			Ok(v) => return v,182			Err(e) => e,183		};184		inner.map(<ThunkIntoUntyped<T>>::default())185	}186}187188fn try_cast_thunk_t<T: 'static>(typed: Thunk<Val>) -> Result<Thunk<T>, Thunk<Val>> {189	if TypeId::of::<T>() == TypeId::of::<Val>() {190		// SAFETY: We know that it is exactly the same type, and we discard the original after that191		// to avoid double-free.192		let transmuted = unsafe { transmute::<Thunk<Val>, Thunk<T>>(typed) };193		Ok(transmuted)194	} else {195		Err(typed)196	}197}198impl<T> FromUntyped for Thunk<T>199where200	T: Typed + FromUntyped + Trace + Clone,201{202	fn from_untyped(untyped: Val) -> Result<Self> {203		Self::from_lazy_untyped(Thunk::evaluated(untyped))204	}205206	fn wants_lazy() -> bool {207		true208	}209210	fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {211		// Avoid lazy mapping212		let inner = match try_cast_thunk_t(inner) {213			Ok(v) => return Ok(v),214			Err(e) => e,215		};216		Ok(inner.map(<ThunkFromUntyped<T>>::default()))217	}218}219220#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]221pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;222#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]223pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;224225macro_rules! impl_int {226	($($ty:ty)*) => {$(227		impl Typed for $ty {228			const TYPE: &'static ComplexValType =229				&ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));230		}231		impl FromUntyped for $ty {232			fn from_untyped(value: Val) -> Result<Self> {233				<Self as Typed>::TYPE.check(&value)?;234				match value {235					Val::Num(n) => {236						let n = n.get();237						#[allow(clippy::float_cmp)]238						if n.trunc() != n {239							bail!(240								"cannot convert number with fractional part to {}",241								stringify!($ty)242							)243						}244						#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation, reason = "checked by TYPE")]245						Ok(n as Self)246					}247					_ => unreachable!(),248				}249			}250		}251		impl IntoUntyped for &$ty {252			fn into_untyped(value: Self) -> Result<Val> {253				Ok(Val::Num((*value).into()))254			}255		}256		impl IntoUntyped for $ty {257			fn into_untyped(value: Self) -> Result<Val> {258				Ok(Val::Num(value.into()))259			}260		}261	)*};262}263264impl_int!(i8 u8 i16 u16 i32 u32);265266macro_rules! impl_bounded_int {267	($($name:ident = $ty:ty)*) => {$(268		#[derive(Clone, Copy)]269		#[allow(clippy::cast_possible_truncation, reason = "overflow is api misuse")]270		pub struct $name<const MIN: $ty, const MAX: $ty>($ty);271		impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {272			pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {273				if value >= MIN && value <= MAX {274					Some(Self(value))275				} else {276					None277				}278			}279			pub const fn value(self) -> $ty {280				self.0281			}282		}283		impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {284			type Target = $ty;285			fn deref(&self) -> &Self::Target {286				&self.0287			}288		}289290		impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {291			#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss, reason = "overflow is api misuse")]292			const TYPE: &'static ComplexValType =293				&ComplexValType::BoundedNumber(294					Some(MIN as f64),295					Some(MAX as f64),296				);297		}298299		impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {300			fn from_untyped(value: Val) -> Result<Self> {301				<Self as Typed>::TYPE.check(&value)?;302				match value {303					Val::Num(n) => {304						let n = n.get();305						#[allow(clippy::float_cmp)]306						if n.trunc() != n {307							bail!(308								"cannot convert number with fractional part to {}",309								stringify!($ty)310							)311						}312						#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "overflow is api misuse, the range is checked by TYPE")]313						Ok(Self(n as $ty))314					}315					_ => unreachable!(),316				}317			}318		}319320		impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {321			#[allow(clippy::cast_lossless)]322			fn into_untyped(value: Self) -> Result<Val> {323				Ok(Val::try_num(value.0)?)324			}325		}326	)*};327}328329impl_bounded_int!(330	BoundedI8 = i8331	BoundedI16 = i16332	BoundedI32 = i32333	BoundedI64 = i64334	BoundedUsize = usize335);336337impl Typed for f64 {338	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);339}340impl IntoUntyped for &f64 {341	fn into_untyped(value: Self) -> Result<Val> {342		Ok(Val::try_num(*value)?)343	}344}345impl IntoUntyped for f64 {346	fn into_untyped(value: Self) -> Result<Val> {347		Ok(Val::try_num(value)?)348	}349}350impl FromUntyped for f64 {351	fn from_untyped(value: Val) -> Result<Self> {352		<Self as Typed>::TYPE.check(&value)?;353		match value {354			Val::Num(n) => Ok(n.get()),355			_ => unreachable!(),356		}357	}358}359360pub struct PositiveF64(pub f64);361impl Typed for PositiveF64 {362	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);363}364impl IntoUntyped for &PositiveF64 {365	fn into_untyped(value: Self) -> Result<Val> {366		Ok(Val::try_num(value.0)?)367	}368}369impl FromUntyped for PositiveF64 {370	fn from_untyped(value: Val) -> Result<Self> {371		<Self as Typed>::TYPE.check(&value)?;372		match value {373			Val::Num(n) => Ok(Self(n.get())),374			_ => unreachable!(),375		}376	}377}378impl Typed for usize {379	const TYPE: &'static ComplexValType =380		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));381}382impl IntoUntyped for usize {383	fn into_untyped(value: Self) -> Result<Val> {384		Ok(Val::try_num(value)?)385	}386}387impl FromUntyped for usize {388	fn from_untyped(value: Val) -> Result<Self> {389		<Self as Typed>::TYPE.check(&value)?;390		match value {391			Val::Num(n) => {392				let n = n.get();393				#[allow(clippy::float_cmp)]394				if n.trunc() != n {395					bail!("cannot convert number with fractional part to usize")396				}397				#[allow(398					clippy::cast_possible_truncation,399					clippy::cast_sign_loss,400					reason = "the range is checked by TYPE"401				)]402				Ok(n as Self)403			}404			_ => unreachable!(),405		}406	}407}408409impl Typed for IStr {410	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);411}412impl IntoUntyped for IStr {413	fn into_untyped(value: Self) -> Result<Val> {414		Ok(Val::string(value))415	}416}417impl FromUntyped for IStr {418	fn from_untyped(value: Val) -> Result<Self> {419		<Self as Typed>::TYPE.check(&value)?;420		match value {421			Val::Str(s) => Ok(s.into_flat()),422			_ => unreachable!(),423		}424	}425}426427impl Typed for String {428	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);429}430impl IntoUntyped for String {431	fn into_untyped(value: Self) -> Result<Val> {432		Ok(Val::string(value))433	}434}435impl FromUntyped for String {436	fn from_untyped(value: Val) -> Result<Self> {437		<Self as Typed>::TYPE.check(&value)?;438		match value {439			Val::Str(s) => Ok(s.to_string()),440			_ => unreachable!(),441		}442	}443}444445impl Typed for StrValue {446	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);447}448impl IntoUntyped for StrValue {449	fn into_untyped(value: Self) -> Result<Val> {450		Ok(Val::Str(value))451	}452}453impl FromUntyped for StrValue {454	fn from_untyped(value: Val) -> Result<Self> {455		<Self as Typed>::TYPE.check(&value)?;456		match value {457			Val::Str(s) => Ok(s),458			_ => unreachable!(),459		}460	}461}462463impl Typed for char {464	const TYPE: &'static ComplexValType = &ComplexValType::Char;465}466impl IntoUntyped for &char {467	fn into_untyped(value: Self) -> Result<Val> {468		Ok(Val::string(*value))469	}470}471impl IntoUntyped for char {472	fn into_untyped(value: Self) -> Result<Val> {473		Ok(Val::string(value))474	}475}476impl FromUntyped for char {477	fn from_untyped(value: Val) -> Result<Self> {478		<Self as Typed>::TYPE.check(&value)?;479		match value {480			Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),481			_ => unreachable!(),482		}483	}484}485486// TODO: View into vec using ArrayLike?487impl<T> Typed for Vec<T>488where489	T: Typed,490{491	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);492}493impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {494	fn into_untyped(value: Self) -> Result<Val> {495		Ok(Val::Arr(496			value497				.into_iter()498				.map(T::into_untyped)499				.collect::<Result<ArrValue>>()?,500		))501	}502}503impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {504	fn from_untyped(value: Val) -> Result<Self> {505		let Val::Arr(a) = value else {506			<Self as Typed>::TYPE.check(&value)?;507			unreachable!("typecheck should fail")508		};509		a.iter()510			.enumerate()511			.map(|(i, r)| {512				r.and_then(|t| {513					T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))514				})515			})516			.collect::<Result<Self>>()517	}518}519520// TODO: View into BTreeMap using ObjectCore?521impl<K, V> Typed for BTreeMap<K, V>522where523	K: Typed + Ord,524	V: Typed,525{526	const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);527}528impl<K, V> IntoUntyped for BTreeMap<K, V>529where530	K: Typed + Ord + IntoUntyped,531	V: Typed + IntoUntyped,532{533	fn into_untyped(typed: Self) -> Result<Val> {534		let mut out = ObjValueBuilder::with_capacity(typed.len());535		for (k, v) in typed {536			let Some(key) = K::into_untyped(k)?.as_str() else {537				bail!("map key should serialize to string");538			};539			let value = V::into_untyped(v)?;540			out.field(key).value(value);541		}542		Ok(Val::Obj(out.build()))543	}544}545impl<K, V> FromUntyped for BTreeMap<K, V>546where547	K: FromUntyped + Ord,548	V: FromUntyped,549{550	fn from_untyped(value: Val) -> Result<Self> {551		Self::TYPE.check(&value)?;552		let obj = value.as_obj().expect("typecheck should fail");553554		let mut out = Self::new();555		if V::wants_lazy() {556			for key in obj.fields_ex(557				false,558				#[cfg(feature = "exp-preserve-order")]559				false,560			) {561				let value = obj.get_lazy(key.clone()).expect("field exists");562				let value = V::from_lazy_untyped(value)?;563				let key = K::from_untyped(Val::Str(key.into()))?;564				let _ = out.insert(key, value);565			}566		} else {567			for (key, value) in obj.iter(568				#[cfg(feature = "exp-preserve-order")]569				false,570			) {571				let key = K::from_untyped(Val::Str(key.into()))?;572				let value = V::from_untyped(value?)?;573				let _ = out.insert(key, value);574			}575		}576		Ok(out)577	}578}579580impl Typed for Val {581	const TYPE: &'static ComplexValType = &ComplexValType::Any;582}583impl IntoUntyped for &Val {584	fn into_untyped(typed: Self) -> Result<Val> {585		Ok(typed.clone())586	}587}588impl IntoUntyped for Val {589	fn into_untyped(typed: Self) -> Result<Val> {590		Ok(typed)591	}592}593impl FromUntyped for Val {594	fn from_untyped(untyped: Val) -> Result<Self> {595		Ok(untyped)596	}597}598599#[doc(hidden)]600impl<T> Typed for Result<T>601where602	T: Typed,603{604	const TYPE: &'static ComplexValType = &ComplexValType::Any;605}606impl<T: IntoUntyped> IntoUntypedResult for Result<T> {607	fn into_untyped_result(typed: Self) -> Result<Val> {608		typed.map(T::into_untyped)?609	}610}611612/// Specialization613impl Typed for IBytes {614	const TYPE: &'static ComplexValType =615		&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));616}617impl IntoUntyped for &IBytes {618	fn into_untyped(value: Self) -> Result<Val> {619		Ok(Val::arr(value.clone()))620	}621}622impl IntoUntyped for IBytes {623	fn into_untyped(value: Self) -> Result<Val> {624		Ok(Val::arr(value))625	}626}627impl FromUntyped for IBytes {628	fn from_untyped(value: Val) -> Result<Self> {629		let Val::Arr(a) = &value else {630			<Self as Typed>::TYPE.check(&value)?;631			unreachable!()632		};633		if let Some(bytes) = a.as_any().downcast_ref::<IBytes>() {634			return Ok(bytes.clone());635		}636		<Self as Typed>::TYPE.check(&value)?;637		// Any::downcast_ref::<ByteArray>(&a);638		let mut out = Vec::with_capacity(a.len());639		for e in a.iter() {640			let r = e?;641			out.push(u8::from_untyped(r)?);642		}643		Ok(out.as_slice().into())644	}645}646647pub struct M1;648impl Typed for M1 {649	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));650}651impl IntoUntyped for &M1 {652	fn into_untyped(_: Self) -> Result<Val> {653		Ok(Val::Num(NumValue::new(-1.0).expect("finite")))654	}655}656impl FromUntyped for M1 {657	fn from_untyped(value: Val) -> Result<Self> {658		<Self as Typed>::TYPE.check(&value)?;659		Ok(Self)660	}661}662663macro_rules! decl_either {664	($($name: ident, $($id: ident)*);*) => {$(665		#[derive(Clone)]666		pub enum $name<$($id),*> {667			$($id($id)),*668		}669		impl<$($id),*> Typed for $name<$($id),*>670		where671			$($id: Typed,)*672		{673			const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);674		}675		impl<$($id),*> IntoUntyped for $name<$($id),*>676		where677			$($id: Typed + IntoUntyped,)*678		{679			fn into_untyped(value: Self) -> Result<Val> {680				match value {$(681					$name::$id(v) => $id::into_untyped(v)682				),*}683			}684		}685686		impl<$($id),*> FromUntyped for $name<$($id),*>687		where688			$($id: Typed + FromUntyped,)*689		{690			fn from_untyped(value: Val) -> Result<Self> {691				$(692					if $id::TYPE.check(&value).is_ok() {693						$id::from_untyped(value).map(Self::$id)694					} else695				)* {696					<Self as Typed>::TYPE.check(&value)?;697					unreachable!()698				}699			}700		}701	)*}702}703decl_either!(704	Either1, A;705	Either2, A B;706	Either3, A B C;707	Either4, A B C D;708	Either5, A B C D E;709	Either6, A B C D E F;710	Either7, A B C D E F G711);712#[macro_export]713macro_rules! Either {714	($a:ty) => {$crate::typed::Either1<$a>};715	($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};716	($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};717	($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};718	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};719	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};720	($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};721}722pub use Either;723724pub type MyType = Either![u32, f64, String];725726impl Typed for ArrValue {727	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);728}729impl IntoUntyped for ArrValue {730	fn into_untyped(value: Self) -> Result<Val> {731		Ok(Val::Arr(value))732	}733}734impl FromUntyped for ArrValue {735	fn from_untyped(value: Val) -> Result<Self> {736		<Self as Typed>::TYPE.check(&value)?;737		match value {738			Val::Arr(a) => Ok(a),739			_ => unreachable!(),740		}741	}742}743744impl Typed for FuncVal {745	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);746}747impl IntoUntyped for FuncVal {748	fn into_untyped(value: Self) -> Result<Val> {749		Ok(Val::Func(value))750	}751}752impl FromUntyped for FuncVal {753	fn from_untyped(value: Val) -> Result<Self> {754		<Self as Typed>::TYPE.check(&value)?;755		match value {756			Val::Func(a) => Ok(a),757			_ => unreachable!(),758		}759	}760}761762impl Typed for ObjValue {763	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);764}765impl IntoUntyped for ObjValue {766	fn into_untyped(value: Self) -> Result<Val> {767		Ok(Val::Obj(value))768	}769}770impl FromUntyped for ObjValue {771	fn from_untyped(value: Val) -> Result<Self> {772		<Self as Typed>::TYPE.check(&value)?;773		match value {774			Val::Obj(a) => Ok(a),775			_ => unreachable!(),776		}777	}778}779780impl Typed for bool {781	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);782}783impl IntoUntyped for &bool {784	fn into_untyped(value: Self) -> Result<Val> {785		Ok(Val::Bool(*value))786	}787}788impl IntoUntyped for bool {789	fn into_untyped(value: Self) -> Result<Val> {790		Ok(Val::Bool(value))791	}792}793impl FromUntyped for bool {794	fn from_untyped(value: Val) -> Result<Self> {795		<Self as Typed>::TYPE.check(&value)?;796		match value {797			Val::Bool(a) => Ok(a),798			_ => unreachable!(),799		}800	}801}802803impl Typed for IndexableVal {804	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[805		&ComplexValType::Simple(ValType::Arr),806		&ComplexValType::Simple(ValType::Str),807	]);808}809impl IntoUntyped for IndexableVal {810	fn into_untyped(value: Self) -> Result<Val> {811		match value {812			Self::Str(s) => Ok(Val::string(s)),813			Self::Arr(a) => Ok(Val::Arr(a)),814		}815	}816}817impl FromUntyped for IndexableVal {818	fn from_untyped(value: Val) -> Result<Self> {819		<Self as Typed>::TYPE.check(&value)?;820		value.into_indexable()821	}822}823824impl Typed for () {825	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);826}827impl IntoUntyped for &() {828	fn into_untyped((): Self) -> Result<Val> {829		Ok(Val::Null)830	}831}832impl IntoUntyped for () {833	fn into_untyped((): Self) -> Result<Val> {834		Ok(Val::Null)835	}836}837impl FromUntyped for () {838	fn from_untyped(value: Val) -> Result<Self> {839		<Self as Typed>::TYPE.check(&value)?;840		Ok(())841	}842}843844impl<T> Typed for Option<T>845where846	T: Typed,847{848	const TYPE: &'static ComplexValType =849		&ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);850}851impl<T> IntoUntyped for Option<T>852where853	T: Typed + IntoUntyped,854{855	fn into_untyped(typed: Self) -> Result<Val> {856		typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))857	}858}859impl<T> FromUntyped for Option<T>860where861	T: Typed + FromUntyped,862{863	fn from_untyped(untyped: Val) -> Result<Self> {864		if matches!(untyped, Val::Null) {865			Ok(None)866		} else {867			T::from_untyped(untyped).map(Some)868		}869	}870}871872impl Typed for NumValue {873	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);874}875impl IntoUntyped for &NumValue {876	fn into_untyped(typed: Self) -> Result<Val> {877		Ok(Val::Num(*typed))878	}879}880impl FromUntyped for NumValue {881	fn from_untyped(untyped: Val) -> Result<Self> {882		Self::TYPE.check(&untyped)?;883		match untyped {884			Val::Num(v) => Ok(v),885			_ => unreachable!(),886		}887	}888}