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
1use crate::{1use crate::{
2 binding, context_creator, create_error, function_default, function_rhs, future_wrapper,2 binding, context_creator, create_error, function_default, function_rhs, future_wrapper,
3 lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,3 lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue,
4 ObjValue, Result, Val,4 Result, Val,
5};5};
6use closure::closure;6use closure::closure;
19 let args = args.clone();19 let args = args.clone();
20 (20 (
21 b.name.clone(),21 b.name.clone(),
22 lazy_binding!(move |this, super_obj| Ok(lazy_val!(22 LazyBinding::Bindable(Rc::new(move |this, super_obj| {
23 Ok(lazy_val!(
23 closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(24 closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(
24 context_creator.0(this.clone(), super_obj.clone())?,25 context_creator.0(this.clone(), super_obj.clone())?,
25 &b.value,26 &b.value,
26 args.clone()27 args.clone()
27 )))28 )))
28 ))),29 ))
30 })),
29 )31 )
30 } else {32 } else {
31 (33 (
32 b.name.clone(),34 b.name.clone(),
33 lazy_binding!(move |this, super_obj| {35 LazyBinding::Bindable(Rc::new(move |this, super_obj| {
34 Ok(lazy_val!(closure!(clone context_creator, clone b, ||36 Ok(lazy_val!(closure!(clone context_creator, clone b, ||
35 push(b.value.clone(), "thunk".to_owned(), ||{37 push(b.value.clone(), "thunk".to_owned(), ||{
36 evaluate(38 evaluate(
39 )41 )
40 })42 })
41 )))43 )))
42 }),44 })),
43 )45 )
44 }46 }
45}47}
405 &evaluate(context.clone(), s)?,407 &evaluate(context.clone(), s)?,
406 &Val::Obj(evaluate_object(context, t.clone())?),408 &Val::Obj(evaluate_object(context, t.clone())?),
407 )?,409 )?,
408 Apply(value, ArgsDesc(args)) => {410 Apply(value, ArgsDesc(args), tailstrict) => {
409 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;411 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;
410 match value {412 match value {
411 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {413 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {
502 evaluate(context.clone(), &args[0].1)?,504 evaluate(context.clone(), &args[0].1)?,
503 evaluate(context, &args[1].1)?,505 evaluate(context, &args[1].1)?,
504 ) {506 ) {
507 // TODO: Line numbers as in original jsonnet
505 println!("{}", a);508 println!("TRACE: {}", a);
506 b509 b
507 } else {510 } else {
508 panic!("bad trace call");511 panic!("bad trace call");
517 .map(move |a| {520 .map(move |a| {
518 (521 (
519 a.clone().0,522 a.clone().0,
523 if *tailstrict {
524 Val::Lazy(LazyVal::new_resolved(
525 evaluate(context.clone(), &a.1).unwrap(),
526 ))
527 } else {
520 Val::Lazy(lazy_val!(528 Val::Lazy(lazy_val!(
521 closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))529 closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))
522 )),530 ))
531 },
523 )532 )
524 })533 })
525 .collect(),534 .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())),
 				);
 			}
 		}