difftreelog
fix fully qualified struct paths in Either!
in: master
2 files changed
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth1use 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::{native::NativeDesc, FuncDesc, FuncVal},12 typed::CheckType,13 val::{IndexableVal, ThunkMapper},14 ObjValue, ObjValueBuilder, Result, 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}122123const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;124125macro_rules! impl_int {126 ($($ty:ty)*) => {$(127 impl Typed for $ty {128 const TYPE: &'static ComplexValType =129 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));130 fn from_untyped(value: Val) -> Result<Self> {131 <Self as Typed>::TYPE.check(&value)?;132 match value {133 Val::Num(n) => {134 #[allow(clippy::float_cmp)]135 if n.trunc() != n {136 bail!(137 "cannot convert number with fractional part to {}",138 stringify!($ty)139 )140 }141 Ok(n as Self)142 }143 _ => unreachable!(),144 }145 }146 fn into_untyped(value: Self) -> Result<Val> {147 Ok(Val::Num(value as f64))148 }149 }150 )*};151}152153impl_int!(i8 u8 i16 u16 i32 u32);154155macro_rules! impl_bounded_int {156 ($($name:ident = $ty:ty)*) => {$(157 #[derive(Clone, Copy)]158 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);159 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {160 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {161 if value >= MIN && value <= MAX {162 Some(Self(value))163 } else {164 None165 }166 }167 pub const fn value(self) -> $ty {168 self.0169 }170 }171 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {172 type Target = $ty;173 fn deref(&self) -> &Self::Target {174 &self.0175 }176 }177178 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {179 const TYPE: &'static ComplexValType =180 &ComplexValType::BoundedNumber(181 Some(MIN as f64),182 Some(MAX as f64),183 );184185 fn from_untyped(value: Val) -> Result<Self> {186 <Self as Typed>::TYPE.check(&value)?;187 match value {188 Val::Num(n) => {189 #[allow(clippy::float_cmp)]190 if n.trunc() != n {191 bail!(192 "cannot convert number with fractional part to {}",193 stringify!($ty)194 )195 }196 Ok(Self(n as $ty))197 }198 _ => unreachable!(),199 }200 }201202 fn into_untyped(value: Self) -> Result<Val> {203 Ok(Val::Num(value.0 as f64))204 }205 }206 )*};207}208209impl_bounded_int!(210 BoundedI8 = i8211 BoundedI16 = i16212 BoundedI32 = i32213 BoundedI64 = i64214 BoundedUsize = usize215);216217impl Typed for f64 {218 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);219220 fn into_untyped(value: Self) -> Result<Val> {221 Ok(Val::Num(value))222 }223224 fn from_untyped(value: Val) -> Result<Self> {225 <Self as Typed>::TYPE.check(&value)?;226 match value {227 Val::Num(n) => Ok(n),228 _ => unreachable!(),229 }230 }231}232233pub struct PositiveF64(pub f64);234impl Typed for PositiveF64 {235 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);236237 fn into_untyped(value: Self) -> Result<Val> {238 Ok(Val::Num(value.0))239 }240241 fn from_untyped(value: Val) -> Result<Self> {242 <Self as Typed>::TYPE.check(&value)?;243 match value {244 Val::Num(n) => Ok(Self(n)),245 _ => unreachable!(),246 }247 }248}249impl Typed for usize {250 const TYPE: &'static ComplexValType =251 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));252253 fn into_untyped(value: Self) -> Result<Val> {254 if value > MAX_SAFE_INTEGER as Self {255 bail!("number is too large")256 }257 Ok(Val::Num(value as f64))258 }259260 fn from_untyped(value: Val) -> Result<Self> {261 <Self as Typed>::TYPE.check(&value)?;262 match value {263 Val::Num(n) => {264 #[allow(clippy::float_cmp)]265 if n.trunc() != n {266 bail!("cannot convert number with fractional part to usize")267 }268 Ok(n as Self)269 }270 _ => unreachable!(),271 }272 }273}274275impl Typed for IStr {276 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);277278 fn into_untyped(value: Self) -> Result<Val> {279 Ok(Val::string(value))280 }281282 fn from_untyped(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Str(s) => Ok(s.into_flat()),286 _ => unreachable!(),287 }288 }289}290291impl Typed for String {292 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);293294 fn into_untyped(value: Self) -> Result<Val> {295 Ok(Val::string(value))296 }297298 fn from_untyped(value: Val) -> Result<Self> {299 <Self as Typed>::TYPE.check(&value)?;300 match value {301 Val::Str(s) => Ok(s.to_string()),302 _ => unreachable!(),303 }304 }305}306307impl Typed for char {308 const TYPE: &'static ComplexValType = &ComplexValType::Char;309310 fn into_untyped(value: Self) -> Result<Val> {311 Ok(Val::string(value))312 }313314 fn from_untyped(value: Val) -> Result<Self> {315 <Self as Typed>::TYPE.check(&value)?;316 match value {317 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),318 _ => unreachable!(),319 }320 }321}322323impl<T> Typed for Vec<T>324where325 T: Typed,326{327 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);328329 fn into_untyped(value: Self) -> Result<Val> {330 Ok(Val::Arr(331 value332 .into_iter()333 .map(T::into_untyped)334 .collect::<Result<ArrValue>>()?,335 ))336 }337338 fn from_untyped(value: Val) -> Result<Self> {339 let Val::Arr(a) = value else {340 <Self as Typed>::TYPE.check(&value)?;341 unreachable!("typecheck should fail")342 };343 a.iter()344 .map(|r| r.and_then(T::from_untyped))345 .collect::<Result<Vec<T>>>()346 }347}348349impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {350 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);351352 fn into_untyped(typed: Self) -> Result<Val> {353 let mut out = ObjValueBuilder::with_capacity(typed.len());354 for (k, v) in typed {355 let Some(key) = K::into_untyped(k)?.as_str() else {356 bail!("map key should serialize to string");357 };358 let value = V::into_untyped(v)?;359 out.field(key).value(value);360 }361 Ok(Val::Obj(out.build()))362 }363364 fn from_untyped(value: Val) -> Result<Self> {365 Self::TYPE.check(&value)?;366 let obj = value.as_obj().expect("typecheck should fail");367368 let mut out = BTreeMap::new();369 if V::wants_lazy() {370 for key in obj.fields_ex(371 false,372 #[cfg(feature = "exp-preserve-order")]373 false,374 ) {375 let value = obj.get_lazy(key.clone()).expect("field exists");376 let value = V::from_lazy_untyped(value)?;377 let key = K::from_untyped(Val::Str(key.into()))?;378 let _ = out.insert(key, value);379 }380 } else {381 for (key, value) in obj.iter(382 #[cfg(feature = "exp-preserve-order")]383 false,384 ) {385 let key = K::from_untyped(Val::Str(key.into()))?;386 let value = V::from_untyped(value?)?;387 let _ = out.insert(key, value);388 }389 }390 Ok(out)391 }392}393394impl Typed for Val {395 const TYPE: &'static ComplexValType = &ComplexValType::Any;396397 fn into_untyped(typed: Self) -> Result<Val> {398 Ok(typed)399 }400 fn from_untyped(untyped: Val) -> Result<Self> {401 Ok(untyped)402 }403}404405// Hack406#[doc(hidden)]407impl<T> Typed for Result<T>408where409 T: Typed,410{411 const TYPE: &'static ComplexValType = &ComplexValType::Any;412413 fn into_untyped(_typed: Self) -> Result<Val> {414 panic!("do not use this conversion")415 }416417 fn from_untyped(_untyped: Val) -> Result<Self> {418 panic!("do not use this conversion")419 }420421 fn into_result(typed: Self) -> Result<Val> {422 typed.map(T::into_untyped)?423 }424}425426/// Specialization427impl Typed for IBytes {428 const TYPE: &'static ComplexValType =429 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));430431 fn into_untyped(value: Self) -> Result<Val> {432 Ok(Val::Arr(ArrValue::bytes(value)))433 }434435 fn from_untyped(value: Val) -> Result<Self> {436 match &value {437 Val::Arr(a) => {438 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {439 return Ok(bytes.0.as_slice().into());440 };441 <Self as Typed>::TYPE.check(&value)?;442 // Any::downcast_ref::<ByteArray>(&a);443 let mut out = Vec::with_capacity(a.len());444 for e in a.iter() {445 let r = e?;446 out.push(u8::from_untyped(r)?);447 }448 Ok(out.as_slice().into())449 }450 _ => {451 <Self as Typed>::TYPE.check(&value)?;452 unreachable!()453 }454 }455 }456}457458pub struct M1;459impl Typed for M1 {460 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));461462 fn into_untyped(_: Self) -> Result<Val> {463 Ok(Val::Num(-1.0))464 }465466 fn from_untyped(value: Val) -> Result<Self> {467 <Self as Typed>::TYPE.check(&value)?;468 Ok(Self)469 }470}471472macro_rules! decl_either {473 ($($name: ident, $($id: ident)*);*) => {$(474 #[derive(Clone)]475 pub enum $name<$($id),*> {476 $($id($id)),*477 }478 impl<$($id),*> Typed for $name<$($id),*>479 where480 $($id: Typed,)*481 {482 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);483484 fn into_untyped(value: Self) -> Result<Val> {485 match value {$(486 $name::$id(v) => $id::into_untyped(v)487 ),*}488 }489490 fn from_untyped(value: Val) -> Result<Self> {491 $(492 if $id::TYPE.check(&value).is_ok() {493 $id::from_untyped(value).map(Self::$id)494 } else495 )* {496 <Self as Typed>::TYPE.check(&value)?;497 unreachable!()498 }499 }500 }501 )*}502}503decl_either!(504 Either1, A;505 Either2, A B;506 Either3, A B C;507 Either4, A B C D;508 Either5, A B C D E;509 Either6, A B C D E F;510 Either7, A B C D E F G511);512#[macro_export]513macro_rules! Either {514 ($a:ty) => {Either1<$a>};515 ($a:ty, $b:ty) => {Either2<$a, $b>};516 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};517 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};518 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};519 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};520 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};521}522pub use Either;523524pub type MyType = Either![u32, f64, String];525526impl Typed for ArrValue {527 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);528529 fn into_untyped(value: Self) -> Result<Val> {530 Ok(Val::Arr(value))531 }532533 fn from_untyped(value: Val) -> Result<Self> {534 <Self as Typed>::TYPE.check(&value)?;535 match value {536 Val::Arr(a) => Ok(a),537 _ => unreachable!(),538 }539 }540}541542impl Typed for FuncVal {543 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);544545 fn into_untyped(value: Self) -> Result<Val> {546 Ok(Val::Func(value))547 }548549 fn from_untyped(value: Val) -> Result<Self> {550 <Self as Typed>::TYPE.check(&value)?;551 match value {552 Val::Func(a) => Ok(a),553 _ => unreachable!(),554 }555 }556}557558impl Typed for Cc<FuncDesc> {559 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);560561 fn into_untyped(value: Self) -> Result<Val> {562 Ok(Val::Func(FuncVal::Normal(value)))563 }564565 fn from_untyped(value: Val) -> Result<Self> {566 <Self as Typed>::TYPE.check(&value)?;567 match value {568 Val::Func(FuncVal::Normal(desc)) => Ok(desc),569 Val::Func(_) => bail!("expected normal function, not builtin"),570 _ => unreachable!(),571 }572 }573}574575impl Typed for ObjValue {576 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);577578 fn into_untyped(value: Self) -> Result<Val> {579 Ok(Val::Obj(value))580 }581582 fn from_untyped(value: Val) -> Result<Self> {583 <Self as Typed>::TYPE.check(&value)?;584 match value {585 Val::Obj(a) => Ok(a),586 _ => unreachable!(),587 }588 }589}590591impl Typed for bool {592 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);593594 fn into_untyped(value: Self) -> Result<Val> {595 Ok(Val::Bool(value))596 }597598 fn from_untyped(value: Val) -> Result<Self> {599 <Self as Typed>::TYPE.check(&value)?;600 match value {601 Val::Bool(a) => Ok(a),602 _ => unreachable!(),603 }604 }605}606impl Typed for IndexableVal {607 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[608 &ComplexValType::Simple(ValType::Arr),609 &ComplexValType::Simple(ValType::Str),610 ]);611612 fn into_untyped(value: Self) -> Result<Val> {613 match value {614 IndexableVal::Str(s) => Ok(Val::string(s)),615 IndexableVal::Arr(a) => Ok(Val::Arr(a)),616 }617 }618619 fn from_untyped(value: Val) -> Result<Self> {620 <Self as Typed>::TYPE.check(&value)?;621 value.into_indexable()622 }623}624625pub struct Null;626impl Typed for Null {627 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);628629 fn into_untyped(_: Self) -> Result<Val> {630 Ok(Val::Null)631 }632633 fn from_untyped(value: Val) -> Result<Self> {634 <Self as Typed>::TYPE.check(&value)?;635 Ok(Self)636 }637}638639pub struct NativeFn<D: NativeDesc>(D::Value);640impl<D: NativeDesc> Deref for NativeFn<D> {641 type Target = D::Value;642643 fn deref(&self) -> &Self::Target {644 &self.0645 }646}647impl<D: NativeDesc> Typed for NativeFn<D> {648 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);649650 fn into_untyped(_typed: Self) -> Result<Val> {651 bail!("can only convert functions from jsonnet to native")652 }653654 fn from_untyped(untyped: Val) -> Result<Self> {655 Ok(Self(656 untyped657 .as_func()658 .expect("shape is checked")659 .into_native::<D>(),660 ))661 }662}crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -64,15 +64,7 @@
match &str {
Val::Str(s) => s.clone().into_flat(),
Val::Func(f) => format!("{f:?}").into(),
- v => v
- .manifest(JsonFormat::std_to_json(
- String::from(" "),
- "\n",
- ": ",
- #[cfg(feature = "exp-preserve-order")]
- true,
- ))?
- .into(),
+ v => v.manifest(JsonFormat::debug())?.into(),
},
);
if let Some(rest) = rest {