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
before · crates/jsonnet-evaluator/src/ctx.rs
1use crate::{2	future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Result,3	Val,4};5use closure::closure;6use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};78rc_fn_helper!(9	ContextCreator,10	context_creator,11	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>12);1314future_wrapper!(Context, FutureContext);1516#[derive(Debug)]17struct ContextInternals {18	dollar: Option<ObjValue>,19	this: Option<ObjValue>,20	super_obj: Option<ObjValue>,21	bindings: Rc<HashMap<String, LazyVal>>,22}23pub struct Context(Rc<ContextInternals>);24impl Debug for Context {25	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {26		f.debug_struct("Context")27			.field("this", &self.0.this.clone().map(|e| Rc::as_ptr(&e.0)))28			.finish()29	}30}31impl Context {32	pub fn new_future() -> FutureContext {33		FutureContext(Rc::new(RefCell::new(None)))34	}3536	pub fn dollar(&self) -> &Option<ObjValue> {37		&self.0.dollar38	}3940	pub fn this(&self) -> &Option<ObjValue> {41		&self.0.this42	}4344	pub fn super_obj(&self) -> &Option<ObjValue> {45		&self.0.super_obj46	}4748	pub fn new() -> Context {49		Context(Rc::new(ContextInternals {50			dollar: None,51			this: None,52			super_obj: None,53			bindings: Rc::new(HashMap::new()),54		}))55	}5657	pub fn binding(&self, name: &str) -> LazyVal {58		self.0.bindings.get(name).cloned().unwrap_or_else(|| {59			panic!("can't find {} in {:?}", name, self);60		})61	}62	pub fn into_future(self, ctx: FutureContext) -> Context {63		{64			ctx.0.borrow_mut().replace(self);65		}66		ctx.unwrap()67	}6869	pub fn with_var(&self, name: String, value: Val) -> Result<Context> {70		let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();71		new_bindings.insert(72			name,73			lazy_binding!(74				closure!(clone value, |_t, _s|Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))75			),76		);77		self.extend(new_bindings, None, None, None)78	}7980	pub fn extend(81		&self,82		new_bindings: HashMap<String, LazyBinding>,83		new_dollar: Option<ObjValue>,84		new_this: Option<ObjValue>,85		new_super_obj: Option<ObjValue>,86	) -> Result<Context> {87		let dollar = new_dollar.or_else(|| self.0.dollar.clone());88		let this = new_this.or_else(|| self.0.this.clone());89		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());90		let bindings = if new_bindings.is_empty() {91			self.0.bindings.clone()92		} else {93			let mut new = HashMap::new(); // = self.0.bindings.clone();94			for (k, v) in self.0.bindings.iter() {95				new.insert(k.clone(), v.clone());96			}97			for (k, v) in new_bindings.into_iter() {98				new.insert(k, v.0(this.clone(), super_obj.clone())?);99			}100			Rc::new(new)101		};102		Ok(Context(Rc::new(ContextInternals {103			dollar,104			this,105			super_obj,106			bindings,107		})))108	}109}110111impl Default for Context {112	fn default() -> Self {113		Self::new()114	}115}116117impl PartialEq for Context {118	fn eq(&self, other: &Self) -> bool {119		Rc::ptr_eq(&self.0, &other.0)120	}121}122123impl Clone for Context {124	fn clone(&self) -> Self {125		Context(self.0.clone())126	}127}
after · crates/jsonnet-evaluator/src/ctx.rs
1use crate::{2	future_wrapper, rc_fn_helper, resolved_lazy_val, LazyBinding, LazyVal, ObjValue, Result, Val,3};4use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};56rc_fn_helper!(7	ContextCreator,8	context_creator,9	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>10);1112future_wrapper!(Context, FutureContext);1314#[derive(Debug)]15struct ContextInternals {16	dollar: Option<ObjValue>,17	this: Option<ObjValue>,18	super_obj: Option<ObjValue>,19	bindings: Rc<HashMap<String, LazyVal>>,20}21pub struct Context(Rc<ContextInternals>);22impl Debug for Context {23	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {24		f.debug_struct("Context")25			.field("this", &self.0.this.clone().map(|e| Rc::as_ptr(&e.0)))26			.finish()27	}28}29impl Context {30	pub fn new_future() -> FutureContext {31		FutureContext(Rc::new(RefCell::new(None)))32	}3334	pub fn dollar(&self) -> &Option<ObjValue> {35		&self.0.dollar36	}3738	pub fn this(&self) -> &Option<ObjValue> {39		&self.0.this40	}4142	pub fn super_obj(&self) -> &Option<ObjValue> {43		&self.0.super_obj44	}4546	pub fn new() -> Context {47		Context(Rc::new(ContextInternals {48			dollar: None,49			this: None,50			super_obj: None,51			bindings: Rc::new(HashMap::new()),52		}))53	}5455	pub fn binding(&self, name: &str) -> LazyVal {56		self.0.bindings.get(name).cloned().unwrap_or_else(|| {57			panic!("can't find {} in {:?}", name, self);58		})59	}60	pub fn into_future(self, ctx: FutureContext) -> Context {61		{62			ctx.0.borrow_mut().replace(self);63		}64		ctx.unwrap()65	}6667	pub fn with_var(&self, name: String, value: Val) -> Result<Context> {68		let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();69		new_bindings.insert(name, LazyBinding::Bound(resolved_lazy_val!(value.clone())));70		self.extend(new_bindings, None, None, None)71	}7273	pub fn extend(74		&self,75		new_bindings: HashMap<String, LazyBinding>,76		new_dollar: Option<ObjValue>,77		new_this: Option<ObjValue>,78		new_super_obj: Option<ObjValue>,79	) -> Result<Context> {80		let dollar = new_dollar.or_else(|| self.0.dollar.clone());81		let this = new_this.or_else(|| self.0.this.clone());82		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());83		let bindings = if new_bindings.is_empty() {84			self.0.bindings.clone()85		} else {86			let mut new = HashMap::new(); // = self.0.bindings.clone();87			for (k, v) in self.0.bindings.iter() {88				new.insert(k.clone(), v.clone());89			}90			for (k, v) in new_bindings.into_iter() {91				new.insert(k, v.evaluate(this.clone(), super_obj.clone())?);92			}93			Rc::new(new)94		};95		Ok(Context(Rc::new(ContextInternals {96			dollar,97			this,98			super_obj,99			bindings,100		})))101	}102}103104impl Default for Context {105	fn default() -> Self {106		Self::new()107	}108}109110impl PartialEq for Context {111	fn eq(&self, other: &Self) -> bool {112		Rc::ptr_eq(&self.0, &other.0)113	}114}115116impl Clone for Context {117	fn clone(&self) -> Self {118		Context(self.0.clone())119	}120}
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
--- a/crates/jsonnet-evaluator/src/val.rs
+++ b/crates/jsonnet-evaluator/src/val.rs
@@ -1,6 +1,5 @@
 use crate::{
-	create_error, lazy_binding, Context, Error, FunctionDefault, FunctionRhs, LazyBinding,
-	ObjValue, Result,
+	create_error, Context, Error, FunctionDefault, FunctionRhs, LazyBinding, ObjValue, Result,
 };
 use closure::closure;
 use jsonnet_parser::{Param, ParamsDesc};
@@ -12,7 +11,7 @@
 };
 
 struct LazyValInternals {
-	pub f: Box<dyn Fn() -> Result<Val>>,
+	pub f: Option<Box<dyn Fn() -> Result<Val>>>,
 	pub cached: RefCell<Option<Val>>,
 }
 #[derive(Clone)]
@@ -20,10 +19,16 @@
 impl LazyVal {
 	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
 		LazyVal(Rc::new(LazyValInternals {
-			f,
+			f: Some(f),
 			cached: RefCell::new(None),
 		}))
 	}
+	pub fn new_resolved(val: Val) -> Self {
+		LazyVal(Rc::new(LazyValInternals {
+			f: None,
+			cached: RefCell::new(Some(val)),
+		}))
+	}
 	pub fn evaluate(&self) -> Result<Val> {
 		{
 			let cached = self.0.cached.borrow();
@@ -31,17 +36,24 @@
 				return Ok(cached.clone().unwrap());
 			}
 		}
-		let result = (self.0.f)()?;
+		let result = (self.0.f.as_ref().unwrap())()?;
 		self.0.cached.borrow_mut().replace(result.clone());
 		Ok(result)
 	}
 }
+
 #[macro_export]
 macro_rules! lazy_val {
 	($f: expr) => {
 		$crate::LazyVal::new(Box::new($f))
 	};
 }
+#[macro_export]
+macro_rules! resolved_lazy_val {
+	($f: expr) => {
+		$crate::LazyVal::new_resolved($f)
+	};
+}
 impl Debug for LazyVal {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		if self.0.cached.borrow().is_some() {
@@ -75,25 +87,23 @@
 			let eval_default = self.eval_default.clone();
 			new_bindings.insert(
 				name,
-				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()).0
-					(future_ctx.clone().unwrap(), default.clone())))))),
+				LazyBinding::Bound(lazy_val!(
+					closure!(clone future_ctx, clone eval_default, clone default, || (eval_default.clone()).0
+					(future_ctx.clone().unwrap(), default.clone()))
+				)),
 			);
 		}
 		for (name, val) in args.clone().into_iter().filter(|e| e.0.is_some()) {
 			new_bindings.insert(
 				name.as_ref().unwrap().clone(),
-				lazy_binding!(
-					closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
-				),
+				LazyBinding::Bound(resolved_lazy_val!(val.clone())),
 			);
 		}
 		for (i, param) in self.params.0.iter().enumerate() {
 			if let Some((None, val)) = args.get(i) {
 				new_bindings.insert(
 					param.0.clone(),
-					lazy_binding!(
-						closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
-					),
+					LazyBinding::Bound(resolved_lazy_val!(val.clone())),
 				);
 			}
 		}