difftreelog
feat(evaluator) use errors, pass EvaluationState
in: master
7 files changed
crates/jsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jsonnet-evaluator/Cargo.toml
+++ b/crates/jsonnet-evaluator/Cargo.toml
@@ -9,6 +9,4 @@
[dependencies]
jsonnet-parser = { path = "../jsonnet-parser" }
closure = "0.3.0"
-
-[dev-dependencies]
jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }
crates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/ctx.rs
+++ b/crates/jsonnet-evaluator/src/ctx.rs
@@ -1,5 +1,6 @@
use crate::{
- future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Val,
+ future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Result,
+ Val,
};
use closure::closure;
use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
@@ -7,7 +8,7 @@
rc_fn_helper!(
ContextCreator,
context_creator,
- dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Context
+ dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>
);
future_wrapper!(Context, FutureContext);
@@ -65,12 +66,12 @@
ctx.unwrap()
}
- pub fn with_var(&self, name: String, value: Val) -> Context {
+ pub fn with_var(&self, name: String, value: Val) -> Result<Context> {
let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();
new_bindings.insert(
name,
lazy_binding!(
- closure!(clone value, |_t, _s|lazy_val!(closure!(clone value, ||value.clone())))
+ closure!(clone value, |_t, _s|Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))
),
);
self.extend(new_bindings, None, None, None)
@@ -82,7 +83,7 @@
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
- ) -> Context {
+ ) -> Result<Context> {
let dollar = new_dollar.or_else(|| self.0.dollar.clone());
let this = new_this.or_else(|| self.0.this.clone());
let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
@@ -94,16 +95,16 @@
new.insert(k.clone(), v.clone());
}
for (k, v) in new_bindings.into_iter() {
- new.insert(k, v.0(this.clone(), super_obj.clone()));
+ new.insert(k, v.0(this.clone(), super_obj.clone())?);
}
Rc::new(new)
};
- Context(Rc::new(ContextInternals {
+ Ok(Context(Rc::new(ContextInternals {
dollar,
this,
super_obj,
bindings,
- }))
+ })))
}
}
crates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -1 +1,20 @@
-pub enum Error {}
+use crate::ValType;
+use jsonnet_parser::LocExpr;
+
+#[derive(Debug)]
+pub enum Error {
+ VariableIsNotDefined(String),
+ TypeMismatch(&'static str, Vec<ValType>, ValType),
+ NoSuchField(String),
+
+ RuntimeError(String),
+}
+
+#[derive(Clone, Debug)]
+pub struct StackTraceElement(pub LocExpr, pub String);
+#[derive(Debug)]
+pub struct StackTrace(pub Vec<StackTraceElement>);
+
+#[derive(Debug)]
+pub struct LocError(pub Error, pub StackTrace);
+pub type Result<V> = std::result::Result<V, LocError>;
crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -1,7 +1,7 @@
use crate::{
- binding, bool_val, context_creator, function_default, function_rhs, future_wrapper,
- lazy_binding, lazy_val, Context, ContextCreator, EvaluationState, FuncDesc, LazyBinding,
- ObjMember, ObjValue, Val,
+ binding, context_creator, create_error, function_default, function_rhs, future_wrapper,
+ lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,
+ ObjValue, Result, Val,
};
use closure::closure;
use jsonnet_parser::{
@@ -14,89 +14,66 @@
rc::Rc,
};
-pub fn evaluate_binding(
- eval_state: EvaluationState,
- b: &BindSpec,
- context_creator: ContextCreator,
-) -> (String, LazyBinding) {
+pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {
let b = b.clone();
if let Some(args) = &b.params {
let args = args.clone();
(
b.name.clone(),
- lazy_binding!(move |this, super_obj| lazy_val!(
- closure!(clone b, clone args, clone context_creator, clone eval_state, || evaluate_method(
- context_creator.0(this.clone(), super_obj.clone()),
- eval_state.clone(),
+ lazy_binding!(move |this, super_obj| Ok(lazy_val!(
+ closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(
+ context_creator.0(this.clone(), super_obj.clone())?,
&b.value,
args.clone()
- ))
- )),
+ )))
+ ))),
)
} else {
(
b.name.clone(),
lazy_binding!(move |this, super_obj| {
- lazy_val!(
- closure!(clone context_creator, clone b, clone eval_state, || evaluate(
- context_creator.0(this.clone(), super_obj.clone()),
- eval_state.clone(),
+ Ok(lazy_val!(
+ closure!(clone context_creator, clone b, || evaluate(
+ context_creator.0(this.clone(), super_obj.clone())?,
&b.value
))
- )
+ ))
}),
)
}
}
-pub fn evaluate_method(
- ctx: Context,
- eval_state: EvaluationState,
- expr: &LocExpr,
- arg_spec: ParamsDesc,
-) -> Val {
+pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {
Val::Func(FuncDesc {
ctx,
params: arg_spec,
- eval_rhs: function_rhs!(
- closure!(clone expr, clone eval_state, |ctx| evaluate(ctx, eval_state.clone(), &expr))
- ),
- eval_default: function_default!(
- closure!(clone eval_state, |ctx, default| evaluate(ctx, eval_state.clone(), &default))
- ),
+ eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),
+ eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),
})
}
pub fn evaluate_field_name(
context: Context,
- eval_state: EvaluationState,
field_name: &jsonnet_parser::FieldName,
-) -> String {
- match field_name {
+) -> Result<String> {
+ Ok(match field_name {
jsonnet_parser::FieldName::Fixed(n) => n.clone(),
jsonnet_parser::FieldName::Dyn(expr) => {
- let name = evaluate(context, eval_state, expr).unwrap_if_lazy();
- match name {
- Val::Str(n) => n,
- _ => panic!(
- "dynamic field name can be only evaluated to 'string', got: {:?}",
- name
- ),
- }
+ evaluate(context, expr)?.try_cast_str("dynamic field name")?
}
- }
+ })
}
-pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Val {
- match (op, b) {
- (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()),
+pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
+ Ok(match (op, b) {
+ (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,
(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),
(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),
- }
+ })
}
-pub fn evaluate_add_op(a: &Val, b: &Val) -> Val {
- match (a, b) {
+pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
+ Ok(match (a, b) {
(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),
(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),
(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),
@@ -104,36 +81,29 @@
(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),
(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),
_ => panic!("can't add: {:?} and {:?}", a, b),
- }
+ })
}
-pub fn evaluate_binary_op(
- context: Context,
- eval_state: EvaluationState,
- a: &Val,
- op: BinaryOpType,
- b: &Val,
-) -> Val {
- match (a, op, b) {
- (Val::Lazy(a), o, b) => evaluate_binary_op(context, eval_state, &a.evaluate(), o, b),
- (a, o, Val::Lazy(b)) => evaluate_binary_op(context, eval_state, a, o, &b.evaluate()),
+pub fn evaluate_binary_op(context: Context, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
+ Ok(match (a, op, b) {
+ (Val::Lazy(a), o, b) => evaluate_binary_op(context, &a.evaluate()?, o, b)?,
+ (a, o, Val::Lazy(b)) => evaluate_binary_op(context, a, o, &b.evaluate()?)?,
- (a, BinaryOpType::Add, b) => evaluate_add_op(a, b),
+ (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,
- (Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => bool_val(v1 != v2),
+ (Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => Val::Bool(v1 != v2),
(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),
(Val::Str(format), BinaryOpType::Mod, args) => evaluate(
context
- .with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))
+ .with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))?
.with_var(
"__tmp__args__".to_owned(),
match args {
Val::Arr(v) => Val::Arr(v.clone()),
v => Val::Arr(vec![v.clone()]),
},
- ),
- eval_state,
+ )?,
&el!(Expr::Apply(
el!(Expr::Index(
el!(Expr::Var("std".to_owned())),
@@ -144,7 +114,7 @@
Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))
])
)),
- ),
+ )?,
(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),
(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),
@@ -162,13 +132,13 @@
Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)
}
- (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => bool_val(v1 < v2),
- (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => bool_val(v1 > v2),
- (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => bool_val(v1 <= v2),
- (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => bool_val(v1 >= v2),
+ (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),
+ (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),
+ (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),
+ (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),
- (Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => bool_val((v1 - v2).abs() < f64::EPSILON),
- (Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => bool_val((v1 - v2).abs() > f64::EPSILON),
+ (Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => Val::Bool((v1 - v2).abs() < f64::EPSILON),
+ (Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => Val::Bool((v1 - v2).abs() > f64::EPSILON),
(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {
Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)
@@ -179,10 +149,10 @@
(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {
Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)
}
- (a, BinaryOpType::Eq, b) => bool_val(a == b),
- (a, BinaryOpType::Ne, b) => bool_val(a != b),
+ (a, BinaryOpType::Eq, b) => Val::Bool(a == b),
+ (a, BinaryOpType::Ne, b) => Val::Bool(a != b),
_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),
- }
+ })
}
future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);
@@ -190,54 +160,52 @@
pub fn evaluate_comp(
context: Context,
- eval_state: EvaluationState,
value: &LocExpr,
specs: &[CompSpec],
-) -> Option<Vec<Val>> {
- match specs.get(0) {
- None => Some(vec![evaluate(context, eval_state, &value)]),
+) -> Result<Option<Vec<Val>>> {
+ Ok(match specs.get(0) {
+ None => Some(vec![evaluate(context, &value)?]),
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
- match evaluate(context.clone(), eval_state.clone(), &cond).unwrap_if_lazy() {
- Val::Bool(false) => None,
- Val::Bool(true) => evaluate_comp(context, eval_state, value, &specs[1..]),
- _ => panic!("if expression evaluated to non-boolean value"),
+ if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {
+ evaluate_comp(context, value, &specs[1..])?
+ } else {
+ None
}
}
Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {
- match evaluate(context.clone(), eval_state.clone(), &expr).unwrap_if_lazy() {
+ match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {
Val::Arr(list) => {
let mut out = Vec::new();
for item in list {
let item = item.clone();
out.push(evaluate_comp(
- context.with_var(var.clone(), item),
- eval_state.clone(),
+ context.with_var(var.clone(), item)?,
value,
&specs[1..],
- ));
+ )?);
}
Some(out.iter().flatten().flatten().cloned().collect())
}
_ => panic!("for expression evaluated to non-iterable value"),
}
}
- }
+ })
}
// TODO: Asserts
-pub fn evaluate_object(context: Context, eval_state: EvaluationState, object: ObjBody) -> ObjValue {
- match object {
+pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {
+ Ok(match object {
ObjBody::MemberList(members) => {
let new_bindings = FutureNewBindings::new();
let future_this = FutureObjValue::new();
let context_creator = context_creator!(
closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {
- context.clone().extend(
+ Ok(context.clone().extend(
new_bindings.clone().unwrap(),
context.clone().dollar().clone().or_else(||this.clone()),
Some(this.unwrap()),
super_obj
- )
+ )?)
})
);
{
@@ -248,7 +216,7 @@
Member::BindStmt(b) => Some(b.clone()),
_ => None,
})
- .map(|b| evaluate_binding(eval_state.clone(), &b, context_creator.clone()))
+ .map(|b| evaluate_binding(&b, context_creator.clone()))
{
bindings.insert(n, b);
}
@@ -265,21 +233,20 @@
visibility,
value,
}) => {
- let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);
+ let name = evaluate_field_name(context.clone(), &name)?;
new_members.insert(
name,
ObjMember {
add: plus,
visibility: visibility.clone(),
invoke: binding!(
- closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {
- let context = context_creator.0(this, super_obj);
+ closure!(clone value, clone context_creator, |this, super_obj| {
+ let context = context_creator.0(this, super_obj)?;
// TODO: Assert
evaluate(
context,
- eval_state.clone(),
&value,
- ).unwrap_if_lazy()
+ )?.unwrap_if_lazy()
})
),
},
@@ -291,21 +258,20 @@
value,
..
}) => {
- let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);
+ let name = evaluate_field_name(context.clone(), &name)?;
new_members.insert(
name,
ObjMember {
add: false,
visibility: Visibility::Hidden,
invoke: binding!(
- closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {
+ closure!(clone value, clone context_creator, |this, super_obj| {
// TODO: Assert
- evaluate_method(
- context_creator.0(this, super_obj),
- eval_state.clone(),
+ Ok(evaluate_method(
+ context_creator.0(this, super_obj)?,
&value.clone(),
params.clone(),
- )
+ ))
})
),
},
@@ -318,14 +284,14 @@
future_this.fill(ObjValue::new(None, Rc::new(new_members)))
}
_ => todo!(),
- }
+ })
}
-pub fn evaluate(context: Context, eval_state: EvaluationState, expr: &LocExpr) -> Val {
+pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
use Expr::*;
- eval_state.clone().push(expr.clone(), "expr".to_owned(), || {
+ push(expr.clone(), "expr".to_owned(), || {
let LocExpr(expr, loc) = expr;
- match &**expr {
+ Ok(match &**expr {
Literal(LiteralType::This) => Val::Obj(
context
.this()
@@ -341,42 +307,31 @@
Literal(LiteralType::True) => Val::Bool(true),
Literal(LiteralType::False) => Val::Bool(false),
Literal(LiteralType::Null) => Val::Null,
- Parened(e) => evaluate(context, eval_state.clone(), e),
+ Parened(e) => evaluate(context, e)?,
Str(v) => Val::Str(v.clone()),
Num(v) => Val::Num(*v),
BinaryOp(v1, o, v2) => {
- let a = evaluate(context.clone(), eval_state.clone(), v1).unwrap_if_lazy();
+ let a = evaluate(context.clone(), v1)?.unwrap_if_lazy()?;
let op = *o;
- let b = evaluate(context.clone(), eval_state.clone(), v2).unwrap_if_lazy();
- evaluate_binary_op(
- context,
- eval_state,
- &a,
- op,
- &b,
- )
- },
- UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, eval_state, v)),
- Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy(),
+ let b = evaluate(context.clone(), v2)?.unwrap_if_lazy()?;
+ evaluate_binary_op(context, &a, op, &b)?
+ }
+ UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
+ Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,
Index(value, index) => {
match (
- evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy(),
- evaluate(context.clone(), eval_state.clone(), index),
+ evaluate(context.clone(), value)?.unwrap_if_lazy()?,
+ evaluate(context.clone(), index)?,
) {
- (Val::Obj(v), Val::Str(s)) => v
- .get(&s)
- .unwrap_or_else(closure!(clone context, clone eval_state, || {
- if let Some(n) = v.get("__intristic_namespace__") {
- if let Val::Str(n) = n.unwrap_if_lazy() {
- Val::Intristic(n, s)
- } else {
- panic!("__intristic_namespace__ should be string");
- }
- } else {
- panic!("{} not found in {:?}", s, v)
- }
- }))
- .unwrap_if_lazy(),
+ (Val::Obj(v), Val::Str(s)) => {
+ if let Some(v) = v.get(&s)? {
+ v.unwrap_if_lazy()?
+ } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {
+ Val::Intristic(n, s)
+ } else {
+ create_error(crate::Error::NoSuchField(s))?
+ }
+ }
(Val::Arr(v), Val::Num(n)) => v
.get(n as usize)
.unwrap_or_else(|| panic!("out of bounds"))
@@ -392,34 +347,35 @@
let future_context = Context::new_future();
let context_creator = context_creator!(
- closure!(clone future_context, |_, _| future_context.clone().unwrap())
+ closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))
);
for (k, v) in bindings
.iter()
- .map(|b| evaluate_binding(eval_state.clone(), b, context_creator.clone()))
+ .map(|b| evaluate_binding(b, context_creator.clone()))
{
new_bindings.insert(k, v);
}
let context = context
- .extend(new_bindings, None, None, None)
+ .extend(new_bindings, None, None, None)?
.into_future(future_context);
- evaluate(context, eval_state.clone(), &returned.clone())
+ evaluate(context, &returned.clone())?
}
Arr(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
- out.push(evaluate(context.clone(), eval_state.clone(), item));
+ out.push(evaluate(context.clone(), item)?);
}
Val::Arr(out)
}
- ArrComp(expr, compspecs) => {
- Val::Arr(evaluate_comp(context, eval_state, expr, compspecs).unwrap())
- }
- Obj(body) => Val::Obj(evaluate_object(context, eval_state, body.clone())),
+ ArrComp(expr, compspecs) => Val::Arr(
+ // First compspec should be forspec, so no "None" possible here
+ evaluate_comp(context, expr, compspecs)?.unwrap(),
+ ),
+ Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),
Apply(value, ArgsDesc(args)) => {
- let value = evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy();
+ let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;
match value {
// TODO: Capture context of application
Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {
@@ -427,7 +383,7 @@
("std", "length") => {
assert_eq!(args.len(), 1);
let expr = &args.get(0).unwrap().1;
- match evaluate(context, eval_state.clone(), expr) {
+ match evaluate(context, expr)? {
Val::Str(n) => Val::Num(n.chars().count() as f64),
Val::Arr(i) => Val::Num(i.len() as f64),
v => panic!("can't get length of {:?}", v),
@@ -437,19 +393,19 @@
("std", "type") => {
assert_eq!(args.len(), 1);
let expr = &args.get(0).unwrap().1;
- Val::Str(evaluate(context, eval_state, expr).type_of().to_owned())
+ Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())
}
// length, idx=>any
("std", "makeArray") => {
assert_eq!(args.len(), 2);
if let (Val::Num(v), Val::Func(d)) = (
- evaluate(context.clone(), eval_state.clone(), &args[0].1),
- evaluate(context, eval_state, &args[1].1),
+ evaluate(context.clone(), &args[0].1)?,
+ evaluate(context, &args[1].1)?,
) {
assert!(v > 0.0);
let mut out = Vec::with_capacity(v as usize);
for i in 0..v as usize {
- out.push(d.evaluate(vec![(None, Val::Num(i as f64))]))
+ out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)
}
Val::Arr(out)
} else {
@@ -459,7 +415,7 @@
// string
("std", "codepoint") => {
assert_eq!(args.len(), 1);
- if let Val::Str(s) = evaluate(context, eval_state, &args[0].1) {
+ if let Val::Str(s) = evaluate(context, &args[0].1)? {
assert!(
s.chars().count() == 1,
"std.codepoint should receive single char string"
@@ -473,8 +429,8 @@
("std", "objectFieldsEx") => {
assert_eq!(args.len(), 2);
if let (Val::Obj(body), Val::Bool(_include_hidden)) = (
- evaluate(context.clone(), eval_state.clone(), &args[0].1),
- evaluate(context, eval_state, &args[1].1),
+ evaluate(context.clone(), &args[0].1)?,
+ evaluate(context, &args[1].1)?,
) {
// TODO: handle visibility (_include_hidden)
Val::Arr(body.fields().into_iter().map(Val::Str).collect())
@@ -491,44 +447,55 @@
(
a.clone().0,
Val::Lazy(lazy_val!(
- closure!(clone context, clone a, clone eval_state, || evaluate(context.clone(), eval_state.clone(), &a.clone().1))
+ closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))
)),
)
})
.collect(),
- ),
+ )?,
_ => panic!("{:?} is not a function", value),
}
}
- Function(params, body) => evaluate_method(context, eval_state, body, params.clone()),
+ Function(params, body) => evaluate_method(context, body, params.clone()),
AssertExpr(AssertStmt(value, msg), returned) => {
- if evaluate(context.clone(), eval_state.clone(), &value).try_cast_bool() {
- evaluate(context, eval_state, returned)
- }else {
- if let Some(msg) = msg {
- panic!("assertion failed ({:?}): {}", value, evaluate(context, eval_state, msg).try_cast_str());
- } else {
- panic!("assertion failed ({:?}): no message", value);
- }
+ if evaluate(context.clone(), &value)?
+ .try_cast_bool("assertion condition should be boolean")?
+ {
+ evaluate(context, returned)?
+ } else if let Some(msg) = msg {
+ panic!(
+ "assertion failed ({:?}): {}",
+ value,
+ evaluate(context, msg)?
+ .try_cast_str("assertion message should be string")?
+ );
+ } else {
+ panic!("assertion failed ({:?}): no message", value);
}
- },
- Error(e) => panic!("error: {}", evaluate(context, eval_state, e)),
+ }
+ Error(e) => create_error(crate::Error::RuntimeError(
+ evaluate(context, e)?.try_cast_str("error text should be string")?,
+ ))?,
IfElse {
cond,
cond_then,
cond_else,
- } => match evaluate(context.clone(), eval_state.clone(), &cond.0).unwrap_if_lazy() {
- Val::Bool(true) => evaluate(context, eval_state.clone(), cond_then),
- Val::Bool(false) => match cond_else {
- Some(v) => evaluate(context, eval_state, v),
- None => Val::Bool(false),
- },
- v => panic!("if condition evaluated to {:?} (boolean needed instead)", v),
- },
+ } => {
+ if evaluate(context.clone(), &cond.0)?
+ .try_cast_bool("if condition should be boolean")?
+ {
+ evaluate(context, cond_then)?
+ } else {
+ match cond_else {
+ Some(v) => evaluate(context, v)?,
+ None => Val::Bool(false),
+ }
+ }
+ }
_ => panic!(
"evaluation not implemented: {:?}",
LocExpr(expr.clone(), loc.clone())
),
- }
+ })
})
}
crates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth1#![feature(box_syntax, box_patterns)]2#![feature(type_alias_impl_trait)]3#![feature(debug_non_exhaustive)]4#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]5mod ctx;6mod dynamic;7mod error;8mod evaluate;9mod obj;10mod val;1112use closure::closure;13pub use ctx::*;14pub use dynamic::*;15pub use error::*;16pub use evaluate::*;17use jsonnet_parser::*;18pub use obj::*;19use std::{cell::RefCell, collections::HashMap, rc::Rc};20pub use val::*;2122rc_fn_helper!(23 Binding,24 binding,25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Val26);27rc_fn_helper!(28 LazyBinding,29 lazy_binding,30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> LazyVal31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Val);33rc_fn_helper!(34 FunctionDefault,35 function_default,36 dyn Fn(Context, LocExpr) -> Val37);3839#[derive(Default)]40pub struct EvaluationStateInternals {41 /// Used for stack-overflows and stacktraces42 stack: RefCell<Vec<(LocExpr, String)>>,43 /// Contains file source codes and evaluated results for imports and pretty printing stacktraces44 files: RefCell<HashMap<String, (String, LocExpr, Option<Val>)>>,45 globals: RefCell<HashMap<String, Val>>,46}4748#[derive(Default, Clone)]49pub struct EvaluationState(Rc<EvaluationStateInternals>);50impl EvaluationState {51 pub fn add_file(&self, name: String, code: String) -> Result<(), Box<dyn std::error::Error>> {52 self.0.files.borrow_mut().insert(53 name.clone(),54 (55 code.clone(),56 parse(57 &code,58 &ParserSettings {59 file_name: name.clone(),60 loc_data: true,61 },62 )?,63 None,64 ),65 );6667 Ok(())68 }69 pub fn evaluate_file(&self, name: &str) -> Result<Val, Box<dyn std::error::Error>> {70 let expr: LocExpr = {71 let ro_map = self.0.files.borrow();72 let value = ro_map73 .get(name)74 .unwrap_or_else(|| panic!("file not added: {:?}", name));75 if value.2.is_some() {76 return Ok(value.2.clone().unwrap());77 }78 value.1.clone()79 };80 let value = evaluate(self.create_default_context(), self.clone(), &expr);81 {82 self.083 .files84 .borrow_mut()85 .get_mut(name)86 .unwrap()87 .288 .replace(value.clone());89 }90 Ok(value)91 }9293 pub fn parse_evaluate_raw(&self, code: &str) -> Val {94 let parsed = parse(95 &code,96 &ParserSettings {97 file_name: "raw.jsonnet".to_owned(),98 loc_data: true,99 },100 );101 evaluate(102 self.create_default_context(),103 self.clone(),104 &parsed.unwrap(),105 )106 }107108 pub fn add_stdlib(&self) {109 use jsonnet_stdlib::STDLIB_STR;110 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())111 .unwrap();112 let val = self.evaluate_file("std.jsonnet").unwrap();113 self.0.globals.borrow_mut().insert("std".to_owned(), val);114 }115116 pub fn create_default_context(&self) -> Context {117 let globals = self.0.globals.borrow();118 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();119 for (name, value) in globals.iter() {120 new_bindings.insert(121 name.clone(),122 lazy_binding!(123 closure!(clone value, |_self, _super_obj| lazy_val!(closure!(clone value, ||value.clone())))124 ),125 );126 }127 Context::new().extend(new_bindings, None, None, None)128 }129130 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {131 self.0.stack.borrow_mut().push((e, comment));132 let result = f();133 self.0.stack.borrow_mut().pop();134 result135 }136 pub fn print_stack_trace(&self) {137 for e in self.stack_trace() {138 println!("{:?} - {:?}", e.0, e.1)139 }140 }141 pub fn stack_trace(&self) -> Vec<(LocExpr, String)> {142 self.0143 .stack144 .borrow()145 .iter()146 .rev()147 .map(|e| e.clone())148 .collect()149 }150}151152#[cfg(test)]153pub mod tests {154 use super::{evaluate, Context, Val};155 use crate::EvaluationState;156 use jsonnet_parser::*;157158 #[test]159 fn eval_state_stacktrace() {160 let state = EvaluationState::default();161 state.push(162 loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),163 "outer".to_owned(),164 || {165 state.push(166 loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),167 "inner".to_owned(),168 || state.print_stack_trace(),169 );170 },171 );172 }173174 #[test]175 fn eval_state_standard() {176 let state = EvaluationState::default();177 state.add_stdlib();178 assert_eq!(179 state.parse_evaluate_raw(r#"std.base64("test") == "dGVzdA==""#),180 Val::Bool(true)181 );182 }183184 macro_rules! eval {185 ($str: expr) => {186 evaluate(187 Context::new(),188 EvaluationState::default(),189 &parse(190 $str,191 &ParserSettings {192 loc_data: true,193 file_name: "test.jsonnet".to_owned(),194 },195 )196 .unwrap(),197 )198 };199 }200201 macro_rules! eval_stdlib {202 ($str: expr) => {{203 let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";204 evaluate(205 Context::new(),206 EvaluationState::default(),207 &parse(208 &(std + $str),209 &ParserSettings {210 loc_data: true,211 file_name: "test.jsonnet".to_owned(),212 },213 )214 .unwrap(),215 )216 }};217 }218219 macro_rules! assert_eval {220 ($str: expr) => {221 assert_eq!(222 evaluate(223 Context::new(),224 EvaluationState::default(),225 &parse(226 $str,227 &ParserSettings {228 loc_data: true,229 file_name: "test.jsonnet".to_owned(),230 }231 )232 .unwrap()233 ),234 Val::Bool(true)235 )236 };237 }238 macro_rules! assert_json {239 ($str: expr, $out: expr) => {240 assert_eq!(241 format!(242 "{}",243 evaluate(244 Context::new(),245 EvaluationState::default(),246 &parse(247 $str,248 &ParserSettings {249 loc_data: true,250 file_name: "test.jsonnet".to_owned(),251 }252 )253 .unwrap()254 )255 ),256 $out257 )258 };259 }260 macro_rules! assert_json_stdlib {261 ($str: expr, $out: expr) => {262 assert_eq!(format!("{}", eval_stdlib!($str)), $out)263 };264 }265 macro_rules! assert_eval_neg {266 ($str: expr) => {267 assert_eq!(268 evaluate(269 Context::new(),270 EvaluationState::default(),271 &parse(272 $str,273 &ParserSettings {274 loc_data: true,275 file_name: "test.jsonnet".to_owned(),276 }277 )278 .unwrap()279 ),280 Val::Bool(false)281 )282 };283 }284285 /// Sanity checking, before trusting to another tests286 #[test]287 fn equality_operator() {288 assert_eval!("2 == 2");289 assert_eval_neg!("2 != 2");290 assert_eval!("2 != 3");291 assert_eval_neg!("2 == 3");292 assert_eval!("'Hello' == 'Hello'");293 assert_eval_neg!("'Hello' != 'Hello'");294 assert_eval!("'Hello' != 'World'");295 assert_eval_neg!("'Hello' == 'World'");296 }297298 #[test]299 fn math_evaluation() {300 assert_eval!("2 + 2 * 2 == 6");301 assert_eval!("3 + (2 + 2 * 2) == 9");302 }303304 #[test]305 fn string_concat() {306 assert_eval!("'Hello' + 'World' == 'HelloWorld'");307 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");308 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");309 }310311 #[test]312 fn local() {313 assert_eval!("local a = 2; local b = 3; a + b == 5");314 assert_eval!("local a = 1, b = a + 1; a + b == 3");315 assert_eval!("local a = 1; local a = 2; a == 2");316 }317318 #[test]319 fn object_lazyness() {320 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);321 }322323 #[test]324 fn object_inheritance() {325 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);326 }327328 #[test]329 fn test_object() {330 assert_json!("{a:2}", r#"{"a":2}"#);331 assert_json!("{a:2+2}", r#"{"a":4}"#);332 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);333 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);334 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);335 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);336 assert_json!(337 r#"338 {339 name: "Alice",340 welcome: "Hello " + self.name + "!",341 }342 "#,343 r#"{"name":"Alice","welcome":"Hello Alice!"}"#344 );345 assert_json!(346 r#"347 {348 name: "Alice",349 welcome: "Hello " + self.name + "!",350 } + {351 name: "Bob"352 }353 "#,354 r#"{"name":"Bob","welcome":"Hello Bob!"}"#355 );356 }357358 #[test]359 fn functions() {360 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");361 assert_json!(362 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,363 r#""HelloDearWorld""#364 );365 }366367 #[test]368 fn local_methods() {369 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");370 assert_json!(371 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,372 r#""HelloDearWorld""#373 );374 }375376 #[test]377 fn object_locals() {378 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);379 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);380 assert_json!(381 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,382 r#"{"test":{"test":4}}"#383 );384 }385386 #[test]387 fn direct_self() {388 println!(389 "{:#?}",390 eval!(391 r#"392 {393 local me = self,394 a: 3,395 b(): me.a,396 }397 "#398 )399 );400 }401402 #[test]403 fn indirect_self() {404 // `self` assigned to `me` was lost when being405 // referenced from field406 eval_stdlib!(407 r#"{408 local me = self,409 a: 3,410 b: me.a,411 }.b"#412 );413 }414415 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly416 #[test]417 fn std_assert_ok() {418 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");419 }420421 #[test]422 #[should_panic]423 fn std_assert_failure() {424 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");425 }426427 #[test]428 fn string_is_string() {429 assert_eq!(430 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),431 Val::Bool(false)432 );433 }434435 #[test]436 fn base64_works() {437 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);438 }439440 #[test]441 fn utf8_chars() {442 assert_json_stdlib!(443 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,444 r#"{"c":128526,"l":1}"#445 )446 }447448 #[test]449 fn json() {450 assert_json_stdlib!(451 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,452 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#453 );454 }455456 #[test]457 fn test() {458 assert_json_stdlib!(459 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,460 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"461 );462 }463464 #[test]465 fn sjsonnet() {466 eval!(467 r#"468 local x0 = {k: 1};469 local x1 = {k: x0.k + x0.k};470 local x2 = {k: x1.k + x1.k};471 local x3 = {k: x2.k + x2.k};472 local x4 = {k: x3.k + x3.k};473 local x5 = {k: x4.k + x4.k};474 local x6 = {k: x5.k + x5.k};475 local x7 = {k: x6.k + x6.k};476 local x8 = {k: x7.k + x7.k};477 local x9 = {k: x8.k + x8.k};478 local x10 = {k: x9.k + x9.k};479 local x11 = {k: x10.k + x10.k};480 local x12 = {k: x11.k + x11.k};481 local x13 = {k: x12.k + x12.k};482 local x14 = {k: x13.k + x13.k};483 local x15 = {k: x14.k + x14.k};484 local x16 = {k: x15.k + x15.k};485 local x17 = {k: x16.k + x16.k};486 local x18 = {k: x17.k + x17.k};487 local x19 = {k: x18.k + x18.k};488 local x20 = {k: x19.k + x19.k};489 local x21 = {k: x20.k + x20.k};490 x21.k491 "#492 );493 }494}1#![feature(box_syntax, box_patterns)]2#![feature(type_alias_impl_trait)]3#![feature(debug_non_exhaustive)]4#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]5mod ctx;6mod dynamic;7mod error;8mod evaluate;9mod obj;10mod val;1112use closure::closure;13pub use ctx::*;14pub use dynamic::*;15pub use error::*;16pub use evaluate::*;17use jsonnet_parser::*;18pub use obj::*;19use std::{cell::RefCell, collections::HashMap, rc::Rc};20pub use val::*;2122rc_fn_helper!(23 Binding,24 binding,25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>26);27rc_fn_helper!(28 LazyBinding,29 lazy_binding,30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);33rc_fn_helper!(34 FunctionDefault,35 function_default,36 dyn Fn(Context, LocExpr) -> Result<Val>37);3839pub struct FileData(String, LocExpr, Option<Val>);40#[derive(Default)]41pub struct EvaluationStateInternals {42 /// Used for stack-overflows and stacktraces43 stack: RefCell<Vec<StackTraceElement>>,44 /// Contains file source codes and evaluated results for imports and pretty printing stacktraces45 files: RefCell<HashMap<String, FileData>>,46 globals: RefCell<HashMap<String, Val>>,47}4849thread_local! {50 pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)51}52pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {53 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))54}55pub(crate) fn create_error<T>(err: Error) -> Result<T> {56 with_state(|s| s.error(err))57}58pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {59 with_state(|s| s.push(e, comment, f))60}6162#[derive(Default, Clone)]63pub struct EvaluationState(Rc<EvaluationStateInternals>);64impl EvaluationState {65 pub fn add_file(66 &self,67 name: String,68 code: String,69 ) -> std::result::Result<(), Box<dyn std::error::Error>> {70 self.0.files.borrow_mut().insert(71 name.clone(),72 FileData(73 code.clone(),74 parse(75 &code,76 &ParserSettings {77 file_name: name,78 loc_data: true,79 },80 )?,81 None,82 ),83 );8485 Ok(())86 }87 pub fn evaluate_file(&self, name: &str) -> Result<Val> {88 self.begin_state();89 let expr: LocExpr = {90 let ro_map = self.0.files.borrow();91 let value = ro_map92 .get(name)93 .unwrap_or_else(|| panic!("file not added: {:?}", name));94 if value.2.is_some() {95 return Ok(value.2.clone().unwrap());96 }97 value.1.clone()98 };99 let value = evaluate(self.create_default_context()?, &expr)?;100 {101 self.0102 .files103 .borrow_mut()104 .get_mut(name)105 .unwrap()106 .2107 .replace(value.clone());108 }109 self.end_state();110 Ok(value)111 }112113 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {114 let parsed = parse(115 &code,116 &ParserSettings {117 file_name: "raw.jsonnet".to_owned(),118 loc_data: true,119 },120 );121 self.begin_state();122 let value = evaluate(self.create_default_context()?, &parsed.unwrap());123 self.end_state();124 value125 }126127 pub fn add_stdlib(&self) {128 self.begin_state();129 use jsonnet_stdlib::STDLIB_STR;130 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())131 .unwrap();132 let val = self.evaluate_file("std.jsonnet").unwrap();133 self.0.globals.borrow_mut().insert("std".to_owned(), val);134 self.end_state();135 }136137 pub fn create_default_context(&self) -> Result<Context> {138 let globals = self.0.globals.borrow();139 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();140 for (name, value) in globals.iter() {141 new_bindings.insert(142 name.clone(),143 lazy_binding!(144 closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))145 ),146 );147 }148 Context::new().extend(new_bindings, None, None, None)149 }150151 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {152 self.0153 .stack154 .borrow_mut()155 .push(StackTraceElement(e, comment));156 let result = f();157 self.0.stack.borrow_mut().pop();158 result159 }160 pub fn print_stack_trace(&self) {161 for e in self.stack_trace().0 {162 println!("{:?} - {:?}", e.0, e.1)163 }164 }165 pub fn stack_trace(&self) -> StackTrace {166 StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())167 }168 pub fn error<T>(&self, err: Error) -> Result<T> {169 Err(LocError(err, self.stack_trace()))170 }171172 fn begin_state(&self) {173 EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));174 }175 fn end_state(&self) {176 EVAL_STATE.with(|v| v.borrow_mut().take());177 }178}179180#[cfg(test)]181pub mod tests {182 use super::Val;183 use crate::EvaluationState;184 use jsonnet_parser::*;185186 #[test]187 fn eval_state_stacktrace() {188 let state = EvaluationState::default();189 state.push(190 loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),191 "outer".to_owned(),192 || {193 state.push(194 loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),195 "inner".to_owned(),196 || state.print_stack_trace(),197 );198 },199 );200 }201202 #[test]203 fn eval_state_standard() {204 let state = EvaluationState::default();205 state.add_stdlib();206 assert_eq!(207 state208 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)209 .unwrap(),210 Val::Bool(true)211 );212 }213214 macro_rules! eval {215 ($str: expr) => {216 evaluate(217 Context::new(),218 EvaluationState::default(),219 &parse(220 $str,221 &ParserSettings {222 loc_data: true,223 file_name: "test.jsonnet".to_owned(),224 },225 )226 .unwrap(),227 )228 };229 }230231 macro_rules! eval_stdlib {232 ($str: expr) => {{233 let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";234 evaluate(235 Context::new(),236 EvaluationState::default(),237 &parse(238 &(std + $str),239 &ParserSettings {240 loc_data: true,241 file_name: "test.jsonnet".to_owned(),242 },243 )244 .unwrap(),245 )246 }};247 }248249 macro_rules! assert_eval {250 ($str: expr) => {251 assert_eq!(252 evaluate(253 Context::new(),254 EvaluationState::default(),255 &parse(256 $str,257 &ParserSettings {258 loc_data: true,259 file_name: "test.jsonnet".to_owned(),260 }261 )262 .unwrap()263 ),264 Val::Bool(true)265 )266 };267 }268 macro_rules! assert_json {269 ($str: expr, $out: expr) => {270 assert_eq!(271 format!(272 "{}",273 evaluate(274 Context::new(),275 EvaluationState::default(),276 &parse(277 $str,278 &ParserSettings {279 loc_data: true,280 file_name: "test.jsonnet".to_owned(),281 }282 )283 .unwrap()284 )285 ),286 $out287 )288 };289 }290 macro_rules! assert_json_stdlib {291 ($str: expr, $out: expr) => {292 assert_eq!(format!("{}", eval_stdlib!($str)), $out)293 };294 }295 macro_rules! assert_eval_neg {296 ($str: expr) => {297 assert_eq!(298 evaluate(299 Context::new(),300 EvaluationState::default(),301 &parse(302 $str,303 &ParserSettings {304 loc_data: true,305 file_name: "test.jsonnet".to_owned(),306 }307 )308 .unwrap()309 ),310 Val::Bool(false)311 )312 };313 }314315 /*316 /// Sanity checking, before trusting to another tests317 #[test]318 fn equality_operator() {319 assert_eval!("2 == 2");320 assert_eval_neg!("2 != 2");321 assert_eval!("2 != 3");322 assert_eval_neg!("2 == 3");323 assert_eval!("'Hello' == 'Hello'");324 assert_eval_neg!("'Hello' != 'Hello'");325 assert_eval!("'Hello' != 'World'");326 assert_eval_neg!("'Hello' == 'World'");327 }328329 #[test]330 fn math_evaluation() {331 assert_eval!("2 + 2 * 2 == 6");332 assert_eval!("3 + (2 + 2 * 2) == 9");333 }334335 #[test]336 fn string_concat() {337 assert_eval!("'Hello' + 'World' == 'HelloWorld'");338 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");339 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");340 }341342 #[test]343 fn local() {344 assert_eval!("local a = 2; local b = 3; a + b == 5");345 assert_eval!("local a = 1, b = a + 1; a + b == 3");346 assert_eval!("local a = 1; local a = 2; a == 2");347 }348349 #[test]350 fn object_lazyness() {351 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);352 }353354 #[test]355 fn object_inheritance() {356 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);357 }358359 #[test]360 fn test_object() {361 assert_json!("{a:2}", r#"{"a":2}"#);362 assert_json!("{a:2+2}", r#"{"a":4}"#);363 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);364 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);365 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);366 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);367 assert_json!(368 r#"369 {370 name: "Alice",371 welcome: "Hello " + self.name + "!",372 }373 "#,374 r#"{"name":"Alice","welcome":"Hello Alice!"}"#375 );376 assert_json!(377 r#"378 {379 name: "Alice",380 welcome: "Hello " + self.name + "!",381 } + {382 name: "Bob"383 }384 "#,385 r#"{"name":"Bob","welcome":"Hello Bob!"}"#386 );387 }388389 #[test]390 fn functions() {391 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");392 assert_json!(393 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,394 r#""HelloDearWorld""#395 );396 }397398 #[test]399 fn local_methods() {400 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");401 assert_json!(402 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,403 r#""HelloDearWorld""#404 );405 }406407 #[test]408 fn object_locals() {409 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);410 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);411 assert_json!(412 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,413 r#"{"test":{"test":4}}"#414 );415 }416417 #[test]418 fn direct_self() {419 println!(420 "{:#?}",421 eval!(422 r#"423 {424 local me = self,425 a: 3,426 b(): me.a,427 }428 "#429 )430 );431 }432433 #[test]434 fn indirect_self() {435 // `self` assigned to `me` was lost when being436 // referenced from field437 eval_stdlib!(438 r#"{439 local me = self,440 a: 3,441 b: me.a,442 }.b"#443 );444 }445446 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly447 #[test]448 fn std_assert_ok() {449 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");450 }451452 #[test]453 #[should_panic]454 fn std_assert_failure() {455 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");456 }457458 #[test]459 fn string_is_string() {460 assert_eq!(461 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),462 Val::Bool(false)463 );464 }465466 #[test]467 fn base64_works() {468 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);469 }470471 #[test]472 fn utf8_chars() {473 assert_json_stdlib!(474 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,475 r#"{"c":128526,"l":1}"#476 )477 }478479 #[test]480 fn json() {481 assert_json_stdlib!(482 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,483 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#484 );485 }486487 #[test]488 fn test() {489 assert_json_stdlib!(490 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,491 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"492 );493 }494495 #[test]496 fn sjsonnet() {497 eval!(498 r#"499 local x0 = {k: 1};500 local x1 = {k: x0.k + x0.k};501 local x2 = {k: x1.k + x1.k};502 local x3 = {k: x2.k + x2.k};503 local x4 = {k: x3.k + x3.k};504 local x5 = {k: x4.k + x4.k};505 local x6 = {k: x5.k + x5.k};506 local x7 = {k: x6.k + x6.k};507 local x8 = {k: x7.k + x7.k};508 local x9 = {k: x8.k + x8.k};509 local x10 = {k: x9.k + x9.k};510 local x11 = {k: x10.k + x10.k};511 local x12 = {k: x11.k + x11.k};512 local x13 = {k: x12.k + x12.k};513 local x14 = {k: x13.k + x13.k};514 local x15 = {k: x14.k + x14.k};515 local x16 = {k: x15.k + x15.k};516 local x17 = {k: x16.k + x16.k};517 local x18 = {k: x17.k + x17.k};518 local x19 = {k: x18.k + x18.k};519 local x20 = {k: x19.k + x19.k};520 local x21 = {k: x20.k + x20.k};521 x21.k522 "#523 );524 }525 */526}crates/jsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/obj.rs
+++ b/crates/jsonnet-evaluator/src/obj.rs
@@ -1,4 +1,4 @@
-use crate::{evaluate_add_op, Binding, Val};
+use crate::{evaluate_add_op, Binding, Result, Val};
use jsonnet_parser::Visibility;
use std::{
cell::RefCell,
@@ -32,13 +32,10 @@
write!(f, " + ")?;
}
let mut debug = f.debug_struct("ObjValue");
- debug.field("$ptr", &Rc::as_ptr(&self.0));
for (name, member) in self.0.this_entries.iter() {
debug.field(name, member);
}
debug.finish_non_exhaustive()
- // .field("fields", &self.fields())
- // .finish_non_exhaustive()
}
}
@@ -71,33 +68,40 @@
}
fields
}
- pub fn get(&self, key: &str) -> Option<Val> {
+ pub fn get(&self, key: &str) -> Result<Option<Val>> {
if let Some(v) = self.0.value_cache.borrow().get(key) {
- return Some(v.clone());
+ return Ok(Some(v.clone()));
}
- let v = self.get_raw(key, self).map(|v| v.unwrap_if_lazy());
- if let Some(v) = v.clone() {
- self.0.value_cache.borrow_mut().insert(key.to_owned(), v);
+ if let Some(v) = self.get_raw(key, self)? {
+ let v = v.unwrap_if_lazy()?;
+ self.0
+ .value_cache
+ .borrow_mut()
+ .insert(key.to_owned(), v.clone());
+ Ok(Some(v))
+ } else {
+ Ok(None)
}
- v
}
- fn get_raw(&self, key: &str, real_this: &ObjValue) -> Option<Val> {
+ fn get_raw(&self, key: &str, real_this: &ObjValue) -> Result<Option<Val>> {
match (self.0.this_entries.get(key), &self.0.super_obj) {
- (Some(k), None) => Some(k.invoke.0(
+ (Some(k), None) => Ok(Some(k.invoke.0(
Some(real_this.clone()),
self.0.super_obj.clone(),
- )),
+ )?)),
(Some(k), Some(s)) => {
- let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone());
+ let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone())?;
if k.add {
- s.get_raw(key, real_this)
- .map_or(Some(our.clone()), |v| Some(evaluate_add_op(&v, &our)))
+ s.get_raw(key, real_this)?
+ .map_or(Ok(Some(our.clone())), |v| {
+ Ok(Some(evaluate_add_op(&v, &our)?))
+ })
} else {
- Some(our)
+ Ok(Some(our))
}
}
(None, Some(s)) => s.get_raw(key, real_this),
- (None, None) => None,
+ (None, None) => Ok(None),
}
}
}
crates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/val.rs
+++ b/crates/jsonnet-evaluator/src/val.rs
@@ -1,4 +1,7 @@
-use crate::{lazy_binding, Context, FunctionDefault, FunctionRhs, LazyBinding, ObjValue};
+use crate::{
+ create_error, lazy_binding, Context, Error, FunctionDefault, FunctionRhs, LazyBinding,
+ ObjValue, Result,
+};
use closure::closure;
use jsonnet_parser::ParamsDesc;
use std::{
@@ -9,28 +12,28 @@
};
struct LazyValInternals {
- pub f: Box<dyn Fn() -> Val>,
+ pub f: Box<dyn Fn() -> Result<Val>>,
pub cached: RefCell<Option<Val>>,
}
#[derive(Clone)]
pub struct LazyVal(Rc<LazyValInternals>);
impl LazyVal {
- pub fn new(f: Box<dyn Fn() -> Val>) -> Self {
+ pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
LazyVal(Rc::new(LazyValInternals {
f,
cached: RefCell::new(None),
}))
}
- pub fn evaluate(&self) -> Val {
+ pub fn evaluate(&self) -> Result<Val> {
{
let cached = self.0.cached.borrow();
if cached.is_some() {
- return cached.clone().unwrap();
+ return Ok(cached.clone().unwrap());
}
}
- let result = (self.0.f)();
+ let result = (self.0.f)()?;
self.0.cached.borrow_mut().replace(result.clone());
- result
+ Ok(result)
}
}
#[macro_export]
@@ -59,7 +62,7 @@
}
impl FuncDesc {
// TODO: Check for unset variables
- pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Val {
+ pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Result<Val> {
let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();
let future_ctx = Context::new_future();
@@ -80,7 +83,7 @@
new_bindings.insert(
name.as_ref().unwrap().clone(),
lazy_binding!(
- closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))
+ closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
),
);
}
@@ -89,19 +92,49 @@
new_bindings.insert(
param.0.clone(),
lazy_binding!(
- closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))
+ closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
),
);
}
}
let ctx = self
.ctx
- .extend(new_bindings, None, None, None)
+ .extend(new_bindings, None, None, None)?
.into_future(future_ctx);
self.eval_rhs.0(ctx)
}
}
+#[derive(Debug)]
+pub enum ValType {
+ Bool,
+ Null,
+ Str,
+ Num,
+ Arr,
+ Obj,
+ Func,
+}
+impl ValType {
+ pub fn name(&self) -> &'static str {
+ use ValType::*;
+ match self {
+ Bool => "boolean",
+ Null => "null",
+ Str => "string",
+ Num => "number",
+ Arr => "array",
+ Obj => "object",
+ Func => "function",
+ }
+ }
+}
+impl Display for ValType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.name())
+ }
+}
+
#[derive(Debug, PartialEq, Clone)]
pub enum Val {
Bool(bool),
@@ -117,80 +150,44 @@
Intristic(String, String),
}
impl Val {
- pub fn try_cast_bool(self) -> bool {
- match self.unwrap_if_lazy() {
- Val::Bool(v) => v,
- v => panic!("expected bool, got {:?}", v),
+ pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
+ match self.unwrap_if_lazy()? {
+ Val::Bool(v) => Ok(v),
+ v => create_error(Error::TypeMismatch(
+ context,
+ vec![ValType::Bool],
+ v.value_type()?,
+ )),
}
}
- pub fn try_cast_str(self) -> String {
- match self.unwrap_if_lazy() {
- Val::Str(v) => v,
- v => panic!("expected bool, got {:?}", v),
+ pub fn try_cast_str(self, context: &'static str) -> Result<String> {
+ match self.unwrap_if_lazy()? {
+ Val::Str(v) => Ok(v),
+ v => create_error(Error::TypeMismatch(
+ context,
+ vec![ValType::Str],
+ v.value_type()?,
+ )),
}
}
- pub fn unwrap_if_lazy(self) -> Self {
- if let Val::Lazy(v) = self {
- v.evaluate().unwrap_if_lazy()
+ pub fn unwrap_if_lazy(self) -> Result<Self> {
+ Ok(if let Val::Lazy(v) = self {
+ v.evaluate()?.unwrap_if_lazy()?
} else {
self
- }
- }
- pub fn type_of(&self) -> &'static str {
- match self {
- Val::Str(..) => "string",
- Val::Num(..) => "number",
- Val::Arr(..) => "array",
- Val::Obj(..) => "object",
- Val::Func(..) => "function",
- _ => panic!("no native type found"),
- }
+ })
}
-}
-impl Display for Val {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Val::Str(str) => write!(f, "\"{}\"", str)?,
- Val::Num(n) => write!(f, "{}", n)?,
- Val::Arr(values) => {
- write!(f, "[")?;
- let mut first = true;
- for value in values {
- if first {
- first = false;
- } else {
- write!(f, ",")?;
- }
- write!(f, "{}", value)?;
- }
- write!(f, "]")?;
- }
- Val::Obj(value) => {
- write!(f, "{{")?;
- let mut first = true;
- for field in value.fields() {
- if first {
- first = false;
- } else {
- write!(f, ",")?;
- }
- write!(f, "\"{}\":", field)?;
- write!(f, "{}", value.get(&field).unwrap())?;
- }
- write!(f, "}}")?;
- }
- Val::Lazy(lazy) => {
- write!(f, "{}", lazy.evaluate())?;
- }
- Val::Func(_) => {
- write!(f, "<<FUNC>>")?;
- }
- v => panic!("no json equivalent for {:?}", v),
- };
- Ok(())
+ pub fn value_type(&self) -> Result<ValType> {
+ Ok(match self {
+ Val::Str(..) => ValType::Str,
+ Val::Num(..) => ValType::Num,
+ Val::Arr(..) => ValType::Arr,
+ Val::Obj(..) => ValType::Obj,
+ Val::Func(..) => ValType::Func,
+ Val::Bool(_) => ValType::Bool,
+ Val::Null => ValType::Null,
+ Val::Intristic(_, _) => ValType::Func,
+ Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
+ })
}
-}
-
-pub fn bool_val(v: bool) -> Val {
- Val::Bool(v)
}