difftreelog
feat rename/flatten field in derive(Typed)
in: master
4 files changed
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1280,7 +1280,8 @@
#[derive(Typed, PartialEq, Debug)]
struct MyTyped {
a: u32,
- b: String,
+ #[typed(rename = "b")]
+ c: String,
}
#[test]
@@ -1293,7 +1294,7 @@
typed,
MyTyped {
a: 14,
- b: "Hello, world!".to_string()
+ c: "Hello, world!".to_string()
}
);
es.settings_mut().globals.insert(
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth1use std::convert::{TryFrom, TryInto};23use jrsonnet_interner::IStr;4pub use jrsonnet_macros::Typed;5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8 error::{Error::*, LocError, Result},9 throw,10 typed::CheckType,11 ArrValue, FuncVal, IndexableVal, ObjValue, Val,12};1314pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {15 const TYPE: &'static ComplexValType;16}1718macro_rules! impl_int {19 ($($ty:ty)*) => {$(20 impl Typed for $ty {21 const TYPE: &'static ComplexValType =22 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));23 }24 impl TryFrom<Val> for $ty {25 type Error = LocError;2627 fn try_from(value: Val) -> Result<Self> {28 <Self as Typed>::TYPE.check(&value)?;29 match value {30 Val::Num(n) => {31 if n.trunc() != n {32 throw!(RuntimeError(33 format!(34 "cannot convert number with fractional part to {}",35 stringify!($ty)36 )37 .into()38 ))39 }40 Ok(n as Self)41 }42 _ => unreachable!(),43 }44 }45 }46 impl TryFrom<$ty> for Val {47 type Error = LocError;4849 fn try_from(value: $ty) -> Result<Self> {50 Ok(Self::Num(value as f64))51 }52 }53 )*};54}5556impl_int!(i8 u8 i16 u16 i32 u32);5758impl Typed for f64 {59 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);60}61impl TryFrom<Val> for f64 {62 type Error = LocError;6364 fn try_from(value: Val) -> Result<Self> {65 <Self as Typed>::TYPE.check(&value)?;66 match value {67 Val::Num(n) => Ok(n),68 _ => unreachable!(),69 }70 }71}72impl TryFrom<f64> for Val {73 type Error = LocError;7475 fn try_from(value: f64) -> Result<Self> {76 Ok(Self::Num(value))77 }78}7980pub struct PositiveF64(pub f64);81impl Typed for PositiveF64 {82 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);83}84impl TryFrom<Val> for PositiveF64 {85 type Error = LocError;8687 fn try_from(value: Val) -> Result<Self> {88 <Self as Typed>::TYPE.check(&value)?;89 match value {90 Val::Num(n) => Ok(Self(n)),91 _ => unreachable!(),92 }93 }94}95impl TryFrom<PositiveF64> for Val {96 type Error = LocError;9798 fn try_from(value: PositiveF64) -> Result<Self> {99 Ok(Self::Num(value.0))100 }101}102103impl Typed for usize {104 // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility105 const TYPE: &'static ComplexValType =106 &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));107}108impl TryFrom<Val> for usize {109 type Error = LocError;110111 fn try_from(value: Val) -> Result<Self> {112 <Self as Typed>::TYPE.check(&value)?;113 match value {114 Val::Num(n) => {115 if n.trunc() != n {116 throw!(RuntimeError(117 "cannot convert number with fractional part to usize".into()118 ))119 }120 Ok(n as Self)121 }122 _ => unreachable!(),123 }124 }125}126impl TryFrom<usize> for Val {127 type Error = LocError;128129 fn try_from(value: usize) -> Result<Self> {130 if value > u32::MAX as usize {131 throw!(RuntimeError("number is too large".into()))132 }133 Ok(Self::Num(value as f64))134 }135}136137impl Typed for IStr {138 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);139}140impl TryFrom<Val> for IStr {141 type Error = LocError;142143 fn try_from(value: Val) -> Result<Self> {144 <Self as Typed>::TYPE.check(&value)?;145 match value {146 Val::Str(s) => Ok(s),147 _ => unreachable!(),148 }149 }150}151impl TryFrom<IStr> for Val {152 type Error = LocError;153154 fn try_from(value: IStr) -> Result<Self> {155 Ok(Self::Str(value))156 }157}158159impl Typed for String {160 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);161}162impl TryFrom<Val> for String {163 type Error = LocError;164165 fn try_from(value: Val) -> Result<Self> {166 <Self as Typed>::TYPE.check(&value)?;167 match value {168 Val::Str(s) => Ok(s.to_string()),169 _ => unreachable!(),170 }171 }172}173impl TryFrom<String> for Val {174 type Error = LocError;175176 fn try_from(value: String) -> Result<Self> {177 Ok(Self::Str(value.into()))178 }179}180181impl Typed for char {182 const TYPE: &'static ComplexValType = &ComplexValType::Char;183}184impl TryFrom<Val> for char {185 type Error = LocError;186187 fn try_from(value: Val) -> Result<Self> {188 <Self as Typed>::TYPE.check(&value)?;189 match value {190 Val::Str(s) => Ok(s.chars().next().unwrap()),191 _ => unreachable!(),192 }193 }194}195impl TryFrom<char> for Val {196 type Error = LocError;197198 fn try_from(value: char) -> Result<Self> {199 Ok(Self::Str(value.to_string().into()))200 }201}202203impl<T> Typed for Vec<T>204where205 T: Typed,206 T: TryFrom<Val, Error = LocError>,207 T: TryInto<Val, Error = LocError>,208{209 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);210}211impl<T> TryFrom<Val> for Vec<T>212where213 T: Typed,214 T: TryFrom<Val, Error = LocError>,215 T: TryInto<Val, Error = LocError>,216{217 type Error = LocError;218219 fn try_from(value: Val) -> Result<Self> {220 <Self as Typed>::TYPE.check(&value)?;221 match value {222 Val::Arr(a) => {223 let mut o = Self::with_capacity(a.len());224 for i in a.iter() {225 o.push(T::try_from(i?)?);226 }227 Ok(o)228 }229 _ => unreachable!(),230 }231 }232}233impl<T> TryFrom<Vec<T>> for Val234where235 T: Typed,236 T: TryFrom<Self, Error = LocError>,237 T: TryInto<Self, Error = LocError>,238{239 type Error = LocError;240241 fn try_from(value: Vec<T>) -> Result<Self> {242 let mut o = Vec::with_capacity(value.len());243 for i in value {244 o.push(i.try_into()?);245 }246 Ok(Self::Arr(o.into()))247 }248}249250/// To be used in Vec<Any>251/// Regular Val can't be used here, because it has wrong TryFrom::Error type252#[derive(Clone)]253pub struct Any(pub Val);254255impl Typed for Any {256 const TYPE: &'static ComplexValType = &ComplexValType::Any;257}258impl TryFrom<Val> for Any {259 type Error = LocError;260261 fn try_from(value: Val) -> Result<Self> {262 Ok(Self(value))263 }264}265impl TryFrom<Any> for Val {266 type Error = LocError;267268 fn try_from(value: Any) -> Result<Self> {269 Ok(value.0)270 }271}272273/// Specialization, provides faster TryFrom<VecVal> for Val274pub struct VecVal(pub Vec<Val>);275276impl Typed for VecVal {277 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);278}279impl TryFrom<Val> for VecVal {280 type Error = LocError;281282 fn try_from(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),286 _ => unreachable!(),287 }288 }289}290impl TryFrom<VecVal> for Val {291 type Error = LocError;292293 fn try_from(value: VecVal) -> Result<Self> {294 Ok(Self::Arr(value.0.into()))295 }296}297298pub struct M1;299impl Typed for M1 {300 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));301}302impl TryFrom<Val> for M1 {303 type Error = LocError;304305 fn try_from(value: Val) -> Result<Self> {306 <Self as Typed>::TYPE.check(&value)?;307 Ok(Self)308 }309}310impl TryFrom<M1> for Val {311 type Error = LocError;312313 fn try_from(_: M1) -> Result<Self> {314 Ok(Self::Num(-1.0))315 }316}317318macro_rules! decl_either {319 ($($name: ident, $($id: ident)*);*) => {$(320 pub enum $name<$($id),*> {321 $($id($id)),*322 }323 impl<$($id),*> Typed for $name<$($id),*>324 where325 $($id: Typed,)*326 {327 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);328 }329 impl<$($id),*> TryFrom<Val> for $name<$($id),*>330 where331 $($id: Typed,)*332 {333 type Error = LocError;334335 fn try_from(value: Val) -> Result<Self> {336 $(337 if $id::TYPE.check(&value).is_ok() {338 $id::try_from(value).map(Self::$id)339 } else340 )* {341 <Self as Typed>::TYPE.check(&value)?;342 unreachable!()343 }344 }345 }346 impl<$($id),*> TryFrom<$name<$($id),*>> for Val347 where348 $($id: Typed,)*349 {350 type Error = LocError;351 fn try_from(value: $name<$($id),*>) -> Result<Self> {352 match value {$(353 $name::$id(v) => v.try_into()354 ),*}355 }356 }357 )*}358}359decl_either!(360 Either1, A;361 Either2, A B;362 Either3, A B C;363 Either4, A B C D;364 Either5, A B C D E;365 Either6, A B C D E F;366 Either7, A B C D E F G367);368#[macro_export]369macro_rules! Either {370 ($a:ty) => {Either1<$a>};371 ($a:ty, $b:ty) => {Either2<$a, $b>};372 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};373 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};374 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};375 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};376 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};377}378379pub type MyType = Either![u32, f64, String];380381impl Typed for ArrValue {382 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);383}384impl TryFrom<Val> for ArrValue {385 type Error = LocError;386387 fn try_from(value: Val) -> Result<Self> {388 <Self as Typed>::TYPE.check(&value)?;389 match value {390 Val::Arr(a) => Ok(a),391 _ => unreachable!(),392 }393 }394}395impl TryFrom<ArrValue> for Val {396 type Error = LocError;397398 fn try_from(value: ArrValue) -> Result<Self> {399 Ok(Self::Arr(value))400 }401}402403impl Typed for FuncVal {404 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);405}406impl TryFrom<Val> for FuncVal {407 type Error = LocError;408409 fn try_from(value: Val) -> Result<Self> {410 <Self as Typed>::TYPE.check(&value)?;411 match value {412 Val::Func(a) => Ok(a),413 _ => unreachable!(),414 }415 }416}417impl TryFrom<FuncVal> for Val {418 type Error = LocError;419420 fn try_from(value: FuncVal) -> Result<Self> {421 Ok(Self::Func(value))422 }423}424impl Typed for ObjValue {425 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);426}427impl TryFrom<Val> for ObjValue {428 type Error = LocError;429430 fn try_from(value: Val) -> Result<Self> {431 <Self as Typed>::TYPE.check(&value)?;432 match value {433 Val::Obj(a) => Ok(a),434 _ => unreachable!(),435 }436 }437}438impl TryFrom<ObjValue> for Val {439 type Error = LocError;440441 fn try_from(value: ObjValue) -> Result<Self> {442 Ok(Self::Obj(value))443 }444}445446impl Typed for bool {447 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);448}449impl TryFrom<Val> for bool {450 type Error = LocError;451452 fn try_from(value: Val) -> Result<Self> {453 <Self as Typed>::TYPE.check(&value)?;454 match value {455 Val::Bool(a) => Ok(a),456 _ => unreachable!(),457 }458 }459}460impl TryFrom<bool> for Val {461 type Error = LocError;462463 fn try_from(value: bool) -> Result<Self> {464 Ok(Self::Bool(value))465 }466}467468impl Typed for IndexableVal {469 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[470 &ComplexValType::Simple(ValType::Arr),471 &ComplexValType::Simple(ValType::Str),472 ]);473}474impl TryFrom<Val> for IndexableVal {475 type Error = LocError;476477 fn try_from(value: Val) -> Result<Self> {478 <Self as Typed>::TYPE.check(&value)?;479 value.into_indexable()480 }481}482impl TryFrom<IndexableVal> for Val {483 type Error = LocError;484485 fn try_from(value: IndexableVal) -> Result<Self> {486 match value {487 IndexableVal::Str(s) => Ok(Self::Str(s)),488 IndexableVal::Arr(a) => Ok(Self::Arr(a)),489 }490 }491}492493pub struct Null;494impl Typed for Null {495 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);496}497impl TryFrom<Val> for Null {498 type Error = LocError;499500 fn try_from(value: Val) -> Result<Self> {501 <Self as Typed>::TYPE.check(&value)?;502 Ok(Self)503 }504}505impl TryFrom<Null> for Val {506 type Error = LocError;507508 fn try_from(_: Null) -> Result<Self> {509 Ok(Self::Null)510 }511}1use std::convert::{TryFrom, TryInto};23use jrsonnet_interner::IStr;4pub use jrsonnet_macros::Typed;5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8 error::{Error::*, LocError, Result},9 throw,10 typed::CheckType,11 ArrValue, FuncVal, IndexableVal, ObjValue, ObjValueBuilder, Val,12};1314pub trait TypedObj: Typed {15 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;16 fn parse(obj: &ObjValue) -> Result<Self>;17 fn into_object(self) -> Result<ObjValue> {18 let mut builder = ObjValueBuilder::new();19 self.serialize(&mut builder)?;20 Ok(builder.build())21 }22}2324pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {25 const TYPE: &'static ComplexValType;26}2728macro_rules! impl_int {29 ($($ty:ty)*) => {$(30 impl Typed for $ty {31 const TYPE: &'static ComplexValType =32 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));33 }34 impl TryFrom<Val> for $ty {35 type Error = LocError;3637 fn try_from(value: Val) -> Result<Self> {38 <Self as Typed>::TYPE.check(&value)?;39 match value {40 Val::Num(n) => {41 if n.trunc() != n {42 throw!(RuntimeError(43 format!(44 "cannot convert number with fractional part to {}",45 stringify!($ty)46 )47 .into()48 ))49 }50 Ok(n as Self)51 }52 _ => unreachable!(),53 }54 }55 }56 impl TryFrom<$ty> for Val {57 type Error = LocError;5859 fn try_from(value: $ty) -> Result<Self> {60 Ok(Self::Num(value as f64))61 }62 }63 )*};64}6566impl_int!(i8 u8 i16 u16 i32 u32);6768impl Typed for f64 {69 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);70}71impl TryFrom<Val> for f64 {72 type Error = LocError;7374 fn try_from(value: Val) -> Result<Self> {75 <Self as Typed>::TYPE.check(&value)?;76 match value {77 Val::Num(n) => Ok(n),78 _ => unreachable!(),79 }80 }81}82impl TryFrom<f64> for Val {83 type Error = LocError;8485 fn try_from(value: f64) -> Result<Self> {86 Ok(Self::Num(value))87 }88}8990pub struct PositiveF64(pub f64);91impl Typed for PositiveF64 {92 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);93}94impl TryFrom<Val> for PositiveF64 {95 type Error = LocError;9697 fn try_from(value: Val) -> Result<Self> {98 <Self as Typed>::TYPE.check(&value)?;99 match value {100 Val::Num(n) => Ok(Self(n)),101 _ => unreachable!(),102 }103 }104}105impl TryFrom<PositiveF64> for Val {106 type Error = LocError;107108 fn try_from(value: PositiveF64) -> Result<Self> {109 Ok(Self::Num(value.0))110 }111}112113impl Typed for usize {114 // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility115 const TYPE: &'static ComplexValType =116 &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));117}118impl TryFrom<Val> for usize {119 type Error = LocError;120121 fn try_from(value: Val) -> Result<Self> {122 <Self as Typed>::TYPE.check(&value)?;123 match value {124 Val::Num(n) => {125 if n.trunc() != n {126 throw!(RuntimeError(127 "cannot convert number with fractional part to usize".into()128 ))129 }130 Ok(n as Self)131 }132 _ => unreachable!(),133 }134 }135}136impl TryFrom<usize> for Val {137 type Error = LocError;138139 fn try_from(value: usize) -> Result<Self> {140 if value > u32::MAX as usize {141 throw!(RuntimeError("number is too large".into()))142 }143 Ok(Self::Num(value as f64))144 }145}146147impl Typed for IStr {148 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);149}150impl TryFrom<Val> for IStr {151 type Error = LocError;152153 fn try_from(value: Val) -> Result<Self> {154 <Self as Typed>::TYPE.check(&value)?;155 match value {156 Val::Str(s) => Ok(s),157 _ => unreachable!(),158 }159 }160}161impl TryFrom<IStr> for Val {162 type Error = LocError;163164 fn try_from(value: IStr) -> Result<Self> {165 Ok(Self::Str(value))166 }167}168169impl Typed for String {170 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);171}172impl TryFrom<Val> for String {173 type Error = LocError;174175 fn try_from(value: Val) -> Result<Self> {176 <Self as Typed>::TYPE.check(&value)?;177 match value {178 Val::Str(s) => Ok(s.to_string()),179 _ => unreachable!(),180 }181 }182}183impl TryFrom<String> for Val {184 type Error = LocError;185186 fn try_from(value: String) -> Result<Self> {187 Ok(Self::Str(value.into()))188 }189}190191impl Typed for char {192 const TYPE: &'static ComplexValType = &ComplexValType::Char;193}194impl TryFrom<Val> for char {195 type Error = LocError;196197 fn try_from(value: Val) -> Result<Self> {198 <Self as Typed>::TYPE.check(&value)?;199 match value {200 Val::Str(s) => Ok(s.chars().next().unwrap()),201 _ => unreachable!(),202 }203 }204}205impl TryFrom<char> for Val {206 type Error = LocError;207208 fn try_from(value: char) -> Result<Self> {209 Ok(Self::Str(value.to_string().into()))210 }211}212213impl<T> Typed for Vec<T>214where215 T: Typed,216 T: TryFrom<Val, Error = LocError>,217 T: TryInto<Val, Error = LocError>,218{219 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);220}221impl<T> TryFrom<Val> for Vec<T>222where223 T: Typed,224 T: TryFrom<Val, Error = LocError>,225 T: TryInto<Val, Error = LocError>,226{227 type Error = LocError;228229 fn try_from(value: Val) -> Result<Self> {230 <Self as Typed>::TYPE.check(&value)?;231 match value {232 Val::Arr(a) => {233 let mut o = Self::with_capacity(a.len());234 for i in a.iter() {235 o.push(T::try_from(i?)?);236 }237 Ok(o)238 }239 _ => unreachable!(),240 }241 }242}243impl<T> TryFrom<Vec<T>> for Val244where245 T: Typed,246 T: TryFrom<Self, Error = LocError>,247 T: TryInto<Self, Error = LocError>,248{249 type Error = LocError;250251 fn try_from(value: Vec<T>) -> Result<Self> {252 let mut o = Vec::with_capacity(value.len());253 for i in value {254 o.push(i.try_into()?);255 }256 Ok(Self::Arr(o.into()))257 }258}259260/// To be used in Vec<Any>261/// Regular Val can't be used here, because it has wrong TryFrom::Error type262#[derive(Clone)]263pub struct Any(pub Val);264265impl Typed for Any {266 const TYPE: &'static ComplexValType = &ComplexValType::Any;267}268impl TryFrom<Val> for Any {269 type Error = LocError;270271 fn try_from(value: Val) -> Result<Self> {272 Ok(Self(value))273 }274}275impl TryFrom<Any> for Val {276 type Error = LocError;277278 fn try_from(value: Any) -> Result<Self> {279 Ok(value.0)280 }281}282283/// Specialization, provides faster TryFrom<VecVal> for Val284pub struct VecVal(pub Vec<Val>);285286impl Typed for VecVal {287 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);288}289impl TryFrom<Val> for VecVal {290 type Error = LocError;291292 fn try_from(value: Val) -> Result<Self> {293 <Self as Typed>::TYPE.check(&value)?;294 match value {295 Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),296 _ => unreachable!(),297 }298 }299}300impl TryFrom<VecVal> for Val {301 type Error = LocError;302303 fn try_from(value: VecVal) -> Result<Self> {304 Ok(Self::Arr(value.0.into()))305 }306}307308pub struct M1;309impl Typed for M1 {310 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));311}312impl TryFrom<Val> for M1 {313 type Error = LocError;314315 fn try_from(value: Val) -> Result<Self> {316 <Self as Typed>::TYPE.check(&value)?;317 Ok(Self)318 }319}320impl TryFrom<M1> for Val {321 type Error = LocError;322323 fn try_from(_: M1) -> Result<Self> {324 Ok(Self::Num(-1.0))325 }326}327328macro_rules! decl_either {329 ($($name: ident, $($id: ident)*);*) => {$(330 pub enum $name<$($id),*> {331 $($id($id)),*332 }333 impl<$($id),*> Typed for $name<$($id),*>334 where335 $($id: Typed,)*336 {337 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);338 }339 impl<$($id),*> TryFrom<Val> for $name<$($id),*>340 where341 $($id: Typed,)*342 {343 type Error = LocError;344345 fn try_from(value: Val) -> Result<Self> {346 $(347 if $id::TYPE.check(&value).is_ok() {348 $id::try_from(value).map(Self::$id)349 } else350 )* {351 <Self as Typed>::TYPE.check(&value)?;352 unreachable!()353 }354 }355 }356 impl<$($id),*> TryFrom<$name<$($id),*>> for Val357 where358 $($id: Typed,)*359 {360 type Error = LocError;361 fn try_from(value: $name<$($id),*>) -> Result<Self> {362 match value {$(363 $name::$id(v) => v.try_into()364 ),*}365 }366 }367 )*}368}369decl_either!(370 Either1, A;371 Either2, A B;372 Either3, A B C;373 Either4, A B C D;374 Either5, A B C D E;375 Either6, A B C D E F;376 Either7, A B C D E F G377);378#[macro_export]379macro_rules! Either {380 ($a:ty) => {Either1<$a>};381 ($a:ty, $b:ty) => {Either2<$a, $b>};382 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};383 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};384 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};385 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};386 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};387}388389pub type MyType = Either![u32, f64, String];390391impl Typed for ArrValue {392 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);393}394impl TryFrom<Val> for ArrValue {395 type Error = LocError;396397 fn try_from(value: Val) -> Result<Self> {398 <Self as Typed>::TYPE.check(&value)?;399 match value {400 Val::Arr(a) => Ok(a),401 _ => unreachable!(),402 }403 }404}405impl TryFrom<ArrValue> for Val {406 type Error = LocError;407408 fn try_from(value: ArrValue) -> Result<Self> {409 Ok(Self::Arr(value))410 }411}412413impl Typed for FuncVal {414 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);415}416impl TryFrom<Val> for FuncVal {417 type Error = LocError;418419 fn try_from(value: Val) -> Result<Self> {420 <Self as Typed>::TYPE.check(&value)?;421 match value {422 Val::Func(a) => Ok(a),423 _ => unreachable!(),424 }425 }426}427impl TryFrom<FuncVal> for Val {428 type Error = LocError;429430 fn try_from(value: FuncVal) -> Result<Self> {431 Ok(Self::Func(value))432 }433}434impl Typed for ObjValue {435 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);436}437impl TryFrom<Val> for ObjValue {438 type Error = LocError;439440 fn try_from(value: Val) -> Result<Self> {441 <Self as Typed>::TYPE.check(&value)?;442 match value {443 Val::Obj(a) => Ok(a),444 _ => unreachable!(),445 }446 }447}448impl TryFrom<ObjValue> for Val {449 type Error = LocError;450451 fn try_from(value: ObjValue) -> Result<Self> {452 Ok(Self::Obj(value))453 }454}455456impl Typed for bool {457 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);458}459impl TryFrom<Val> for bool {460 type Error = LocError;461462 fn try_from(value: Val) -> Result<Self> {463 <Self as Typed>::TYPE.check(&value)?;464 match value {465 Val::Bool(a) => Ok(a),466 _ => unreachable!(),467 }468 }469}470impl TryFrom<bool> for Val {471 type Error = LocError;472473 fn try_from(value: bool) -> Result<Self> {474 Ok(Self::Bool(value))475 }476}477478impl Typed for IndexableVal {479 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[480 &ComplexValType::Simple(ValType::Arr),481 &ComplexValType::Simple(ValType::Str),482 ]);483}484impl TryFrom<Val> for IndexableVal {485 type Error = LocError;486487 fn try_from(value: Val) -> Result<Self> {488 <Self as Typed>::TYPE.check(&value)?;489 value.into_indexable()490 }491}492impl TryFrom<IndexableVal> for Val {493 type Error = LocError;494495 fn try_from(value: IndexableVal) -> Result<Self> {496 match value {497 IndexableVal::Str(s) => Ok(Self::Str(s)),498 IndexableVal::Arr(a) => Ok(Self::Arr(a)),499 }500 }501}502503pub struct Null;504impl Typed for Null {505 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);506}507impl TryFrom<Val> for Null {508 type Error = LocError;509510 fn try_from(value: Val) -> Result<Self> {511 <Self as Typed>::TYPE.check(&value)?;512 Ok(Self)513 }514}515impl TryFrom<Null> for Val {516 type Error = LocError;517518 fn try_from(_: Null) -> Result<Self> {519 Ok(Self::Null)520 }521}crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -15,7 +15,7 @@
pub enum TypeError {
#[error("expected {0}, got {1}")]
ExpectedGot(ComplexValType, ValType),
- #[error("missing property {0} from {1:?}")]
+ #[error("missing property {0} from {1}")]
MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
#[error("every failed from {0}:\n{1}")]
UnionFailed(ComplexValType, TypeLocErrorList),
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,10 +1,38 @@
+use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
- parenthesized, parse::Parse, parse_macro_input, punctuated::Punctuated, spanned::Spanned,
- token::Comma, DeriveInput, FnArg, GenericArgument, Ident, ItemFn, Pat, PatType, Path,
- PathArguments, Token, Type,
+ parenthesized,
+ parse::{Parse, ParseStream},
+ parse_macro_input,
+ punctuated::Punctuated,
+ spanned::Spanned,
+ token::Comma,
+ Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, PatType,
+ Path, PathArguments, Result, Token, Type,
};
+fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>
+where
+ Ident: PartialEq<I>,
+{
+ let attrs = attrs
+ .iter()
+ .filter(|a| a.path.is_ident(&ident))
+ .collect::<Vec<_>>();
+ if attrs.len() > 1 {
+ return Err(Error::new(
+ attrs[1].span(),
+ "this attribute may be specified only once",
+ ));
+ } else if attrs.is_empty() {
+ return Ok(None);
+ }
+ let attr = attrs[0];
+ let attr = attr.parse_args::<A>()?;
+
+ Ok(Some(attr))
+}
+
fn is_location_arg(t: &PatType) -> bool {
t.attrs.iter().any(|a| a.path.is_ident("location"))
}
@@ -56,7 +84,7 @@
ty: Type,
}
impl Parse for Field {
- fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
name: input.parse()?,
_colon: input.parse()?,
@@ -67,13 +95,22 @@
mod kw {
syn::custom_keyword!(fields);
+ syn::custom_keyword!(rename);
+ syn::custom_keyword!(flatten);
+}
+
+struct EmptyAttr;
+impl Parse for EmptyAttr {
+ fn parse(input: ParseStream) -> Result<Self> {
+ Ok(Self)
+ }
}
struct BuiltinAttrs {
fields: Vec<Field>,
}
impl Parse for BuiltinAttrs {
- fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
if input.is_empty() {
return Ok(Self { fields: Vec::new() });
}
@@ -255,7 +292,172 @@
.into()
}
-#[proc_macro_derive(Typed)]
+#[derive(Default)]
+struct TypedAttr {
+ rename: Option<String>,
+ flatten: bool,
+}
+impl Parse for TypedAttr {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ let mut out = Self::default();
+ loop {
+ let lookahead = input.lookahead1();
+ if lookahead.peek(kw::rename) {
+ input.parse::<kw::rename>()?;
+ input.parse::<Token![=]>()?;
+ let name = input.parse::<LitStr>()?;
+ if out.rename.is_some() {
+ return Err(Error::new(
+ name.span(),
+ "rename attribute may only be specified once",
+ ));
+ }
+ out.rename = Some(name.value());
+ } else if lookahead.peek(kw::flatten) {
+ input.parse::<kw::flatten>()?;
+ out.flatten = true;
+ } else if input.is_empty() {
+ break;
+ } else {
+ return Err(lookahead.error());
+ }
+ if input.peek(Token![,]) {
+ input.parse::<Token![,]>()?;
+ } else {
+ break;
+ }
+ }
+ // input.parse::<kw::rename>()?;
+ // input.parse::<Token![=]>()?;
+ // let rename = input.parse::<LitStr>()?.value();
+ Ok(out)
+ }
+}
+
+struct TypedField<'f>(&'f syn::Field, TypedAttr);
+impl<'f> TypedField<'f> {
+ fn try_new(field: &'f syn::Field) -> Result<Self> {
+ let attr =
+ parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_else(Default::default);
+ if field.ident.is_none() {
+ return Err(Error::new(
+ field.span(),
+ "this field should appear in output object, but it has no visible name",
+ ));
+ }
+ Ok(Self(field, attr))
+ }
+ fn ident(&self) -> Ident {
+ self.0
+ .ident
+ .clone()
+ .expect("constructor disallows fields without name")
+ }
+ /// None if this field is flattened in jsonnet output
+ fn name(&self) -> Option<String> {
+ if self.1.flatten {
+ return None;
+ }
+ Some(
+ self.1
+ .rename
+ .clone()
+ .unwrap_or_else(|| self.ident().to_string()),
+ )
+ }
+
+ fn expand_shallow_field(&self) -> Option<TokenStream> {
+ if self.is_option() {
+ return None;
+ }
+ let name = self.name()?;
+ Some(quote! {
+ (#name, ComplexValType::Any)
+ })
+ }
+ fn expand_field(&self) -> Option<TokenStream> {
+ if self.is_option() {
+ return None;
+ }
+ let name = self.name()?;
+ let ty = &self.0.ty;
+ Some(quote! {
+ (#name, <#ty>::TYPE)
+ })
+ }
+ fn expand_parse(&self) -> TokenStream {
+ let ident = self.ident();
+ let ty = &self.0.ty;
+ if self.1.flatten {
+ // optional flatten is handled in same way as serde
+ return if self.is_option() {
+ quote! {
+ #ident: <#ty>::parse(&obj).ok(),
+ }
+ } else {
+ quote! {
+ #ident: <#ty>::parse(&obj)?,
+ }
+ };
+ };
+
+ let name = self.name().unwrap();
+ let value = if let Some(ty) = self.as_option() {
+ quote! {
+ if let Some(value) = obj.get(#name.into())? {
+ Some(<#ty>::try_from(vakue)?)
+ } else {
+ None
+ }
+ }
+ } else {
+ quote! {
+ <#ty>::try_from(obj.get(#name.into())?.ok_or_else(|| Error::NoSuchField(#name.into()))?)?
+ }
+ };
+
+ quote! {
+ #ident: #value,
+ }
+ }
+ fn expand_serialize(&self) -> TokenStream {
+ let ident = self.ident();
+ if let Some(name) = self.name() {
+ if self.is_option() {
+ quote! {
+ if let Some(value) = self.#ident {
+ out.member(#name.into()).value(value.try_into()?);
+ }
+ }
+ } else {
+ quote! {
+ out.member(#name.into()).value(self.#ident.try_into()?);
+ }
+ }
+ } else {
+ if self.is_option() {
+ quote! {
+ if let Some(value) = self.#ident {
+ value.serialize(out)?;
+ }
+ }
+ } else {
+ quote! {
+ self.#ident.serialize(out)?;
+ }
+ }
+ }
+ }
+
+ fn as_option(&self) -> Option<&Type> {
+ extract_type_from_option(&self.0.ty)
+ }
+ fn is_option(&self) -> bool {
+ self.as_option().is_some()
+ }
+}
+
+#[proc_macro_derive(Typed, attributes(typed))]
pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(item as DeriveInput);
let data = match &input.data {
@@ -268,67 +470,71 @@
};
let ident = &input.ident;
+ let fields = match data
+ .fields
+ .iter()
+ .map(TypedField::try_new)
+ .collect::<Result<Vec<_>>>()
+ {
+ Ok(v) => v,
+ Err(e) => return e.to_compile_error().into(),
+ };
- let fields_def = data.fields.iter().map(|f| {
- let name = f
- .ident
- .as_ref()
- .expect("only named fields supported")
- .to_string();
- let ty = &f.ty;
- quote! {
- (#name, #ty::TYPE),
- }
- });
- let fields_parse = data.fields.iter().map(|f| {
- let ident = f.ident.as_ref().unwrap();
- let name = ident.to_string();
- let ty = &f.ty;
+ let typed = {
+ let fields = fields
+ .iter()
+ .flat_map(TypedField::expand_field)
+ .collect::<Vec<_>>();
+ let len = fields.len();
quote! {
- #ident: #ty::try_from(obj.get(#name.into())?.expect("shape is correct"))?,
+ const ITEMS: [(&'static str, &'static ComplexValType); #len] = [
+ #(#fields,)*
+ ];
+ impl Typed for #ident {
+ const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&ITEMS);
+ }
}
- });
- let fields_serialize = data.fields.iter().map(|f| {
- let ident = f.ident.as_ref().unwrap();
- let name = ident.to_string();
- quote! {
- out.member(#name.into()).value(self.#ident.try_into()?);
- }
- });
- let field_count = data.fields.len();
+ };
+
+ let fields_parse = fields.iter().map(TypedField::expand_parse);
+ let fields_serialize = fields.iter().map(TypedField::expand_serialize);
quote! {
const _: () = {
use ::jrsonnet_evaluator::{
- typed::{ComplexValType, Typed, CheckType},
+ typed::{ComplexValType, Typed, TypedObj, CheckType},
Val,
- error::LocError,
- obj::ObjValueBuilder,
+ error::{LocError, Error},
+ ObjValueBuilder, ObjValue,
};
- const ITEMS: [(&'static str, &'static ComplexValType); #field_count] = [
- #(#fields_def)*
- ];
- impl Typed for #ident {
- const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&ITEMS);
+ #typed
+
+ impl #ident {
+ fn serialize(self, out: &mut ObjValueBuilder) -> Result<(), LocError> {
+ #(#fields_serialize)*
+
+ Ok(())
+ }
+ fn parse(obj: &ObjValue) -> Result<Self, LocError> {
+ Ok(Self {
+ #(#fields_parse)*
+ })
+ }
}
impl TryFrom<Val> for #ident {
type Error = LocError;
fn try_from(value: Val) -> Result<Self, Self::Error> {
- <Self as Typed>::TYPE.check(&value)?;
let obj = value.as_obj().expect("shape is correct");
-
- Ok(Self {
- #(#fields_parse)*
- })
+ Self::parse(&obj)
}
}
impl TryInto<Val> for #ident {
type Error = LocError;
fn try_into(self) -> Result<Val, Self::Error> {
let mut out = ObjValueBuilder::new();
- #(#fields_serialize)*
+ self.serialize(&mut out)?;
Ok(Val::Obj(out.build()))
}
}