git.delta.rocks / jrsonnet / refs/commits / 9b331948fca2

difftreelog

feat(evaluator) Err instead of panic on unknown variable

Лач2020-06-25parent: #012ef80.patch.diff
in: master

3 files changed

modifiedcrates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
before · crates/jsonnet-evaluator/src/ctx.rs
1use crate::{2	future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val, LazyBinding, LazyVal,3	ObjValue, Result, Val,4};5use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};67rc_fn_helper!(8	ContextCreator,9	context_creator,10	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>11);1213future_wrapper!(Context, FutureContext);1415struct ContextInternals {16	dollar: Option<ObjValue>,17	this: Option<ObjValue>,18	super_obj: Option<ObjValue>,19	bindings: LayeredHashMap<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: LayeredHashMap::default(),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::with_capacity(1);69		new_bindings.insert(name, resolved_lazy_val!(value));70		self.extend(new_bindings, None, None, None)71	}7273	pub fn extend(74		&self,75		new_bindings: HashMap<String, LazyVal>,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			self.0.bindings.extend(new_bindings)87		};88		Ok(Context(Rc::new(ContextInternals {89			dollar,90			this,91			super_obj,92			bindings,93		})))94	}95	pub fn extend_unbound(96		&self,97		new_bindings: HashMap<String, LazyBinding>,98		new_dollar: Option<ObjValue>,99		new_this: Option<ObjValue>,100		new_super_obj: Option<ObjValue>,101	) -> Result<Context> {102		let this = new_this.or_else(|| self.0.this.clone());103		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());104		let mut new = HashMap::with_capacity(new_bindings.len());105		for (k, v) in new_bindings.into_iter() {106			new.insert(k, v.evaluate(this.clone(), super_obj.clone())?);107		}108		self.extend(new, new_dollar, this, super_obj)109	}110}111112impl Default for Context {113	fn default() -> Self {114		Self::new()115	}116}117118impl PartialEq for Context {119	fn eq(&self, other: &Self) -> bool {120		Rc::ptr_eq(&self.0, &other.0)121	}122}123124impl Clone for Context {125	fn clone(&self) -> Self {126		Context(self.0.clone())127	}128}
after · crates/jsonnet-evaluator/src/ctx.rs
1use crate::{2	future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val, LazyBinding, LazyVal,3	ObjValue, Result, Val,4};5use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};67rc_fn_helper!(8	ContextCreator,9	context_creator,10	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>11);1213future_wrapper!(Context, FutureContext);1415struct ContextInternals {16	dollar: Option<ObjValue>,17	this: Option<ObjValue>,18	super_obj: Option<ObjValue>,19	bindings: LayeredHashMap<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: LayeredHashMap::default(),52		}))53	}5455	pub fn binding(&self, name: &str) -> Result<LazyVal> {56		self.0.bindings.get(name).cloned().ok_or_else(|| {57			create_error::<()>(Error::UnknownVariable(name.to_owned()))58				.err()59				.unwrap()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::with_capacity(1);71		new_bindings.insert(name, resolved_lazy_val!(value));72		self.extend(new_bindings, None, None, None)73	}7475	pub fn extend(76		&self,77		new_bindings: HashMap<String, LazyVal>,78		new_dollar: Option<ObjValue>,79		new_this: Option<ObjValue>,80		new_super_obj: Option<ObjValue>,81	) -> Result<Context> {82		let dollar = new_dollar.or_else(|| self.0.dollar.clone());83		let this = new_this.or_else(|| self.0.this.clone());84		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());85		let bindings = if new_bindings.is_empty() {86			self.0.bindings.clone()87		} else {88			self.0.bindings.extend(new_bindings)89		};90		Ok(Context(Rc::new(ContextInternals {91			dollar,92			this,93			super_obj,94			bindings,95		})))96	}97	pub fn extend_unbound(98		&self,99		new_bindings: HashMap<String, LazyBinding>,100		new_dollar: Option<ObjValue>,101		new_this: Option<ObjValue>,102		new_super_obj: Option<ObjValue>,103	) -> Result<Context> {104		let this = new_this.or_else(|| self.0.this.clone());105		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());106		let mut new = HashMap::with_capacity(new_bindings.len());107		for (k, v) in new_bindings.into_iter() {108			new.insert(k, v.evaluate(this.clone(), super_obj.clone())?);109		}110		self.extend(new, new_dollar, this, super_obj)111	}112}113114impl Default for Context {115	fn default() -> Self {116		Self::new()117	}118}119120impl PartialEq for Context {121	fn eq(&self, other: &Self) -> bool {122		Rc::ptr_eq(&self.0, &other.0)123	}124}125126impl Clone for Context {127	fn clone(&self) -> Self {128		Context(self.0.clone())129	}130}
modifiedcrates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -7,6 +7,8 @@
 	TypeMismatch(&'static str, Vec<ValType>, ValType),
 	NoSuchField(String),
 
+	UnknownVariable(String),
+
 	UnknownFunctionParameter(String),
 	BindingParameterASecondTime(String),
 	TooManyArgsFunctionHas(usize),
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -397,7 +397,7 @@
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
 		Var(name) => push(locexpr, "var".to_owned(), || {
-			Val::Lazy(context.binding(&name)).unwrap_if_lazy()
+			Val::Lazy(context.binding(&name)?).unwrap_if_lazy()
 		})?,
 		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
 			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;