git.delta.rocks / jrsonnet / refs/commits / 432b17211316

difftreelog

feat(evaluator) tailstrict functions

Лач2020-06-07parent: #8eff851.patch.diff
in: master

5 files changed

modifiedcrates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/ctx.rs
+++ b/crates/jsonnet-evaluator/src/ctx.rs
@@ -1,8 +1,6 @@
 use crate::{
-	future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Result,
-	Val,
+	future_wrapper, rc_fn_helper, resolved_lazy_val, LazyBinding, LazyVal, ObjValue, Result, Val,
 };
-use closure::closure;
 use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
 
 rc_fn_helper!(
@@ -68,12 +66,7 @@
 
 	pub fn with_var(&self, name: String, value: Val) -> Result<Context> {
 		let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();
-		new_bindings.insert(
-			name,
-			lazy_binding!(
-				closure!(clone value, |_t, _s|Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))
-			),
-		);
+		new_bindings.insert(name, LazyBinding::Bound(resolved_lazy_val!(value.clone())));
 		self.extend(new_bindings, None, None, None)
 	}
 
@@ -95,7 +88,7 @@
 				new.insert(k.clone(), v.clone());
 			}
 			for (k, v) in new_bindings.into_iter() {
-				new.insert(k, v.0(this.clone(), super_obj.clone())?);
+				new.insert(k, v.evaluate(this.clone(), super_obj.clone())?);
 			}
 			Rc::new(new)
 		};
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -1,7 +1,7 @@
 use crate::{
 	binding, context_creator, create_error, function_default, function_rhs, future_wrapper,
-	lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,
-	ObjValue, Result, Val,
+	lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue,
+	Result, Val,
 };
 use closure::closure;
 use jsonnet_parser::{
@@ -19,18 +19,20 @@
 		let args = args.clone();
 		(
 			b.name.clone(),
-			lazy_binding!(move |this, super_obj| Ok(lazy_val!(
-				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(
-					context_creator.0(this.clone(), super_obj.clone())?,
-					&b.value,
-					args.clone()
-				)))
-			))),
+			LazyBinding::Bindable(Rc::new(move |this, super_obj| {
+				Ok(lazy_val!(
+					closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(
+						context_creator.0(this.clone(), super_obj.clone())?,
+						&b.value,
+						args.clone()
+					)))
+				))
+			})),
 		)
 	} else {
 		(
 			b.name.clone(),
-			lazy_binding!(move |this, super_obj| {
+			LazyBinding::Bindable(Rc::new(move |this, super_obj| {
 				Ok(lazy_val!(closure!(clone context_creator, clone b, ||
 					push(b.value.clone(), "thunk".to_owned(), ||{
 						evaluate(
@@ -39,7 +41,7 @@
 						)
 					})
 				)))
-			}),
+			})),
 		)
 	}
 }
@@ -405,7 +407,7 @@
 			&evaluate(context.clone(), s)?,
 			&Val::Obj(evaluate_object(context, t.clone())?),
 		)?,
-		Apply(value, ArgsDesc(args)) => {
+		Apply(value, ArgsDesc(args), tailstrict) => {
 			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;
 			match value {
 				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {
@@ -502,7 +504,8 @@
 							evaluate(context.clone(), &args[0].1)?,
 							evaluate(context, &args[1].1)?,
 						) {
-							println!("{}", a);
+							// TODO: Line numbers as in original jsonnet
+							println!("TRACE: {}", a);
 							b
 						} else {
 							panic!("bad trace call");
@@ -517,9 +520,15 @@
 							.map(move |a| {
 								(
 									a.clone().0,
-									Val::Lazy(lazy_val!(
-										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))
-									)),
+									if *tailstrict {
+										Val::Lazy(LazyVal::new_resolved(
+											evaluate(context.clone(), &a.1).unwrap(),
+										))
+									} else {
+										Val::Lazy(lazy_val!(
+											closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))
+										))
+									},
 								)
 							})
 							.collect(),
addedcrates/jsonnet-evaluator/src/function.rsdiffbeforeafterboth

no changes

modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -6,28 +6,23 @@
 mod dynamic;
 mod error;
 mod evaluate;
+mod function;
 mod obj;
 mod val;
 
-use closure::closure;
 pub use ctx::*;
 pub use dynamic::*;
 pub use error::*;
 pub use evaluate::*;
 use jsonnet_parser::*;
 pub use obj::*;
-use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
+use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};
 pub use val::*;
 
 rc_fn_helper!(
 	Binding,
 	binding,
 	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>
-);
-rc_fn_helper!(
-	LazyBinding,
-	lazy_binding,
-	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>
 );
 rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);
 rc_fn_helper!(
@@ -36,6 +31,26 @@
 	dyn Fn(Context, LocExpr) -> Result<Val>
 );
 
+#[derive(Clone)]
+pub enum LazyBinding {
+	Bindable(Rc<dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>>),
+	Bound(LazyVal),
+}
+
+impl Debug for LazyBinding {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		write!(f, "LazyBinding")
+	}
+}
+impl LazyBinding {
+	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
+		match self {
+			LazyBinding::Bindable(v) => v(this, super_obj),
+			LazyBinding::Bound(v) => Ok(v.clone()),
+		}
+	}
+}
+
 pub struct FileData(String, LocExpr, Option<Val>);
 #[derive(Default)]
 pub struct EvaluationStateInternals {
@@ -168,9 +183,7 @@
 		for (name, value) in globals.iter() {
 			new_bindings.insert(
 				name.clone(),
-				lazy_binding!(
-					closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))
-				),
+				LazyBinding::Bound(resolved_lazy_val!(value.clone())),
 			);
 		}
 		Context::new().extend(new_bindings, None, None, None)
@@ -179,7 +192,7 @@
 	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {
 		{
 			let mut stack = self.0.stack.borrow_mut();
-			if stack.len() > 5000 {
+			if stack.len() > 500 {
 				drop(stack);
 				return self.error(Error::StackOverflow);
 			} else {
modifiedcrates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jsonnet-evaluator/src/val.rs
1use crate::{2	create_error, lazy_binding, Context, Error, FunctionDefault, FunctionRhs, LazyBinding,3	ObjValue, Result,4};5use closure::closure;6use jsonnet_parser::{Param, ParamsDesc};7use std::{8	cell::RefCell,9	collections::HashMap,10	fmt::{Debug, Display},11	rc::Rc,12};1314struct LazyValInternals {15	pub f: Box<dyn Fn() -> Result<Val>>,16	pub cached: RefCell<Option<Val>>,17}18#[derive(Clone)]19pub struct LazyVal(Rc<LazyValInternals>);20impl LazyVal {21	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {22		LazyVal(Rc::new(LazyValInternals {23			f,24			cached: RefCell::new(None),25		}))26	}27	pub fn evaluate(&self) -> Result<Val> {28		{29			let cached = self.0.cached.borrow();30			if cached.is_some() {31				return Ok(cached.clone().unwrap());32			}33		}34		let result = (self.0.f)()?;35		self.0.cached.borrow_mut().replace(result.clone());36		Ok(result)37	}38}39#[macro_export]40macro_rules! lazy_val {41	($f: expr) => {42		$crate::LazyVal::new(Box::new($f))43	};44}45impl Debug for LazyVal {46	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {47		if self.0.cached.borrow().is_some() {48			write!(f, "{:?}", self.0.cached.borrow().clone().unwrap())49		} else {50			write!(f, "Lazy")51		}52	}53}54impl PartialEq for LazyVal {55	fn eq(&self, other: &Self) -> bool {56		Rc::ptr_eq(&self.0, &other.0)57	}58}5960#[derive(Debug, PartialEq, Clone)]61pub struct FuncDesc {62	pub ctx: Context,63	pub params: ParamsDesc,64	pub eval_rhs: FunctionRhs,65	pub eval_default: FunctionDefault,66}67impl FuncDesc {68	// TODO: Check for unset variables69	pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Result<Val> {70		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();71		let future_ctx = Context::new_future();7273		for Param(name, default) in self.params.with_defaults() {74			let default = default.unwrap();75			let eval_default = self.eval_default.clone();76			new_bindings.insert(77				name,78				lazy_binding!(closure!(clone future_ctx, clone default, clone eval_default, |_, _| Ok(lazy_val!(closure!(clone future_ctx, clone eval_default, clone default, || (eval_default.clone()).079					(future_ctx.clone().unwrap(), default.clone())))))),80			);81		}82		for (name, val) in args.clone().into_iter().filter(|e| e.0.is_some()) {83			new_bindings.insert(84				name.as_ref().unwrap().clone(),85				lazy_binding!(86					closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))87				),88			);89		}90		for (i, param) in self.params.0.iter().enumerate() {91			if let Some((None, val)) = args.get(i) {92				new_bindings.insert(93					param.0.clone(),94					lazy_binding!(95						closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))96					),97				);98			}99		}100		let ctx = self101			.ctx102			.extend(new_bindings, None, None, None)?103			.into_future(future_ctx);104		self.eval_rhs.0(ctx)105	}106}107108#[derive(Debug)]109pub enum ValType {110	Bool,111	Null,112	Str,113	Num,114	Arr,115	Obj,116	Func,117}118impl ValType {119	pub fn name(&self) -> &'static str {120		use ValType::*;121		match self {122			Bool => "boolean",123			Null => "null",124			Str => "string",125			Num => "number",126			Arr => "array",127			Obj => "object",128			Func => "function",129		}130	}131}132impl Display for ValType {133	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {134		write!(f, "{}", self.name())135	}136}137138#[derive(Debug, PartialEq, Clone)]139pub enum Val {140	Bool(bool),141	Null,142	Str(String),143	Num(f64),144	Lazy(LazyVal),145	Arr(Vec<Val>),146	Obj(ObjValue),147	Func(FuncDesc),148149	// Library functions implemented in native150	Intristic(String, String),151}152impl Val {153	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {154		match self.unwrap_if_lazy()? {155			Val::Bool(v) => Ok(v),156			v => create_error(Error::TypeMismatch(157				context,158				vec![ValType::Bool],159				v.value_type()?,160			)),161		}162	}163	pub fn try_cast_str(self, context: &'static str) -> Result<String> {164		match self.unwrap_if_lazy()? {165			Val::Str(v) => Ok(v),166			v => create_error(Error::TypeMismatch(167				context,168				vec![ValType::Str],169				v.value_type()?,170			)),171		}172	}173	pub fn unwrap_if_lazy(self) -> Result<Self> {174		Ok(if let Val::Lazy(v) = self {175			v.evaluate()?.unwrap_if_lazy()?176		} else {177			self178		})179	}180	pub fn value_type(&self) -> Result<ValType> {181		Ok(match self {182			Val::Str(..) => ValType::Str,183			Val::Num(..) => ValType::Num,184			Val::Arr(..) => ValType::Arr,185			Val::Obj(..) => ValType::Obj,186			Val::Func(..) => ValType::Func,187			Val::Bool(_) => ValType::Bool,188			Val::Null => ValType::Null,189			Val::Intristic(_, _) => ValType::Func,190			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,191		})192	}193}
after · crates/jsonnet-evaluator/src/val.rs
1use crate::{2	create_error, Context, Error, FunctionDefault, FunctionRhs, LazyBinding, ObjValue, Result,3};4use closure::closure;5use jsonnet_parser::{Param, ParamsDesc};6use std::{7	cell::RefCell,8	collections::HashMap,9	fmt::{Debug, Display},10	rc::Rc,11};1213struct LazyValInternals {14	pub f: Option<Box<dyn Fn() -> Result<Val>>>,15	pub cached: RefCell<Option<Val>>,16}17#[derive(Clone)]18pub struct LazyVal(Rc<LazyValInternals>);19impl LazyVal {20	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {21		LazyVal(Rc::new(LazyValInternals {22			f: Some(f),23			cached: RefCell::new(None),24		}))25	}26	pub fn new_resolved(val: Val) -> Self {27		LazyVal(Rc::new(LazyValInternals {28			f: None,29			cached: RefCell::new(Some(val)),30		}))31	}32	pub fn evaluate(&self) -> Result<Val> {33		{34			let cached = self.0.cached.borrow();35			if cached.is_some() {36				return Ok(cached.clone().unwrap());37			}38		}39		let result = (self.0.f.as_ref().unwrap())()?;40		self.0.cached.borrow_mut().replace(result.clone());41		Ok(result)42	}43}4445#[macro_export]46macro_rules! lazy_val {47	($f: expr) => {48		$crate::LazyVal::new(Box::new($f))49	};50}51#[macro_export]52macro_rules! resolved_lazy_val {53	($f: expr) => {54		$crate::LazyVal::new_resolved($f)55	};56}57impl Debug for LazyVal {58	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {59		if self.0.cached.borrow().is_some() {60			write!(f, "{:?}", self.0.cached.borrow().clone().unwrap())61		} else {62			write!(f, "Lazy")63		}64	}65}66impl PartialEq for LazyVal {67	fn eq(&self, other: &Self) -> bool {68		Rc::ptr_eq(&self.0, &other.0)69	}70}7172#[derive(Debug, PartialEq, Clone)]73pub struct FuncDesc {74	pub ctx: Context,75	pub params: ParamsDesc,76	pub eval_rhs: FunctionRhs,77	pub eval_default: FunctionDefault,78}79impl FuncDesc {80	// TODO: Check for unset variables81	pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Result<Val> {82		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();83		let future_ctx = Context::new_future();8485		for Param(name, default) in self.params.with_defaults() {86			let default = default.unwrap();87			let eval_default = self.eval_default.clone();88			new_bindings.insert(89				name,90				LazyBinding::Bound(lazy_val!(91					closure!(clone future_ctx, clone eval_default, clone default, || (eval_default.clone()).092					(future_ctx.clone().unwrap(), default.clone()))93				)),94			);95		}96		for (name, val) in args.clone().into_iter().filter(|e| e.0.is_some()) {97			new_bindings.insert(98				name.as_ref().unwrap().clone(),99				LazyBinding::Bound(resolved_lazy_val!(val.clone())),100			);101		}102		for (i, param) in self.params.0.iter().enumerate() {103			if let Some((None, val)) = args.get(i) {104				new_bindings.insert(105					param.0.clone(),106					LazyBinding::Bound(resolved_lazy_val!(val.clone())),107				);108			}109		}110		let ctx = self111			.ctx112			.extend(new_bindings, None, None, None)?113			.into_future(future_ctx);114		self.eval_rhs.0(ctx)115	}116}117118#[derive(Debug)]119pub enum ValType {120	Bool,121	Null,122	Str,123	Num,124	Arr,125	Obj,126	Func,127}128impl ValType {129	pub fn name(&self) -> &'static str {130		use ValType::*;131		match self {132			Bool => "boolean",133			Null => "null",134			Str => "string",135			Num => "number",136			Arr => "array",137			Obj => "object",138			Func => "function",139		}140	}141}142impl Display for ValType {143	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {144		write!(f, "{}", self.name())145	}146}147148#[derive(Debug, PartialEq, Clone)]149pub enum Val {150	Bool(bool),151	Null,152	Str(String),153	Num(f64),154	Lazy(LazyVal),155	Arr(Vec<Val>),156	Obj(ObjValue),157	Func(FuncDesc),158159	// Library functions implemented in native160	Intristic(String, String),161}162impl Val {163	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {164		match self.unwrap_if_lazy()? {165			Val::Bool(v) => Ok(v),166			v => create_error(Error::TypeMismatch(167				context,168				vec![ValType::Bool],169				v.value_type()?,170			)),171		}172	}173	pub fn try_cast_str(self, context: &'static str) -> Result<String> {174		match self.unwrap_if_lazy()? {175			Val::Str(v) => Ok(v),176			v => create_error(Error::TypeMismatch(177				context,178				vec![ValType::Str],179				v.value_type()?,180			)),181		}182	}183	pub fn unwrap_if_lazy(self) -> Result<Self> {184		Ok(if let Val::Lazy(v) = self {185			v.evaluate()?.unwrap_if_lazy()?186		} else {187			self188		})189	}190	pub fn value_type(&self) -> Result<ValType> {191		Ok(match self {192			Val::Str(..) => ValType::Str,193			Val::Num(..) => ValType::Num,194			Val::Arr(..) => ValType::Arr,195			Val::Obj(..) => ValType::Obj,196			Val::Func(..) => ValType::Func,197			Val::Bool(_) => ValType::Bool,198			Val::Null => ValType::Null,199			Val::Intristic(_, _) => ValType::Func,200			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,201		})202	}203}