git.delta.rocks / jrsonnet / refs/commits / 78d82dfdf2a1

difftreelog

feat derive(Typed) for struct

Yaroslav Bolyukin2022-04-04parent: #d710b4f.patch.diff
in: master

9 files changed

modifiedCargo.lockdiffbeforeafterboth
before · Cargo.lock
74 packageslockfile v3
after · Cargo.lock
74 packageslockfile v3
modifiedcrates/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 {
modifiedcrates/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];
modifiedcrates/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)
+		}
+	}
 }
modifiedcrates/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::{
modifiedcrates/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(())
modifiedcrates/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> {
modifiedcrates/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()
+}
modifiedcrates/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>),