difftreelog
feat object assertions
in: master
6 files changed
crates/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>,
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth261 }261 }262262263 let mut new_members = FxHashMap::default();263 let mut new_members = FxHashMap::default();264 let mut assertions = Vec::new();264 for member in members.iter() {265 for member in members.iter() {265 match member {266 match member {266 Member::Field(FieldMember {267 Member::Field(FieldMember {325 );326 );326 }327 }327 Member::BindStmt(_) => {}328 Member::BindStmt(_) => {}328 Member::AssertStmt(_) => {}329 Member::AssertStmt(stmt) => {330 assertions.push(stmt.clone());331 }329 }332 }330 }333 }331 let this = ObjValue::new(None, Rc::new(new_members));334 let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(assertions));332 future_this.fill(this.clone());335 future_this.fill(this.clone());333 Ok(this)336 Ok(this)334}337}385 }388 }386 }389 }387390388 let this = ObjValue::new(None, Rc::new(new_members));391 let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(Vec::new()));389 future_this.fill(this.clone());392 future_this.fill(this.clone());390 this393 this391 }394 }413 })416 })414}417}418419pub fn evaluate_assert(420 context: Context,421 assertion: &AssertStmt,422) -> Result<()> {423 let value = &assertion.0;424 let msg = &assertion.1;425 let assertion_result = push(426 value.1.as_ref(),427 || "assertion condition".to_owned(),428 || {429 evaluate(context.clone(), value)?430 .try_cast_bool("assertion condition should be of type `boolean`")431 },432 )?;433 if !assertion_result {434 push(435 value.1.as_ref(),436 || "assertion failure".to_owned(),437 || {438 if let Some(msg) = msg {439 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));440 } else {441 throw!(AssertionFailed(Val::Null.to_string()?));442 }443 },444 )?445 }446 Ok(())447}415448416pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {449pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {417 use Expr::*;450 use Expr::*;552 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())585 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())553 }586 }554 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),587 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),555 AssertExpr(AssertStmt(value, msg), returned) => {588 AssertExpr(assert, returned) => {556 let assertion_result = push(589 evaluate_assert(context.clone(), &assert)?;557 value.1.as_ref(),558 || "assertion condition".to_owned(),559 || {560 evaluate(context.clone(), value)?561 .try_cast_bool("assertion condition should be of type `boolean`")562 },563 )?;564 if assertion_result {565 evaluate(context, returned)?590 evaluate(context, returned)?566 } else {567 push(568 value.1.as_ref(),569 || "assertion failure".to_owned(),570 || {571 if let Some(msg) = msg {572 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));573 } else {574 throw!(AssertionFailed(Val::Null.to_string()?));575 }576 },577 )?578 }579 }591 }580 ErrorStmt(e) => push(592 ErrorStmt(e) => push(581 loc.as_ref(),593 loc.as_ref(),crates/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())))
}
}
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,7 +1,7 @@
-use crate::{evaluate_add_op, LazyBinding, Result, Val};
+use crate::{Context, evaluate_add_op, evaluate_assert, LazyBinding, Result, Val};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ExprLocation, Visibility};
-use rustc_hash::FxHashMap;
+use jrsonnet_parser::{ExprLocation, LocExpr, Visibility, AssertStmt};
+use rustc_hash::{FxHashMap, FxHashSet};
use std::hash::{Hash, Hasher};
use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};
@@ -17,7 +17,10 @@
type CacheKey = (IStr, ObjValue);
#[derive(Debug)]
pub struct ObjValueInternals {
+ context: Context,
super_obj: Option<ObjValue>,
+ assertions: Rc<Vec<AssertStmt>>,
+ assertions_ran: RefCell<FxHashSet<ObjValue>>,
this_obj: Option<ObjValue>,
this_entries: Rc<FxHashMap<IStr, ObjMember>>,
value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,
@@ -51,26 +54,32 @@
}
impl ObjValue {
- pub fn new(super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>) -> Self {
+ pub fn new(context: Context, super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>, assertions: Rc<Vec<AssertStmt>>) -> Self {
Self(Rc::new(ObjValueInternals {
+ context,
super_obj,
+ assertions,
+ assertions_ran: RefCell::new(FxHashSet::default()),
this_obj: None,
this_entries,
value_cache: RefCell::new(FxHashMap::default()),
}))
}
pub fn new_empty() -> Self {
- Self::new(None, Rc::new(FxHashMap::default()))
+ Self::new(Context::new(), None, Rc::new(FxHashMap::default()), Rc::new(Vec::new()))
}
pub fn extend_from(&self, super_obj: Self) -> Self {
match &self.0.super_obj {
- None => Self::new(Some(super_obj), self.0.this_entries.clone()),
- Some(v) => Self::new(Some(v.extend_from(super_obj)), self.0.this_entries.clone()),
+ None => Self::new(self.0.context.clone(), Some(super_obj), self.0.this_entries.clone(), self.0.assertions.clone()),
+ Some(v) => Self::new(self.0.context.clone(), Some(v.extend_from(super_obj)), self.0.this_entries.clone(), self.0.assertions.clone()),
}
}
pub fn with_this(&self, this_obj: Self) -> Self {
Self(Rc::new(ObjValueInternals {
+ context: self.0.context.clone(),
super_obj: self.0.super_obj.clone(),
+ assertions: self.0.assertions.clone(),
+ assertions_ran: RefCell::new(FxHashSet::default()),
this_obj: Some(this_obj),
this_entries: self.0.this_entries.clone(),
value_cache: RefCell::new(FxHashMap::default()),
@@ -167,16 +176,17 @@
}
pub fn get(&self, key: IStr) -> Result<Option<Val>> {
+ self.run_assertions(self.0.this_obj.as_ref().unwrap_or(self))?;
self.get_raw(key, self.0.this_obj.as_ref())
}
pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {
let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
new.insert(key, value);
- Self::new(Some(self), Rc::new(new))
+ Self::new(Context::new(), Some(self), Rc::new(new), Rc::new(Vec::new()))
}
- pub(crate) fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
+ pub fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
let real_this = real_this.unwrap_or(self);
let cache_key = (key.clone(), real_this.clone());
@@ -210,6 +220,24 @@
.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
.evaluate()
}
+ fn run_assertions(&self, real_this: &Self) -> Result<()> {
+ if self.0.assertions_ran.borrow().contains(&real_this) {
+ // Assertions already ran
+ } else {
+ self.0.assertions_ran.borrow_mut().insert(real_this.clone());
+ for assertion in self.0.assertions.iter() {
+ println!("{:#?}", assertion);
+ if let Err(e) = evaluate_assert(self.0.context.clone().with_this_super(real_this.clone(), self.0.super_obj.clone()), &assertion) {
+ self.0.assertions_ran.borrow_mut().remove(&real_this);
+ return Err(e)
+ }
+ }
+ if let Some(super_obj) = &self.0.super_obj {
+ super_obj.run_assertions(&real_this)?;
+ }
+ }
+ Ok(())
+ }
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
Rc::ptr_eq(&a.0, &b.0)
crates/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))]
flake.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; });
}