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.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(),
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.rsdiffbeforeafterboth1use crate::{evaluate_add_op, LazyBinding, Result, Val};1use crate::{Context, evaluate_add_op, evaluate_assert, LazyBinding, Result, Val};2use jrsonnet_interner::IStr;2use jrsonnet_interner::IStr;3use jrsonnet_parser::{ExprLocation, Visibility};3use jrsonnet_parser::{ExprLocation, LocExpr, Visibility, AssertStmt};4use rustc_hash::FxHashMap;4use rustc_hash::{FxHashMap, FxHashSet};5use std::hash::{Hash, Hasher};5use std::hash::{Hash, Hasher};6use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};6use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};7717type CacheKey = (IStr, ObjValue);17type CacheKey = (IStr, ObjValue);18#[derive(Debug)]18#[derive(Debug)]19pub struct ObjValueInternals {19pub struct ObjValueInternals {20 context: Context,20 super_obj: Option<ObjValue>,21 super_obj: Option<ObjValue>,22 assertions: Rc<Vec<AssertStmt>>,23 assertions_ran: RefCell<FxHashSet<ObjValue>>,21 this_obj: Option<ObjValue>,24 this_obj: Option<ObjValue>,22 this_entries: Rc<FxHashMap<IStr, ObjMember>>,25 this_entries: Rc<FxHashMap<IStr, ObjMember>>,23 value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,26 value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,51}54}525553impl ObjValue {56impl ObjValue {54 pub fn new(super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>) -> Self {57 pub fn new(context: Context, super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>, assertions: Rc<Vec<AssertStmt>>) -> Self {55 Self(Rc::new(ObjValueInternals {58 Self(Rc::new(ObjValueInternals {59 context,56 super_obj,60 super_obj,61 assertions,62 assertions_ran: RefCell::new(FxHashSet::default()),57 this_obj: None,63 this_obj: None,58 this_entries,64 this_entries,59 value_cache: RefCell::new(FxHashMap::default()),65 value_cache: RefCell::new(FxHashMap::default()),60 }))66 }))61 }67 }62 pub fn new_empty() -> Self {68 pub fn new_empty() -> Self {63 Self::new(None, Rc::new(FxHashMap::default()))69 Self::new(Context::new(), None, Rc::new(FxHashMap::default()), Rc::new(Vec::new()))64 }70 }65 pub fn extend_from(&self, super_obj: Self) -> Self {71 pub fn extend_from(&self, super_obj: Self) -> Self {66 match &self.0.super_obj {72 match &self.0.super_obj {67 None => Self::new(Some(super_obj), self.0.this_entries.clone()),73 None => Self::new(self.0.context.clone(), Some(super_obj), self.0.this_entries.clone(), self.0.assertions.clone()),68 Some(v) => Self::new(Some(v.extend_from(super_obj)), self.0.this_entries.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()),69 }75 }70 }76 }71 pub fn with_this(&self, this_obj: Self) -> Self {77 pub fn with_this(&self, this_obj: Self) -> Self {72 Self(Rc::new(ObjValueInternals {78 Self(Rc::new(ObjValueInternals {79 context: self.0.context.clone(),73 super_obj: self.0.super_obj.clone(),80 super_obj: self.0.super_obj.clone(),81 assertions: self.0.assertions.clone(),82 assertions_ran: RefCell::new(FxHashSet::default()),74 this_obj: Some(this_obj),83 this_obj: Some(this_obj),75 this_entries: self.0.this_entries.clone(),84 this_entries: self.0.this_entries.clone(),76 value_cache: RefCell::new(FxHashMap::default()),85 value_cache: RefCell::new(FxHashMap::default()),167 }176 }168177169 pub fn get(&self, key: IStr) -> Result<Option<Val>> {178 pub fn get(&self, key: IStr) -> Result<Option<Val>> {179 self.run_assertions(self.0.this_obj.as_ref().unwrap_or(self))?;170 self.get_raw(key, self.0.this_obj.as_ref())180 self.get_raw(key, self.0.this_obj.as_ref())171 }181 }172182173 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {183 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {174 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());184 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());175 new.insert(key, value);185 new.insert(key, value);176 Self::new(Some(self), Rc::new(new))186 Self::new(Context::new(), Some(self), Rc::new(new), Rc::new(Vec::new()))177 }187 }178188179 pub(crate) fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {189 pub fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {180 let real_this = real_this.unwrap_or(self);190 let real_this = real_this.unwrap_or(self);181 let cache_key = (key.clone(), real_this.clone());191 let cache_key = (key.clone(), real_this.clone());182192210 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?220 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?211 .evaluate()221 .evaluate()212 }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 }213241214 pub fn ptr_eq(a: &Self, b: &Self) -> bool {242 pub fn ptr_eq(a: &Self, b: &Self) -> bool {215 Rc::ptr_eq(&a.0, &b.0)243 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; });
}