difftreelog
feat derive(Typed) for struct
in: master
9 files changed
Cargo.lockdiffbeforeafterboth707071[[package]]71[[package]]72name = "clap"72name = "clap"73version = "3.0.0-beta.2"73version = "3.1.8"74source = "git+https://github.com/clap-rs/clap?rev=f0c5ea5e1503de5c8e74d8c047a799cf51498e83#f0c5ea5e1503de5c8e74d8c047a799cf51498e83"74source = "registry+https://github.com/rust-lang/crates.io-index"75checksum = "71c47df61d9e16dc010b55dba1952a57d8c215dbb533fd13cdd13369aac73b1c"75dependencies = [76dependencies = [76 "atty",77 "atty",77 "bitflags",78 "bitflags",82 "strsim",83 "strsim",83 "termcolor",84 "termcolor",84 "textwrap",85 "textwrap",85 "vec_map",86]86]878788[[package]]88[[package]]89name = "clap_derive"89name = "clap_complete"90version = "3.0.0-beta.2"90version = "3.1.1"91source = "git+https://github.com/clap-rs/clap?rev=f0c5ea5e1503de5c8e74d8c047a799cf51498e83#f0c5ea5e1503de5c8e74d8c047a799cf51498e83"91source = "registry+https://github.com/rust-lang/crates.io-index"92checksum = "df6f3613c0a3cddfd78b41b10203eb322cb29b600cbdf808a7d3db95691b8e25"92dependencies = [93dependencies = [93 "heck",94 "clap",94 "proc-macro-error",95 "proc-macro2",96 "quote",97 "syn",98]95]9996100[[package]]97[[package]]101name = "clap_generate"98name = "clap_derive"102version = "3.0.0-beta.2"99version = "3.1.7"103source = "git+https://github.com/clap-rs/clap?rev=f0c5ea5e1503de5c8e74d8c047a799cf51498e83#f0c5ea5e1503de5c8e74d8c047a799cf51498e83"100source = "registry+https://github.com/rust-lang/crates.io-index"101checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1"104dependencies = [102dependencies = [105 "clap",103 "heck",104 "proc-macro-error",105 "proc-macro2",106 "quote",107 "syn",106]108]107109108[[package]]110[[package]]148150149[[package]]151[[package]]150name = "heck"152name = "heck"151version = "0.3.3"153version = "0.4.0"152source = "registry+https://github.com/rust-lang/crates.io-index"154source = "registry+https://github.com/rust-lang/crates.io-index"153checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"155checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"154dependencies = [155 "unicode-segmentation",156]157156158[[package]]157[[package]]159name = "hermit-abi"158name = "hermit-abi"185version = "0.4.2"184version = "0.4.2"186dependencies = [185dependencies = [187 "clap",186 "clap",188 "clap_generate",187 "clap_complete",189 "gcmodule",188 "gcmodule",190 "jrsonnet-cli",189 "jrsonnet-cli",191 "jrsonnet-evaluator",190 "jrsonnet-evaluator",214 "bincode",213 "bincode",215 "gcmodule",214 "gcmodule",216 "jrsonnet-interner",215 "jrsonnet-interner",216 "jrsonnet-macros",217 "jrsonnet-parser",217 "jrsonnet-parser",218 "jrsonnet-stdlib",218 "jrsonnet-stdlib",219 "jrsonnet-types",219 "jrsonnet-types",235 "serde",235 "serde",236]236]237238[[package]]239name = "jrsonnet-macros"240version = "0.4.2"241dependencies = [242 "proc-macro2",243 "quote",244 "syn",245]237246238[[package]]247[[package]]239name = "jrsonnet-parser"248name = "jrsonnet-parser"300source = "registry+https://github.com/rust-lang/crates.io-index"309source = "registry+https://github.com/rust-lang/crates.io-index"301checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"310checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"311312[[package]]313name = "memchr"314version = "2.4.1"315source = "registry+https://github.com/rust-lang/crates.io-index"316checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"302317303[[package]]318[[package]]304name = "mimalloc-sys"319name = "mimalloc-sys"321336322[[package]]337[[package]]323name = "os_str_bytes"338name = "os_str_bytes"324version = "3.1.0"339version = "6.0.0"325source = "registry+https://github.com/rust-lang/crates.io-index"340source = "registry+https://github.com/rust-lang/crates.io-index"326checksum = "6acbef58a60fe69ab50510a55bc8cdd4d6cf2283d27ad338f54cb52747a9cf2d"341checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"342dependencies = [343 "memchr",344]327345328[[package]]346[[package]]329name = "parking_lot"347name = "parking_lot"357375358[[package]]376[[package]]359name = "peg"377name = "peg"360version = "0.7.0"378version = "0.8.0"361source = "registry+https://github.com/rust-lang/crates.io-index"379source = "registry+https://github.com/rust-lang/crates.io-index"362checksum = "07c0b841ea54f523f7aa556956fbd293bcbe06f2e67d2eb732b7278aaf1d166a"380checksum = "af728fe826811af3b38c37e93de6d104485953ea373d656eebae53d6987fcd2c"363dependencies = [381dependencies = [364 "peg-macros",382 "peg-macros",365 "peg-runtime",383 "peg-runtime",366]384]367385368[[package]]386[[package]]369name = "peg-macros"387name = "peg-macros"370version = "0.7.0"388version = "0.8.0"371source = "registry+https://github.com/rust-lang/crates.io-index"389source = "registry+https://github.com/rust-lang/crates.io-index"372checksum = "b5aa52829b8decbef693af90202711348ab001456803ba2a98eb4ec8fb70844c"390checksum = "4536be147b770b824895cbad934fccce8e49f14b4c4946eaa46a6e4a12fcdc16"373dependencies = [391dependencies = [374 "peg-runtime",392 "peg-runtime",375 "proc-macro2",393 "proc-macro2",378396379[[package]]397[[package]]380name = "peg-runtime"398name = "peg-runtime"381version = "0.7.0"399version = "0.8.0"382source = "registry+https://github.com/rust-lang/crates.io-index"400source = "registry+https://github.com/rust-lang/crates.io-index"383checksum = "c719dcf55f09a3a7e764c6649ab594c18a177e3599c467983cdf644bfc0a4088"401checksum = "f9b0efd3ba03c3a409d44d60425f279ec442bcf0b9e63ff4e410da31c8b0f69f"384402385[[package]]403[[package]]386name = "proc-macro-error"404name = "proc-macro-error"536554537[[package]]555[[package]]538name = "textwrap"556name = "textwrap"539version = "0.14.2"557version = "0.15.0"540source = "registry+https://github.com/rust-lang/crates.io-index"558source = "registry+https://github.com/rust-lang/crates.io-index"541checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80"559checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"542dependencies = [543 "unicode-width",544]545560546[[package]]561[[package]]547name = "thiserror"562name = "thiserror"563 "syn",578 "syn",564]579]565566[[package]]567name = "unicode-segmentation"568version = "1.8.0"569source = "registry+https://github.com/rust-lang/crates.io-index"570checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"571580572[[package]]581[[package]]573name = "unicode-width"582name = "unicode-width"581source = "registry+https://github.com/rust-lang/crates.io-index"590source = "registry+https://github.com/rust-lang/crates.io-index"582checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"591checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"583584[[package]]585name = "vec_map"586version = "0.8.2"587source = "registry+https://github.com/rust-lang/crates.io-index"588checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"589592590[[package]]593[[package]]591name = "version_check"594name = "version_check"crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -179,7 +179,7 @@
}
}
-pub type Result<V> = std::result::Result<V, LocError>;
+pub type Result<V, E = LocError> = std::result::Result<V, E>;
#[macro_export]
macro_rules! throw {
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -8,6 +8,7 @@
};
use gcmodule::Trace;
use jrsonnet_interner::IStr;
+pub use jrsonnet_macros::builtin;
use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};
use std::{borrow::Cow, collections::HashMap, convert::TryFrom};
@@ -377,6 +378,7 @@
pub has_default: bool,
}
+/// Do not implement it directly, instead use #[builtin] macro
pub trait Builtin: Trace {
fn name(&self) -> &str;
fn params(&self) -> &[BuiltinParam];
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -174,7 +174,11 @@
pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)
}
pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
- EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
+ EVAL_STATE.with(|s| {
+ f(s.borrow().as_ref().expect(
+ "missing evaluation state, some functions should be called inside of run_in_state call",
+ ))
+ })
}
pub fn push_frame<T>(
e: Option<&ExprLocation>,
@@ -728,12 +732,15 @@
}
macro_rules! eval {
- ($str: expr) => {
- EvaluationState::default()
- .with_stdlib()
- .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
- .unwrap()
- };
+ ($str: expr) => {{
+ let evaluator = EvaluationState::default();
+ evaluator.with_stdlib();
+ evaluator.run_in_state(|| {
+ evaluator
+ .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
+ .unwrap()
+ })
+ }};
}
macro_rules! eval_json {
($str: expr) => {{
@@ -1265,4 +1272,47 @@
assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);
assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);
}
+
+ mod derive_typed {
+ use crate::{typed::Typed, EvaluationState};
+ use std::path::PathBuf;
+
+ #[derive(Typed, PartialEq, Debug)]
+ struct MyTyped {
+ a: u32,
+ b: String,
+ }
+
+ #[test]
+ fn test() {
+ let es = EvaluationState::default();
+ let val = eval!("{a: 14, b: 'Hello, world!'}");
+ let typed = es.run_in_state(|| MyTyped::try_from(val).unwrap());
+
+ assert_eq!(
+ typed,
+ MyTyped {
+ a: 14,
+ b: "Hello, world!".to_string()
+ }
+ );
+ es.settings_mut().globals.insert(
+ "mytyped".into(),
+ es.run_in_state(|| typed.try_into()).unwrap(),
+ );
+
+ let v = es
+ .evaluate_snippet_raw(
+ PathBuf::from("raw.jsonnet").into(),
+ "
+ mytyped == {a: 14, b: 'Hello, world!'}
+ "
+ .into(),
+ )
+ .unwrap()
+ .as_bool()
+ .unwrap();
+ assert!(v)
+ }
+ }
}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,6 +1,7 @@
use std::convert::{TryFrom, TryInto};
use jrsonnet_interner::IStr;
+pub use jrsonnet_macros::Typed;
use jrsonnet_types::{ComplexValType, ValType};
use crate::{
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -8,20 +8,8 @@
push_description_frame, Val,
};
use gcmodule::Trace;
-use jrsonnet_types::{ComplexValType, ValType};
+pub use jrsonnet_types::{ComplexValType, ValType};
use thiserror::Error;
-
-#[macro_export]
-macro_rules! unwrap_type {
- ($desc:expr, $value:expr, $typ:expr => $match:path) => {{
- use $crate::{push_frame, typed::CheckType};
- push_frame(None, $desc, || Ok($typ.check(&$value)?))?;
- match $value {
- $match(v) => v,
- _ => unreachable!(),
- }
- }};
-}
#[derive(Debug, Error, Clone, Trace)]
pub enum TypeError {
@@ -136,7 +124,7 @@
impl Display for ValuePathItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Self::Field(name) => write!(f, ".{}", name)?,
+ Self::Field(name) => write!(f, ".{:?}", name)?,
Self::Index(idx) => write!(f, "[{}]", idx)?,
}
Ok(())
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -91,7 +91,7 @@
Normal(Cc<FuncDesc>),
/// Standard library function
StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),
-
+ /// User-provided function
Builtin(Cc<TraceBox<dyn Builtin>>),
}
@@ -99,8 +99,10 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),
- Self::StaticBuiltin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),
- Self::Builtin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),
+ Self::StaticBuiltin(arg0) => {
+ f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()
+ }
+ Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),
}
}
}
@@ -338,6 +340,49 @@
}
impl Val {
+ pub fn as_bool(&self) -> Option<bool> {
+ match self {
+ Val::Bool(v) => Some(*v),
+ _ => None,
+ }
+ }
+ pub fn as_null(&self) -> Option<()> {
+ match self {
+ Val::Null => Some(()),
+ _ => None,
+ }
+ }
+ pub fn as_str(&self) -> Option<IStr> {
+ match self {
+ Val::Str(s) => Some(s.clone()),
+ _ => None,
+ }
+ }
+ pub fn as_num(&self) -> Option<f64> {
+ match self {
+ Val::Num(n) => Some(*n),
+ _ => None,
+ }
+ }
+ pub fn as_arr(&self) -> Option<ArrValue> {
+ match self {
+ Val::Arr(a) => Some(a.clone()),
+ _ => None,
+ }
+ }
+ pub fn as_obj(&self) -> Option<ObjValue> {
+ match self {
+ Val::Obj(o) => Some(o.clone()),
+ _ => None,
+ }
+ }
+ pub fn as_func(&self) -> Option<FuncVal> {
+ match self {
+ Val::Func(f) => Some(f.clone()),
+ _ => None,
+ }
+ }
+
/// Creates `Val::Num` after checking for numeric overflow.
/// As numbers are `f64`, we can just check for their finity.
pub fn new_checked_num(num: f64) -> Result<Self> {
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,8 +1,8 @@
use quote::{quote, quote_spanned};
use syn::{
parenthesized, parse::Parse, parse_macro_input, punctuated::Punctuated, spanned::Spanned,
- token::Comma, FnArg, GenericArgument, Ident, ItemFn, Pat, PatType, Path, PathArguments, Token,
- Type,
+ token::Comma, DeriveInput, FnArg, GenericArgument, Ident, ItemFn, Pat, PatType, Path,
+ PathArguments, Token, Type,
};
fn is_location_arg(t: &PatType) -> bool {
@@ -254,3 +254,86 @@
})
.into()
}
+
+#[proc_macro_derive(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 {
+ syn::Data::Struct(s) => s,
+ _ => {
+ return syn::Error::new(input.span(), "only structs supported")
+ .to_compile_error()
+ .into()
+ }
+ };
+
+ let ident = &input.ident;
+
+ 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;
+ quote! {
+ #ident: #ty::try_from(obj.get(#name.into())?.expect("shape is correct"))?,
+ }
+ });
+ 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();
+
+ quote! {
+ const _: () = {
+ use ::jrsonnet_evaluator::{
+ typed::{ComplexValType, Typed, CheckType},
+ Val,
+ error::LocError,
+ obj::ObjValueBuilder,
+ };
+
+ const ITEMS: [(&'static str, &'static ComplexValType); #field_count] = [
+ #(#fields_def)*
+ ];
+ impl Typed for #ident {
+ const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&ITEMS);
+ }
+
+ 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)*
+ })
+ }
+ }
+ impl TryInto<Val> for #ident {
+ type Error = LocError;
+ fn try_into(self) -> Result<Val, Self::Error> {
+ let mut out = ObjValueBuilder::new();
+ #(#fields_serialize)*
+ Ok(Val::Obj(out.build()))
+ }
+ }
+ ()
+ };
+ }
+ .into()
+}
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -122,7 +122,7 @@
BoundedNumber(Option<f64>, Option<f64>),
Array(Box<ComplexValType>),
ArrayRef(&'static ComplexValType),
- ObjectRef(&'static [(&'static str, ComplexValType)]),
+ ObjectRef(&'static [(&'static str, &'static ComplexValType)]),
Union(Vec<ComplexValType>),
UnionRef(&'static [&'static ComplexValType]),
Sum(Vec<ComplexValType>),