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};2use jrsonnet_interner::IStr;3use jrsonnet_parser::{ExprLocation, Visibility};4use rustc_hash::FxHashMap;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 super_obj: Option<ObjValue>,21 this_obj: Option<ObjValue>,22 this_entries: Rc<FxHashMap<IStr, ObjMember>>,23 value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,24}2526#[derive(Clone)]27pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);28impl Debug for ObjValue {29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {30 if let Some(super_obj) = self.0.super_obj.as_ref() {31 if f.alternate() {32 write!(f, "{:#?}", super_obj)?;33 } else {34 write!(f, "{:?}", super_obj)?;35 }36 write!(f, " + ")?;37 }38 let mut debug = f.debug_struct("ObjValue");39 for (name, member) in self.0.this_entries.iter() {40 debug.field(name, member);41 }42 #[cfg(feature = "unstable")]43 {44 debug.finish_non_exhaustive()45 }46 #[cfg(not(feature = "unstable"))]47 {48 debug.finish()49 }50 }51}5253impl ObjValue {54 pub fn new(super_obj: Option<Self>, this_entries: Rc<FxHashMap<IStr, ObjMember>>) -> Self {55 Self(Rc::new(ObjValueInternals {56 super_obj,57 this_obj: None,58 this_entries,59 value_cache: RefCell::new(FxHashMap::default()),60 }))61 }62 pub fn new_empty() -> Self {63 Self::new(None, Rc::new(FxHashMap::default()))64 }65 pub fn extend_from(&self, super_obj: Self) -> Self {66 match &self.0.super_obj {67 None => Self::new(Some(super_obj), self.0.this_entries.clone()),68 Some(v) => Self::new(Some(v.extend_from(super_obj)), self.0.this_entries.clone()),69 }70 }71 pub fn with_this(&self, this_obj: Self) -> Self {72 Self(Rc::new(ObjValueInternals {73 super_obj: self.0.super_obj.clone(),74 this_obj: Some(this_obj),75 this_entries: self.0.this_entries.clone(),76 value_cache: RefCell::new(FxHashMap::default()),77 }))78 }7980 /// Run callback for every field found in object81 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {82 if let Some(s) = &self.0.super_obj {83 if s.enum_fields(handler) {84 return true;85 }86 }87 for (name, member) in self.0.this_entries.iter() {88 if handler(name, &member.visibility) {89 return true;90 }91 }92 false93 }9495 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {96 let mut out = FxHashMap::default();97 self.enum_fields(&mut |name, visibility| {98 match visibility {99 Visibility::Normal => {100 let entry = out.entry(name.to_owned());101 entry.or_insert(true);102 }103 Visibility::Hidden => {104 out.insert(name.to_owned(), false);105 }106 Visibility::Unhide => {107 out.insert(name.to_owned(), true);108 }109 };110 false111 });112 out113 }114 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {115 let mut fields: Vec<_> = self116 .fields_visibility()117 .into_iter()118 .filter(|(_k, v)| include_hidden || *v)119 .map(|(k, _)| k)120 .collect();121 fields.sort_unstable();122 fields123 }124 pub fn fields(&self) -> Vec<IStr> {125 self.fields_ex(false)126 }127128 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {129 if let Some(m) = self.0.this_entries.get(&name) {130 Some(match &m.visibility {131 Visibility::Normal => self132 .0133 .super_obj134 .as_ref()135 .and_then(|super_obj| super_obj.field_visibility(name))136 .unwrap_or(Visibility::Normal),137 v => *v,138 })139 } else if let Some(super_obj) = &self.0.super_obj {140 super_obj.field_visibility(name)141 } else {142 None143 }144 }145146 fn has_field_include_hidden(&self, name: IStr) -> bool {147 if self.0.this_entries.contains_key(&name) {148 true149 } else if let Some(super_obj) = &self.0.super_obj {150 super_obj.has_field_include_hidden(name)151 } else {152 false153 }154 }155156 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {157 if include_hidden {158 self.has_field_include_hidden(name)159 } else {160 self.has_field(name)161 }162 }163 pub fn has_field(&self, name: IStr) -> bool {164 self.field_visibility(name)165 .map(|v| v.is_visible())166 .unwrap_or(false)167 }168169 pub fn get(&self, key: IStr) -> Result<Option<Val>> {170 self.get_raw(key, self.0.this_obj.as_ref())171 }172173 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {174 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());175 new.insert(key, value);176 Self::new(Some(self), Rc::new(new))177 }178179 pub(crate) fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {180 let real_this = real_this.unwrap_or(self);181 let cache_key = (key.clone(), real_this.clone());182183 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {184 return Ok(v.clone());185 }186 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {187 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),188 (Some(k), Some(s)) => {189 let our = self.evaluate_this(k, real_this)?;190 if k.add {191 s.get_raw(key, Some(real_this))?192 .map_or(Ok(Some(our.clone())), |v| {193 Ok(Some(evaluate_add_op(&v, &our)?))194 })195 } else {196 Ok(Some(our))197 }198 }199 (None, Some(s)) => s.get_raw(key, Some(real_this)),200 (None, None) => Ok(None),201 }?;202 self.0203 .value_cache204 .borrow_mut()205 .insert(cache_key, value.clone());206 Ok(value)207 }208 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {209 v.invoke210 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?211 .evaluate()212 }213214 pub fn ptr_eq(a: &Self, b: &Self) -> bool {215 Rc::ptr_eq(&a.0, &b.0)216 }217}218219impl PartialEq for ObjValue {220 fn eq(&self, other: &Self) -> bool {221 Rc::ptr_eq(&self.0, &other.0)222 }223}224225impl Eq for ObjValue {}226impl Hash for ObjValue {227 fn hash<H: Hasher>(&self, state: &mut H) {228 state.write_usize(Rc::as_ptr(&self.0) as usize)229 }230}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; });
}