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
85 self.extend(new_bindings, None, None, None)85 self.extend(new_bindings, None, None, None)
86 }86 }
87
88 pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
89 self.extend(FxHashMap::default(), None, Some(new_this), new_super_obj)
90 }
8791
88 pub fn extend(92 pub fn extend(
89 self,93 self,
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
261 }261 }
262262
263 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 }
387390
388 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 this
391 }394 }
413 })416 })
414}417}
418
419pub 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}
415448
416pub 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(),
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
1use crate::{1use crate::{
2 Context,
2 error::{Error::*, LocError, Result},3 error::{Error::*, LocError, Result},
3 throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,4 throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
4};5};
76 },77 },
77 );78 );
78 }79 }
79 Self::Obj(ObjValue::new(None, Rc::new(entries)))80 Self::Obj(ObjValue::new(Context::new(), None, Rc::new(entries), Rc::new(Vec::new())))
80 }81 }
81 }82 }
82 }83 }
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
1use 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};
77
17type 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}
5255
53impl 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 }
168177
169 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 }
172182
173 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 }
178188
179 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());
182192
210 .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 ran
226 } 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 }
213241
214 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)
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
4040
41#[cfg_attr(feature = "serialize", derive(Serialize))]41#[cfg_attr(feature = "serialize", derive(Serialize))]
42#[cfg_attr(feature = "deserialize", derive(Deserialize))]42#[cfg_attr(feature = "deserialize", derive(Deserialize))]
43#[derive(Debug, PartialEq)]43#[derive(Clone, Debug, PartialEq)]
44pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);44pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
4545
46#[cfg_attr(feature = "serialize", derive(Serialize))]46#[cfg_attr(feature = "serialize", derive(Serialize))]
modifiedflake.nixdiffbeforeafterboth
12 pname = "jrsonnet";12 pname = "jrsonnet";
13 version = "0.1.0";13 version = "0.1.0";
14 src = self;14 src = self;
15 cargoSha256 = "sha256-5RzjO9McVqG8+1+p+wRvygYCnemPjUAVB9TpWOp2ipA=";15 cargoSha256 = "sha256-6VhaQi3L2LWzR0cq7oRG81MDbrKJbzSNPcvYSoQ5ISo=";
16 };16 };
17 in { defaultPackage = jrsonnet; });17 in { defaultPackage = jrsonnet; });
18}18}