git.delta.rocks / jrsonnet / refs/commits / 1cc9e6c67fda

difftreelog

feat object assertions

Yaroslav Bolyukin2021-05-23parent: #0ec1408.patch.diff
in: master

6 files changed

modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -85,6 +85,10 @@
 		self.extend(new_bindings, None, None, None)
 	}
 
+	pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
+		self.extend(FxHashMap::default(), None, Some(new_this), new_super_obj)
+	}
+
 	pub fn extend(
 		self,
 		new_bindings: FxHashMap<IStr, LazyVal>,
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -261,6 +261,7 @@
 	}
 
 	let mut new_members = FxHashMap::default();
+	let mut assertions = Vec::new();
 	for member in members.iter() {
 		match member {
 			Member::Field(FieldMember {
@@ -325,10 +326,12 @@
 				);
 			}
 			Member::BindStmt(_) => {}
-			Member::AssertStmt(_) => {}
+			Member::AssertStmt(stmt) => {
+				assertions.push(stmt.clone());
+			}
 		}
 	}
-	let this = ObjValue::new(None, Rc::new(new_members));
+	let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(assertions));
 	future_this.fill(this.clone());
 	Ok(this)
 }
@@ -385,7 +388,7 @@
 				}
 			}
 
-			let this = ObjValue::new(None, Rc::new(new_members));
+			let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(Vec::new()));
 			future_this.fill(this.clone());
 			this
 		}
@@ -413,6 +416,36 @@
 	})
 }
 
+pub fn evaluate_assert(
+	context: Context,
+	assertion: &AssertStmt,
+) -> Result<()> {
+	let value = &assertion.0;
+	let msg = &assertion.1;
+	let assertion_result = push(
+		value.1.as_ref(),
+		|| "assertion condition".to_owned(),
+		|| {
+			evaluate(context.clone(), value)?
+				.try_cast_bool("assertion condition should be of type `boolean`")
+		},
+	)?;
+	if !assertion_result {
+		push(
+			value.1.as_ref(),
+			|| "assertion failure".to_owned(),
+			|| {
+				if let Some(msg) = msg {
+					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));
+				} else {
+					throw!(AssertionFailed(Val::Null.to_string()?));
+				}
+			},
+		)?
+	}
+	Ok(())
+}
+
 pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
 	use Expr::*;
 	let LocExpr(expr, _loc) = lexpr;
@@ -552,30 +585,9 @@
 			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
 		}
 		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),
-		AssertExpr(AssertStmt(value, msg), returned) => {
-			let assertion_result = push(
-				value.1.as_ref(),
-				|| "assertion condition".to_owned(),
-				|| {
-					evaluate(context.clone(), value)?
-						.try_cast_bool("assertion condition should be of type `boolean`")
-				},
-			)?;
-			if assertion_result {
-				evaluate(context, returned)?
-			} else {
-				push(
-					value.1.as_ref(),
-					|| "assertion failure".to_owned(),
-					|| {
-						if let Some(msg) = msg {
-							throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));
-						} else {
-							throw!(AssertionFailed(Val::Null.to_string()?));
-						}
-					},
-				)?
-			}
+		AssertExpr(assert, returned) => {
+			evaluate_assert(context.clone(), &assert)?;
+			evaluate(context, returned)?
 		}
 		ErrorStmt(e) => push(
 			loc.as_ref(),
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,4 +1,5 @@
 use crate::{
+	Context,
 	error::{Error::*, LocError, Result},
 	throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
 };
@@ -76,7 +77,7 @@
 						},
 					);
 				}
-				Self::Obj(ObjValue::new(None, Rc::new(entries)))
+				Self::Obj(ObjValue::new(Context::new(), None, Rc::new(entries), Rc::new(Vec::new())))
 			}
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/obj.rs
1use crate::{Context, evaluate_add_op, evaluate_assert, LazyBinding, Result, Val};2use jrsonnet_interner::IStr;3use jrsonnet_parser::{ExprLocation, LocExpr, Visibility, AssertStmt};4use rustc_hash::{FxHashMap, FxHashSet};5use std::hash::{Hash, Hasher};6use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};78#[derive(Debug)]9pub struct ObjMember {10	pub add: bool,11	pub visibility: Visibility,12	pub invoke: LazyBinding,13	pub location: Option<ExprLocation>,14}1516// Field => This17type CacheKey = (IStr, ObjValue);18#[derive(Debug)]19pub struct ObjValueInternals {20	context: Context,21	super_obj: Option<ObjValue>,22	assertions: Rc<Vec<AssertStmt>>,23	assertions_ran: RefCell<FxHashSet<ObjValue>>,24	this_obj: Option<ObjValue>,25	this_entries: Rc<FxHashMap<IStr, ObjMember>>,26	value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,27}2829#[derive(Clone)]30pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);31impl Debug for ObjValue {32	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {33		if let Some(super_obj) = self.0.super_obj.as_ref() {34			if f.alternate() {35				write!(f, "{:#?}", super_obj)?;36			} else {37				write!(f, "{:?}", super_obj)?;38			}39			write!(f, " + ")?;40		}41		let mut debug = f.debug_struct("ObjValue");42		for (name, member) in self.0.this_entries.iter() {43			debug.field(name, member);44		}45		#[cfg(feature = "unstable")]46		{47			debug.finish_non_exhaustive()48		}49		#[cfg(not(feature = "unstable"))]50		{51			debug.finish()52		}53	}54}5556impl ObjValue {57	pub fn new(context: Context, super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>, assertions: Rc<Vec<AssertStmt>>) -> Self {58		Self(Rc::new(ObjValueInternals {59			context,60			super_obj,61			assertions,62			assertions_ran: RefCell::new(FxHashSet::default()),63			this_obj: None,64			this_entries,65			value_cache: RefCell::new(FxHashMap::default()),66		}))67	}68	pub fn new_empty() -> Self {69		Self::new(Context::new(), None, Rc::new(FxHashMap::default()), Rc::new(Vec::new()))70	}71	pub fn extend_from(&self, super_obj: Self) -> Self {72		match &self.0.super_obj {73			None => Self::new(self.0.context.clone(), Some(super_obj), self.0.this_entries.clone(), self.0.assertions.clone()),74			Some(v) => Self::new(self.0.context.clone(), Some(v.extend_from(super_obj)), self.0.this_entries.clone(), self.0.assertions.clone()),75		}76	}77	pub fn with_this(&self, this_obj: Self) -> Self {78		Self(Rc::new(ObjValueInternals {79			context: self.0.context.clone(),80			super_obj: self.0.super_obj.clone(),81			assertions: self.0.assertions.clone(),82			assertions_ran: RefCell::new(FxHashSet::default()),83			this_obj: Some(this_obj),84			this_entries: self.0.this_entries.clone(),85			value_cache: RefCell::new(FxHashMap::default()),86		}))87	}8889	/// Run callback for every field found in object90	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {91		if let Some(s) = &self.0.super_obj {92			if s.enum_fields(handler) {93				return true;94			}95		}96		for (name, member) in self.0.this_entries.iter() {97			if handler(name, &member.visibility) {98				return true;99			}100		}101		false102	}103104	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {105		let mut out = FxHashMap::default();106		self.enum_fields(&mut |name, visibility| {107			match visibility {108				Visibility::Normal => {109					let entry = out.entry(name.to_owned());110					entry.or_insert(true);111				}112				Visibility::Hidden => {113					out.insert(name.to_owned(), false);114				}115				Visibility::Unhide => {116					out.insert(name.to_owned(), true);117				}118			};119			false120		});121		out122	}123	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {124		let mut fields: Vec<_> = self125			.fields_visibility()126			.into_iter()127			.filter(|(_k, v)| include_hidden || *v)128			.map(|(k, _)| k)129			.collect();130		fields.sort_unstable();131		fields132	}133	pub fn fields(&self) -> Vec<IStr> {134		self.fields_ex(false)135	}136137	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {138		if let Some(m) = self.0.this_entries.get(&name) {139			Some(match &m.visibility {140				Visibility::Normal => self141					.0142					.super_obj143					.as_ref()144					.and_then(|super_obj| super_obj.field_visibility(name))145					.unwrap_or(Visibility::Normal),146				v => *v,147			})148		} else if let Some(super_obj) = &self.0.super_obj {149			super_obj.field_visibility(name)150		} else {151			None152		}153	}154155	fn has_field_include_hidden(&self, name: IStr) -> bool {156		if self.0.this_entries.contains_key(&name) {157			true158		} else if let Some(super_obj) = &self.0.super_obj {159			super_obj.has_field_include_hidden(name)160		} else {161			false162		}163	}164165	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {166		if include_hidden {167			self.has_field_include_hidden(name)168		} else {169			self.has_field(name)170		}171	}172	pub fn has_field(&self, name: IStr) -> bool {173		self.field_visibility(name)174			.map(|v| v.is_visible())175			.unwrap_or(false)176	}177178	pub fn get(&self, key: IStr) -> Result<Option<Val>> {179		self.run_assertions(self.0.this_obj.as_ref().unwrap_or(self))?;180		self.get_raw(key, self.0.this_obj.as_ref())181	}182183	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {184		let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());185		new.insert(key, value);186		Self::new(Context::new(), Some(self), Rc::new(new), Rc::new(Vec::new()))187	}188189	pub fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {190		let real_this = real_this.unwrap_or(self);191		let cache_key = (key.clone(), real_this.clone());192193		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {194			return Ok(v.clone());195		}196		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {197			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),198			(Some(k), Some(s)) => {199				let our = self.evaluate_this(k, real_this)?;200				if k.add {201					s.get_raw(key, Some(real_this))?202						.map_or(Ok(Some(our.clone())), |v| {203							Ok(Some(evaluate_add_op(&v, &our)?))204						})205				} else {206					Ok(Some(our))207				}208			}209			(None, Some(s)) => s.get_raw(key, Some(real_this)),210			(None, None) => Ok(None),211		}?;212		self.0213			.value_cache214			.borrow_mut()215			.insert(cache_key, value.clone());216		Ok(value)217	}218	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {219		v.invoke220			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?221			.evaluate()222	}223	fn run_assertions(&self, real_this: &Self) -> Result<()> {224		if self.0.assertions_ran.borrow().contains(&real_this) {225			// Assertions already ran226		} else {227			self.0.assertions_ran.borrow_mut().insert(real_this.clone());228			for assertion in self.0.assertions.iter() {229				println!("{:#?}", assertion);230				if let Err(e) = evaluate_assert(self.0.context.clone().with_this_super(real_this.clone(), self.0.super_obj.clone()), &assertion) {231					self.0.assertions_ran.borrow_mut().remove(&real_this);232					return Err(e)233				}234			}235			if let Some(super_obj) = &self.0.super_obj {236				super_obj.run_assertions(&real_this)?;237			}238		}239		Ok(())240	}241242	pub fn ptr_eq(a: &Self, b: &Self) -> bool {243		Rc::ptr_eq(&a.0, &b.0)244	}245}246247impl PartialEq for ObjValue {248	fn eq(&self, other: &Self) -> bool {249		Rc::ptr_eq(&self.0, &other.0)250	}251}252253impl Eq for ObjValue {}254impl Hash for ObjValue {255	fn hash<H: Hasher>(&self, state: &mut H) {256		state.write_usize(Rc::as_ptr(&self.0) as usize)257	}258}
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -40,7 +40,7 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -12,7 +12,7 @@
           pname = "jrsonnet";
           version = "0.1.0";
           src = self;
-          cargoSha256 = "sha256-5RzjO9McVqG8+1+p+wRvygYCnemPjUAVB9TpWOp2ipA=";
+          cargoSha256 = "sha256-6VhaQi3L2LWzR0cq7oRG81MDbrKJbzSNPcvYSoQ5ISo=";
         };
       in { defaultPackage = jrsonnet; });
 }