difftreelog
feat(evaluator) use errors, pass EvaluationState
in: master
7 files changed
crates/jsonnet-evaluator/Cargo.tomldiffbeforeafterboth10jsonnet-parser = { path = "../jsonnet-parser" }10jsonnet-parser = { path = "../jsonnet-parser" }11closure = "0.3.0"11closure = "0.3.0"1213[dev-dependencies]14jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }12jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }1513crates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth1use crate::{1use crate::{2 future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Val,2 future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Result,3 Val,3};4};4use closure::closure;5use closure::closure;5use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};6use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};677rc_fn_helper!(8rc_fn_helper!(8 ContextCreator,9 ContextCreator,9 context_creator,10 context_creator,10 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Context11 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>11);12);121313future_wrapper!(Context, FutureContext);14future_wrapper!(Context, FutureContext);65 ctx.unwrap()66 ctx.unwrap()66 }67 }676868 pub fn with_var(&self, name: String, value: Val) -> Context {69 pub fn with_var(&self, name: String, value: Val) -> Result<Context> {69 let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();70 let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();70 new_bindings.insert(71 new_bindings.insert(71 name,72 name,72 lazy_binding!(73 lazy_binding!(73 closure!(clone value, |_t, _s|lazy_val!(closure!(clone value, ||value.clone())))74 closure!(clone value, |_t, _s|Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))74 ),75 ),75 );76 );76 self.extend(new_bindings, None, None, None)77 self.extend(new_bindings, None, None, None)82 new_dollar: Option<ObjValue>,83 new_dollar: Option<ObjValue>,83 new_this: Option<ObjValue>,84 new_this: Option<ObjValue>,84 new_super_obj: Option<ObjValue>,85 new_super_obj: Option<ObjValue>,85 ) -> Context {86 ) -> Result<Context> {86 let dollar = new_dollar.or_else(|| self.0.dollar.clone());87 let dollar = new_dollar.or_else(|| self.0.dollar.clone());87 let this = new_this.or_else(|| self.0.this.clone());88 let this = new_this.or_else(|| self.0.this.clone());88 let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());89 let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());94 new.insert(k.clone(), v.clone());95 new.insert(k.clone(), v.clone());95 }96 }96 for (k, v) in new_bindings.into_iter() {97 for (k, v) in new_bindings.into_iter() {97 new.insert(k, v.0(this.clone(), super_obj.clone()));98 new.insert(k, v.0(this.clone(), super_obj.clone())?);98 }99 }99 Rc::new(new)100 Rc::new(new)100 };101 };101 Context(Rc::new(ContextInternals {102 Ok(Context(Rc::new(ContextInternals {102 dollar,103 dollar,103 this,104 this,104 super_obj,105 super_obj,105 bindings,106 bindings,106 }))107 })))107 }108 }108}109}109110crates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth1use crate::ValType;2use jsonnet_parser::LocExpr;34#[derive(Debug)]1pub enum Error {}5pub enum Error {6 VariableIsNotDefined(String),7 TypeMismatch(&'static str, Vec<ValType>, ValType),8 NoSuchField(String),910 RuntimeError(String),11}1213#[derive(Clone, Debug)]14pub struct StackTraceElement(pub LocExpr, pub String);15#[derive(Debug)]16pub struct StackTrace(pub Vec<StackTraceElement>);1718#[derive(Debug)]19pub struct LocError(pub Error, pub StackTrace);20pub type Result<V> = std::result::Result<V, LocError>;221crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use crate::{1use crate::{2 binding, bool_val, context_creator, function_default, function_rhs, future_wrapper,2 binding, context_creator, create_error, function_default, function_rhs, future_wrapper,3 lazy_binding, lazy_val, Context, ContextCreator, EvaluationState, FuncDesc, LazyBinding,3 lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,4 ObjMember, ObjValue, Val,4 ObjValue, Result, Val,5};5};6use closure::closure;6use closure::closure;7use jsonnet_parser::{7use jsonnet_parser::{15};15};161617pub fn evaluate_binding(17pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {18 eval_state: EvaluationState,19 b: &BindSpec,20 context_creator: ContextCreator,21) -> (String, LazyBinding) {22 let b = b.clone();18 let b = b.clone();23 if let Some(args) = &b.params {19 if let Some(args) = &b.params {24 let args = args.clone();20 let args = args.clone();25 (21 (26 b.name.clone(),22 b.name.clone(),27 lazy_binding!(move |this, super_obj| lazy_val!(23 lazy_binding!(move |this, super_obj| Ok(lazy_val!(28 closure!(clone b, clone args, clone context_creator, clone eval_state, || evaluate_method(24 closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(29 context_creator.0(this.clone(), super_obj.clone()),25 context_creator.0(this.clone(), super_obj.clone())?,30 eval_state.clone(),31 &b.value,26 &b.value,32 args.clone()27 args.clone()33 ))28 )))34 )),29 ))),35 )30 )36 } else {31 } else {37 (32 (38 b.name.clone(),33 b.name.clone(),39 lazy_binding!(move |this, super_obj| {34 lazy_binding!(move |this, super_obj| {40 lazy_val!(35 Ok(lazy_val!(41 closure!(clone context_creator, clone b, clone eval_state, || evaluate(36 closure!(clone context_creator, clone b, || evaluate(42 context_creator.0(this.clone(), super_obj.clone()),37 context_creator.0(this.clone(), super_obj.clone())?,43 eval_state.clone(),44 &b.value38 &b.value45 ))39 ))46 )40 ))47 }),41 }),48 )42 )49 }43 }50}44}514552pub fn evaluate_method(46pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {53 ctx: Context,54 eval_state: EvaluationState,55 expr: &LocExpr,56 arg_spec: ParamsDesc,57) -> Val {58 Val::Func(FuncDesc {47 Val::Func(FuncDesc {59 ctx,48 ctx,60 params: arg_spec,49 params: arg_spec,61 eval_rhs: function_rhs!(50 eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),62 closure!(clone expr, clone eval_state, |ctx| evaluate(ctx, eval_state.clone(), &expr))63 ),64 eval_default: function_default!(51 eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),65 closure!(clone eval_state, |ctx, default| evaluate(ctx, eval_state.clone(), &default))66 ),67 })52 })68}53}695470pub fn evaluate_field_name(55pub fn evaluate_field_name(71 context: Context,56 context: Context,72 eval_state: EvaluationState,73 field_name: &jsonnet_parser::FieldName,57 field_name: &jsonnet_parser::FieldName,74) -> String {58) -> Result<String> {75 match field_name {59 Ok(match field_name {76 jsonnet_parser::FieldName::Fixed(n) => n.clone(),60 jsonnet_parser::FieldName::Fixed(n) => n.clone(),77 jsonnet_parser::FieldName::Dyn(expr) => {61 jsonnet_parser::FieldName::Dyn(expr) => {78 let name = evaluate(context, eval_state, expr).unwrap_if_lazy();62 evaluate(context, expr)?.try_cast_str("dynamic field name")?79 match name {80 Val::Str(n) => n,81 _ => panic!(82 "dynamic field name can be only evaluated to 'string', got: {:?}",83 name84 ),85 }86 }63 }87 }64 })88}65}896690pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Val {67pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {91 match (op, b) {68 Ok(match (op, b) {92 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()),69 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,93 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),70 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),94 (op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),71 (op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),95 }72 })96}73}977498pub fn evaluate_add_op(a: &Val, b: &Val) -> Val {75pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {99 match (a, b) {76 Ok(match (a, b) {100 (Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),77 (Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),101 (Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),78 (Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),102 (Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),79 (Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),103 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),80 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),104 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),81 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),105 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),82 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),106 _ => panic!("can't add: {:?} and {:?}", a, b),83 _ => panic!("can't add: {:?} and {:?}", a, b),107 }84 })108}85}10986110pub fn evaluate_binary_op(87pub fn evaluate_binary_op(context: Context, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {111 context: Context,112 eval_state: EvaluationState,113 a: &Val,114 op: BinaryOpType,115 b: &Val,116) -> Val {117 match (a, op, b) {88 Ok(match (a, op, b) {118 (Val::Lazy(a), o, b) => evaluate_binary_op(context, eval_state, &a.evaluate(), o, b),89 (Val::Lazy(a), o, b) => evaluate_binary_op(context, &a.evaluate()?, o, b)?,119 (a, o, Val::Lazy(b)) => evaluate_binary_op(context, eval_state, a, o, &b.evaluate()),90 (a, o, Val::Lazy(b)) => evaluate_binary_op(context, a, o, &b.evaluate()?)?,12091121 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b),92 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,12293123 (Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => bool_val(v1 != v2),94 (Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => Val::Bool(v1 != v2),12495125 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),96 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),126 (Val::Str(format), BinaryOpType::Mod, args) => evaluate(97 (Val::Str(format), BinaryOpType::Mod, args) => evaluate(127 context98 context128 .with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))99 .with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))?129 .with_var(100 .with_var(130 "__tmp__args__".to_owned(),101 "__tmp__args__".to_owned(),131 match args {102 match args {132 Val::Arr(v) => Val::Arr(v.clone()),103 Val::Arr(v) => Val::Arr(v.clone()),133 v => Val::Arr(vec![v.clone()]),104 v => Val::Arr(vec![v.clone()]),134 },105 },135 ),106 )?,136 eval_state,137 &el!(Expr::Apply(107 &el!(Expr::Apply(138 el!(Expr::Index(108 el!(Expr::Index(139 el!(Expr::Var("std".to_owned())),109 el!(Expr::Var("std".to_owned())),144 Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))114 Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))145 ])115 ])146 )),116 )),147 ),117 )?,148118149 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),119 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),150 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),120 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),162 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)132 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)163 }133 }164134165 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => bool_val(v1 < v2),135 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),166 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => bool_val(v1 > v2),136 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),167 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => bool_val(v1 <= v2),137 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),168 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => bool_val(v1 >= v2),138 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),169139170 (Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => bool_val((v1 - v2).abs() < f64::EPSILON),140 (Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => Val::Bool((v1 - v2).abs() < f64::EPSILON),171 (Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => bool_val((v1 - v2).abs() > f64::EPSILON),141 (Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => Val::Bool((v1 - v2).abs() > f64::EPSILON),172142173 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {143 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {174 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)144 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)179 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {149 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {180 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)150 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)181 }151 }182 (a, BinaryOpType::Eq, b) => bool_val(a == b),152 (a, BinaryOpType::Eq, b) => Val::Bool(a == b),183 (a, BinaryOpType::Ne, b) => bool_val(a != b),153 (a, BinaryOpType::Ne, b) => Val::Bool(a != b),184 _ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),154 _ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),185 }155 })186}156}187157188future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);158future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);189future_wrapper!(ObjValue, FutureObjValue);159future_wrapper!(ObjValue, FutureObjValue);190160191pub fn evaluate_comp(161pub fn evaluate_comp(192 context: Context,162 context: Context,193 eval_state: EvaluationState,194 value: &LocExpr,163 value: &LocExpr,195 specs: &[CompSpec],164 specs: &[CompSpec],196) -> Option<Vec<Val>> {165) -> Result<Option<Vec<Val>>> {197 match specs.get(0) {166 Ok(match specs.get(0) {198 None => Some(vec![evaluate(context, eval_state, &value)]),167 None => Some(vec![evaluate(context, &value)?]),199 Some(CompSpec::IfSpec(IfSpecData(cond))) => {168 Some(CompSpec::IfSpec(IfSpecData(cond))) => {200 match evaluate(context.clone(), eval_state.clone(), &cond).unwrap_if_lazy() {169 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {201 Val::Bool(false) => None,202 Val::Bool(true) => evaluate_comp(context, eval_state, value, &specs[1..]),170 evaluate_comp(context, value, &specs[1..])?203 _ => panic!("if expression evaluated to non-boolean value"),204 }171 } else {172 None173 }205 }174 }206 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {175 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {207 match evaluate(context.clone(), eval_state.clone(), &expr).unwrap_if_lazy() {176 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {208 Val::Arr(list) => {177 Val::Arr(list) => {209 let mut out = Vec::new();178 let mut out = Vec::new();210 for item in list {179 for item in list {211 let item = item.clone();180 let item = item.clone();212 out.push(evaluate_comp(181 out.push(evaluate_comp(213 context.with_var(var.clone(), item),182 context.with_var(var.clone(), item)?,214 eval_state.clone(),215 value,183 value,216 &specs[1..],184 &specs[1..],217 ));185 )?);218 }186 }219 Some(out.iter().flatten().flatten().cloned().collect())187 Some(out.iter().flatten().flatten().cloned().collect())220 }188 }221 _ => panic!("for expression evaluated to non-iterable value"),189 _ => panic!("for expression evaluated to non-iterable value"),222 }190 }223 }191 }224 }192 })225}193}226194227// TODO: Asserts195// TODO: Asserts228pub fn evaluate_object(context: Context, eval_state: EvaluationState, object: ObjBody) -> ObjValue {196pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {229 match object {197 Ok(match object {230 ObjBody::MemberList(members) => {198 ObjBody::MemberList(members) => {231 let new_bindings = FutureNewBindings::new();199 let new_bindings = FutureNewBindings::new();232 let future_this = FutureObjValue::new();200 let future_this = FutureObjValue::new();233 let context_creator = context_creator!(201 let context_creator = context_creator!(234 closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {202 closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {235 context.clone().extend(203 Ok(context.clone().extend(236 new_bindings.clone().unwrap(),204 new_bindings.clone().unwrap(),237 context.clone().dollar().clone().or_else(||this.clone()),205 context.clone().dollar().clone().or_else(||this.clone()),238 Some(this.unwrap()),206 Some(this.unwrap()),239 super_obj207 super_obj240 )208 )?)241 })209 })242 );210 );243 {211 {248 Member::BindStmt(b) => Some(b.clone()),216 Member::BindStmt(b) => Some(b.clone()),249 _ => None,217 _ => None,250 })218 })251 .map(|b| evaluate_binding(eval_state.clone(), &b, context_creator.clone()))219 .map(|b| evaluate_binding(&b, context_creator.clone()))252 {220 {253 bindings.insert(n, b);221 bindings.insert(n, b);254 }222 }265 visibility,233 visibility,266 value,234 value,267 }) => {235 }) => {268 let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);236 let name = evaluate_field_name(context.clone(), &name)?;269 new_members.insert(237 new_members.insert(270 name,238 name,271 ObjMember {239 ObjMember {272 add: plus,240 add: plus,273 visibility: visibility.clone(),241 visibility: visibility.clone(),274 invoke: binding!(242 invoke: binding!(275 closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {243 closure!(clone value, clone context_creator, |this, super_obj| {276 let context = context_creator.0(this, super_obj);244 let context = context_creator.0(this, super_obj)?;277 // TODO: Assert245 // TODO: Assert278 evaluate(246 evaluate(279 context,247 context,280 eval_state.clone(),281 &value,248 &value,282 ).unwrap_if_lazy()249 )?.unwrap_if_lazy()283 })250 })284 ),251 ),285 },252 },291 value,258 value,292 ..259 ..293 }) => {260 }) => {294 let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);261 let name = evaluate_field_name(context.clone(), &name)?;295 new_members.insert(262 new_members.insert(296 name,263 name,297 ObjMember {264 ObjMember {298 add: false,265 add: false,299 visibility: Visibility::Hidden,266 visibility: Visibility::Hidden,300 invoke: binding!(267 invoke: binding!(301 closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {268 closure!(clone value, clone context_creator, |this, super_obj| {302 // TODO: Assert269 // TODO: Assert303 evaluate_method(270 Ok(evaluate_method(304 context_creator.0(this, super_obj),271 context_creator.0(this, super_obj)?,305 eval_state.clone(),306 &value.clone(),272 &value.clone(),307 params.clone(),273 params.clone(),308 )274 ))309 })275 })310 ),276 ),311 },277 },318 future_this.fill(ObjValue::new(None, Rc::new(new_members)))284 future_this.fill(ObjValue::new(None, Rc::new(new_members)))319 }285 }320 _ => todo!(),286 _ => todo!(),321 }287 })322}288}323289324pub fn evaluate(context: Context, eval_state: EvaluationState, expr: &LocExpr) -> Val {290pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {325 use Expr::*;291 use Expr::*;326 eval_state.clone().push(expr.clone(), "expr".to_owned(), || {292 push(expr.clone(), "expr".to_owned(), || {327 let LocExpr(expr, loc) = expr;293 let LocExpr(expr, loc) = expr;328 match &**expr {294 Ok(match &**expr {329 Literal(LiteralType::This) => Val::Obj(295 Literal(LiteralType::This) => Val::Obj(330 context296 context331 .this()297 .this()341 Literal(LiteralType::True) => Val::Bool(true),307 Literal(LiteralType::True) => Val::Bool(true),342 Literal(LiteralType::False) => Val::Bool(false),308 Literal(LiteralType::False) => Val::Bool(false),343 Literal(LiteralType::Null) => Val::Null,309 Literal(LiteralType::Null) => Val::Null,344 Parened(e) => evaluate(context, eval_state.clone(), e),310 Parened(e) => evaluate(context, e)?,345 Str(v) => Val::Str(v.clone()),311 Str(v) => Val::Str(v.clone()),346 Num(v) => Val::Num(*v),312 Num(v) => Val::Num(*v),347 BinaryOp(v1, o, v2) => {313 BinaryOp(v1, o, v2) => {348 let a = evaluate(context.clone(), eval_state.clone(), v1).unwrap_if_lazy();314 let a = evaluate(context.clone(), v1)?.unwrap_if_lazy()?;349 let op = *o;315 let op = *o;350 let b = evaluate(context.clone(), eval_state.clone(), v2).unwrap_if_lazy();316 let b = evaluate(context.clone(), v2)?.unwrap_if_lazy()?;351 evaluate_binary_op(317 evaluate_binary_op(context, &a, op, &b)?352 context,353 eval_state,354 &a,355 op,356 &b,357 )358 },318 }359 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, eval_state, v)),319 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,360 Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy(),320 Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,361 Index(value, index) => {321 Index(value, index) => {362 match (322 match (363 evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy(),323 evaluate(context.clone(), value)?.unwrap_if_lazy()?,364 evaluate(context.clone(), eval_state.clone(), index),324 evaluate(context.clone(), index)?,365 ) {325 ) {366 (Val::Obj(v), Val::Str(s)) => v326 (Val::Obj(v), Val::Str(s)) => {327 if let Some(v) = v.get(&s)? {367 .get(&s)328 v.unwrap_if_lazy()?368 .unwrap_or_else(closure!(clone context, clone eval_state, || {369 if let Some(n) = v.get("__intristic_namespace__") {329 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {370 if let Val::Str(n) = n.unwrap_if_lazy() {371 Val::Intristic(n, s)330 Val::Intristic(n, s)372 } else {373 panic!("__intristic_namespace__ should be string");374 }375 } else {331 } else {376 panic!("{} not found in {:?}", s, v)332 create_error(crate::Error::NoSuchField(s))?377 }333 }378 }))334 }379 .unwrap_if_lazy(),380 (Val::Arr(v), Val::Num(n)) => v335 (Val::Arr(v), Val::Num(n)) => v381 .get(n as usize)336 .get(n as usize)382 .unwrap_or_else(|| panic!("out of bounds"))337 .unwrap_or_else(|| panic!("out of bounds"))392 let future_context = Context::new_future();347 let future_context = Context::new_future();393348394 let context_creator = context_creator!(349 let context_creator = context_creator!(395 closure!(clone future_context, |_, _| future_context.clone().unwrap())350 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))396 );351 );397352398 for (k, v) in bindings353 for (k, v) in bindings399 .iter()354 .iter()400 .map(|b| evaluate_binding(eval_state.clone(), b, context_creator.clone()))355 .map(|b| evaluate_binding(b, context_creator.clone()))401 {356 {402 new_bindings.insert(k, v);357 new_bindings.insert(k, v);403 }358 }404359405 let context = context360 let context = context406 .extend(new_bindings, None, None, None)361 .extend(new_bindings, None, None, None)?407 .into_future(future_context);362 .into_future(future_context);408 evaluate(context, eval_state.clone(), &returned.clone())363 evaluate(context, &returned.clone())?409 }364 }410 Arr(items) => {365 Arr(items) => {411 let mut out = Vec::with_capacity(items.len());366 let mut out = Vec::with_capacity(items.len());412 for item in items {367 for item in items {413 out.push(evaluate(context.clone(), eval_state.clone(), item));368 out.push(evaluate(context.clone(), item)?);414 }369 }415 Val::Arr(out)370 Val::Arr(out)416 }371 }417 ArrComp(expr, compspecs) => {372 ArrComp(expr, compspecs) => Val::Arr(373 // First compspec should be forspec, so no "None" possible here418 Val::Arr(evaluate_comp(context, eval_state, expr, compspecs).unwrap())374 evaluate_comp(context, expr, compspecs)?.unwrap(),419 }375 ),420 Obj(body) => Val::Obj(evaluate_object(context, eval_state, body.clone())),376 Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),421 Apply(value, ArgsDesc(args)) => {377 Apply(value, ArgsDesc(args)) => {422 let value = evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy();378 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;423 match value {379 match value {424 // TODO: Capture context of application380 // TODO: Capture context of application425 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {381 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {426 // arr/string/function382 // arr/string/function427 ("std", "length") => {383 ("std", "length") => {428 assert_eq!(args.len(), 1);384 assert_eq!(args.len(), 1);429 let expr = &args.get(0).unwrap().1;385 let expr = &args.get(0).unwrap().1;430 match evaluate(context, eval_state.clone(), expr) {386 match evaluate(context, expr)? {431 Val::Str(n) => Val::Num(n.chars().count() as f64),387 Val::Str(n) => Val::Num(n.chars().count() as f64),432 Val::Arr(i) => Val::Num(i.len() as f64),388 Val::Arr(i) => Val::Num(i.len() as f64),433 v => panic!("can't get length of {:?}", v),389 v => panic!("can't get length of {:?}", v),437 ("std", "type") => {393 ("std", "type") => {438 assert_eq!(args.len(), 1);394 assert_eq!(args.len(), 1);439 let expr = &args.get(0).unwrap().1;395 let expr = &args.get(0).unwrap().1;440 Val::Str(evaluate(context, eval_state, expr).type_of().to_owned())396 Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())441 }397 }442 // length, idx=>any398 // length, idx=>any443 ("std", "makeArray") => {399 ("std", "makeArray") => {444 assert_eq!(args.len(), 2);400 assert_eq!(args.len(), 2);445 if let (Val::Num(v), Val::Func(d)) = (401 if let (Val::Num(v), Val::Func(d)) = (446 evaluate(context.clone(), eval_state.clone(), &args[0].1),402 evaluate(context.clone(), &args[0].1)?,447 evaluate(context, eval_state, &args[1].1),403 evaluate(context, &args[1].1)?,448 ) {404 ) {449 assert!(v > 0.0);405 assert!(v > 0.0);450 let mut out = Vec::with_capacity(v as usize);406 let mut out = Vec::with_capacity(v as usize);451 for i in 0..v as usize {407 for i in 0..v as usize {452 out.push(d.evaluate(vec![(None, Val::Num(i as f64))]))408 out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)453 }409 }454 Val::Arr(out)410 Val::Arr(out)455 } else {411 } else {459 // string415 // string460 ("std", "codepoint") => {416 ("std", "codepoint") => {461 assert_eq!(args.len(), 1);417 assert_eq!(args.len(), 1);462 if let Val::Str(s) = evaluate(context, eval_state, &args[0].1) {418 if let Val::Str(s) = evaluate(context, &args[0].1)? {463 assert!(419 assert!(464 s.chars().count() == 1,420 s.chars().count() == 1,465 "std.codepoint should receive single char string"421 "std.codepoint should receive single char string"473 ("std", "objectFieldsEx") => {429 ("std", "objectFieldsEx") => {474 assert_eq!(args.len(), 2);430 assert_eq!(args.len(), 2);475 if let (Val::Obj(body), Val::Bool(_include_hidden)) = (431 if let (Val::Obj(body), Val::Bool(_include_hidden)) = (476 evaluate(context.clone(), eval_state.clone(), &args[0].1),432 evaluate(context.clone(), &args[0].1)?,477 evaluate(context, eval_state, &args[1].1),433 evaluate(context, &args[1].1)?,478 ) {434 ) {479 // TODO: handle visibility (_include_hidden)435 // TODO: handle visibility (_include_hidden)480 Val::Arr(body.fields().into_iter().map(Val::Str).collect())436 Val::Arr(body.fields().into_iter().map(Val::Str).collect())491 (447 (492 a.clone().0,448 a.clone().0,493 Val::Lazy(lazy_val!(449 Val::Lazy(lazy_val!(494 closure!(clone context, clone a, clone eval_state, || evaluate(context.clone(), eval_state.clone(), &a.clone().1))450 closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))495 )),451 )),496 )452 )497 })453 })498 .collect(),454 .collect(),499 ),455 )?,500 _ => panic!("{:?} is not a function", value),456 _ => panic!("{:?} is not a function", value),501 }457 }502 }458 }503 Function(params, body) => evaluate_method(context, eval_state, body, params.clone()),459 Function(params, body) => evaluate_method(context, body, params.clone()),504 AssertExpr(AssertStmt(value, msg), returned) => {460 AssertExpr(AssertStmt(value, msg), returned) => {505 if evaluate(context.clone(), eval_state.clone(), &value).try_cast_bool() {461 if evaluate(context.clone(), &value)?462 .try_cast_bool("assertion condition should be boolean")?463 {506 evaluate(context, eval_state, returned)464 evaluate(context, returned)?507 }else {465 } else if let Some(msg) = msg {508 if let Some(msg) = msg {509 panic!("assertion failed ({:?}): {}", value, evaluate(context, eval_state, msg).try_cast_str());466 panic!(467 "assertion failed ({:?}): {}",468 value,469 evaluate(context, msg)?470 .try_cast_str("assertion message should be string")?471 );510 } else {472 } else {511 panic!("assertion failed ({:?}): no message", value);473 panic!("assertion failed ({:?}): no message", value);512 }474 }513 }514 },475 }515 Error(e) => panic!("error: {}", evaluate(context, eval_state, e)),476 Error(e) => create_error(crate::Error::RuntimeError(477 evaluate(context, e)?.try_cast_str("error text should be string")?,478 ))?,516 IfElse {479 IfElse {517 cond,480 cond,518 cond_then,481 cond_then,519 cond_else,482 cond_else,520 } => match evaluate(context.clone(), eval_state.clone(), &cond.0).unwrap_if_lazy() {483 } => {484 if evaluate(context.clone(), &cond.0)?485 .try_cast_bool("if condition should be boolean")?486 {521 Val::Bool(true) => evaluate(context, eval_state.clone(), cond_then),487 evaluate(context, cond_then)?488 } else {522 Val::Bool(false) => match cond_else {489 match cond_else {523 Some(v) => evaluate(context, eval_state, v),490 Some(v) => evaluate(context, v)?,524 None => Val::Bool(false),491 None => Val::Bool(false),525 },492 }526 v => panic!("if condition evaluated to {:?} (boolean needed instead)", v),493 }527 },494 }528 _ => panic!(495 _ => panic!(529 "evaluation not implemented: {:?}",496 "evaluation not implemented: {:?}",530 LocExpr(expr.clone(), loc.clone())497 LocExpr(expr.clone(), loc.clone())531 ),498 ),532 }499 })533 })500 })534}501}535502crates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth22rc_fn_helper!(22rc_fn_helper!(23 Binding,23 Binding,24 binding,24 binding,25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Val25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>26);26);27rc_fn_helper!(27rc_fn_helper!(28 LazyBinding,28 LazyBinding,29 lazy_binding,29 lazy_binding,30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> LazyVal30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>31);31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Val);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);33rc_fn_helper!(33rc_fn_helper!(34 FunctionDefault,34 FunctionDefault,35 function_default,35 function_default,36 dyn Fn(Context, LocExpr) -> Val36 dyn Fn(Context, LocExpr) -> Result<Val>37);37);383839pub struct FileData(String, LocExpr, Option<Val>);39#[derive(Default)]40#[derive(Default)]40pub struct EvaluationStateInternals {41pub struct EvaluationStateInternals {41 /// Used for stack-overflows and stacktraces42 /// Used for stack-overflows and stacktraces42 stack: RefCell<Vec<(LocExpr, String)>>,43 stack: RefCell<Vec<StackTraceElement>>,43 /// Contains file source codes and evaluated results for imports and pretty printing stacktraces44 /// Contains file source codes and evaluated results for imports and pretty printing stacktraces44 files: RefCell<HashMap<String, (String, LocExpr, Option<Val>)>>,45 files: RefCell<HashMap<String, FileData>>,45 globals: RefCell<HashMap<String, Val>>,46 globals: RefCell<HashMap<String, Val>>,46}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}476148#[derive(Default, Clone)]62#[derive(Default, Clone)]49pub struct EvaluationState(Rc<EvaluationStateInternals>);63pub struct EvaluationState(Rc<EvaluationStateInternals>);50impl EvaluationState {64impl EvaluationState {51 pub fn add_file(&self, name: String, code: String) -> Result<(), Box<dyn std::error::Error>> {65 pub fn add_file(66 &self,67 name: String,68 code: String,69 ) -> std::result::Result<(), Box<dyn std::error::Error>> {52 self.0.files.borrow_mut().insert(70 self.0.files.borrow_mut().insert(53 name.clone(),71 name.clone(),54 (72 FileData(55 code.clone(),73 code.clone(),56 parse(74 parse(57 &code,75 &code,58 &ParserSettings {76 &ParserSettings {59 file_name: name.clone(),77 file_name: name,60 loc_data: true,78 loc_data: true,61 },79 },62 )?,80 )?,668467 Ok(())85 Ok(())68 }86 }69 pub fn evaluate_file(&self, name: &str) -> Result<Val, Box<dyn std::error::Error>> {87 pub fn evaluate_file(&self, name: &str) -> Result<Val> {88 self.begin_state();70 let expr: LocExpr = {89 let expr: LocExpr = {71 let ro_map = self.0.files.borrow();90 let ro_map = self.0.files.borrow();72 let value = ro_map91 let value = ro_map77 }96 }78 value.1.clone()97 value.1.clone()79 };98 };80 let value = evaluate(self.create_default_context(), self.clone(), &expr);99 let value = evaluate(self.create_default_context()?, &expr)?;81 {100 {82 self.0101 self.083 .files102 .files87 .2106 .288 .replace(value.clone());107 .replace(value.clone());89 }108 }109 self.end_state();90 Ok(value)110 Ok(value)91 }111 }9211293 pub fn parse_evaluate_raw(&self, code: &str) -> Val {113 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {94 let parsed = parse(114 let parsed = parse(95 &code,115 &code,96 &ParserSettings {116 &ParserSettings {97 file_name: "raw.jsonnet".to_owned(),117 file_name: "raw.jsonnet".to_owned(),98 loc_data: true,118 loc_data: true,99 },119 },100 );120 );121 self.begin_state();101 evaluate(122 let value = evaluate(self.create_default_context()?, &parsed.unwrap());102 self.create_default_context(),123 self.end_state();103 self.clone(),124 value104 &parsed.unwrap(),105 )106 }125 }107126108 pub fn add_stdlib(&self) {127 pub fn add_stdlib(&self) {128 self.begin_state();109 use jsonnet_stdlib::STDLIB_STR;129 use jsonnet_stdlib::STDLIB_STR;110 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())130 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())111 .unwrap();131 .unwrap();112 let val = self.evaluate_file("std.jsonnet").unwrap();132 let val = self.evaluate_file("std.jsonnet").unwrap();113 self.0.globals.borrow_mut().insert("std".to_owned(), val);133 self.0.globals.borrow_mut().insert("std".to_owned(), val);134 self.end_state();114 }135 }115136116 pub fn create_default_context(&self) -> Context {137 pub fn create_default_context(&self) -> Result<Context> {117 let globals = self.0.globals.borrow();138 let globals = self.0.globals.borrow();118 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();139 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();119 for (name, value) in globals.iter() {140 for (name, value) in globals.iter() {120 new_bindings.insert(141 new_bindings.insert(121 name.clone(),142 name.clone(),122 lazy_binding!(143 lazy_binding!(123 closure!(clone value, |_self, _super_obj| lazy_val!(closure!(clone value, ||value.clone())))144 closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))124 ),145 ),125 );146 );126 }147 }131 self.0.stack.borrow_mut().push((e, comment));152 self.0153 .stack154 .borrow_mut()155 .push(StackTraceElement(e, comment));132 let result = f();156 let result = f();133 self.0.stack.borrow_mut().pop();157 self.0.stack.borrow_mut().pop();134 result158 result135 }159 }136 pub fn print_stack_trace(&self) {160 pub fn print_stack_trace(&self) {137 for e in self.stack_trace() {161 for e in self.stack_trace().0 {138 println!("{:?} - {:?}", e.0, e.1)162 println!("{:?} - {:?}", e.0, e.1)139 }163 }140 }164 }141 pub fn stack_trace(&self) -> Vec<(LocExpr, String)> {165 pub fn stack_trace(&self) -> StackTrace {142 self.0166 StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())143 .stack144 .borrow()145 .iter()146 .rev()147 .map(|e| e.clone())148 .collect()149 }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 }150}178}151179152#[cfg(test)]180#[cfg(test)]153pub mod tests {181pub mod tests {154 use super::{evaluate, Context, Val};182 use super::Val;155 use crate::EvaluationState;183 use crate::EvaluationState;156 use jsonnet_parser::*;184 use jsonnet_parser::*;157185176 let state = EvaluationState::default();204 let state = EvaluationState::default();177 state.add_stdlib();205 state.add_stdlib();178 assert_eq!(206 assert_eq!(179 state.parse_evaluate_raw(r#"std.base64("test") == "dGVzdA==""#),207 state208 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)209 .unwrap(),180 Val::Bool(true)210 Val::Bool(true)181 );211 );182 }212 }282 };312 };283 }313 }284314285 /// Sanity checking, before trusting to another tests315 /*286 #[test]316 /// Sanity checking, before trusting to another tests287 fn equality_operator() {317 #[test]288 assert_eval!("2 == 2");318 fn equality_operator() {289 assert_eval_neg!("2 != 2");319 assert_eval!("2 == 2");290 assert_eval!("2 != 3");320 assert_eval_neg!("2 != 2");291 assert_eval_neg!("2 == 3");321 assert_eval!("2 != 3");292 assert_eval!("'Hello' == 'Hello'");322 assert_eval_neg!("2 == 3");293 assert_eval_neg!("'Hello' != 'Hello'");323 assert_eval!("'Hello' == 'Hello'");294 assert_eval!("'Hello' != 'World'");324 assert_eval_neg!("'Hello' != 'Hello'");295 assert_eval_neg!("'Hello' == 'World'");325 assert_eval!("'Hello' != 'World'");296 }326 assert_eval_neg!("'Hello' == 'World'");297327 }298 #[test]328299 fn math_evaluation() {329 #[test]300 assert_eval!("2 + 2 * 2 == 6");330 fn math_evaluation() {301 assert_eval!("3 + (2 + 2 * 2) == 9");331 assert_eval!("2 + 2 * 2 == 6");302 }332 assert_eval!("3 + (2 + 2 * 2) == 9");303333 }304 #[test]334305 fn string_concat() {335 #[test]306 assert_eval!("'Hello' + 'World' == 'HelloWorld'");336 fn string_concat() {307 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");337 assert_eval!("'Hello' + 'World' == 'HelloWorld'");308 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");338 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");309 }339 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");310340 }311 #[test]341312 fn local() {342 #[test]313 assert_eval!("local a = 2; local b = 3; a + b == 5");343 fn local() {314 assert_eval!("local a = 1, b = a + 1; a + b == 3");344 assert_eval!("local a = 2; local b = 3; a + b == 5");315 assert_eval!("local a = 1; local a = 2; a == 2");345 assert_eval!("local a = 1, b = a + 1; a + b == 3");316 }346 assert_eval!("local a = 1; local a = 2; a == 2");317347 }318 #[test]348319 fn object_lazyness() {349 #[test]320 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);350 fn object_lazyness() {321 }351 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);322352 }323 #[test]353324 fn object_inheritance() {354 #[test]325 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);355 fn object_inheritance() {326 }356 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);327357 }328 #[test]358329 fn test_object() {359 #[test]330 assert_json!("{a:2}", r#"{"a":2}"#);360 fn test_object() {331 assert_json!("{a:2+2}", r#"{"a":4}"#);361 assert_json!("{a:2}", r#"{"a":2}"#);332 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);362 assert_json!("{a:2+2}", r#"{"a":4}"#);333 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);363 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);334 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);364 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);335 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);365 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);336 assert_json!(366 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);337 r#"367 assert_json!(338 {368 r#"339 name: "Alice",369 {340 welcome: "Hello " + self.name + "!",370 name: "Alice",341 }371 welcome: "Hello " + self.name + "!",342 "#,372 }343 r#"{"name":"Alice","welcome":"Hello Alice!"}"#373 "#,344 );374 r#"{"name":"Alice","welcome":"Hello Alice!"}"#345 assert_json!(375 );346 r#"376 assert_json!(347 {377 r#"348 name: "Alice",378 {349 welcome: "Hello " + self.name + "!",379 name: "Alice",350 } + {380 welcome: "Hello " + self.name + "!",351 name: "Bob"381 } + {352 }382 name: "Bob"353 "#,383 }354 r#"{"name":"Bob","welcome":"Hello Bob!"}"#384 "#,355 );385 r#"{"name":"Bob","welcome":"Hello Bob!"}"#356 }386 );357387 }358 #[test]388359 fn functions() {389 #[test]360 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");390 fn functions() {361 assert_json!(391 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");362 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,392 assert_json!(363 r#""HelloDearWorld""#393 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,364 );394 r#""HelloDearWorld""#365 }395 );366396 }367 #[test]397368 fn local_methods() {398 #[test]369 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");399 fn local_methods() {370 assert_json!(400 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");371 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,401 assert_json!(372 r#""HelloDearWorld""#402 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,373 );403 r#""HelloDearWorld""#374 }404 );375405 }376 #[test]406377 fn object_locals() {407 #[test]378 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);408 fn object_locals() {379 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);409 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);380 assert_json!(410 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);381 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,411 assert_json!(382 r#"{"test":{"test":4}}"#412 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,383 );413 r#"{"test":{"test":4}}"#384 }414 );385415 }386 #[test]416387 fn direct_self() {417 #[test]388 println!(418 fn direct_self() {389 "{:#?}",419 println!(390 eval!(420 "{:#?}",391 r#"421 eval!(392 {422 r#"393 local me = self,423 {394 a: 3,424 local me = self,395 b(): me.a,425 a: 3,396 }426 b(): me.a,397 "#427 }398 )428 "#399 );429 )400 }430 );401431 }402 #[test]432403 fn indirect_self() {433 #[test]404 // `self` assigned to `me` was lost when being434 fn indirect_self() {405 // referenced from field435 // `self` assigned to `me` was lost when being406 eval_stdlib!(436 // referenced from field407 r#"{437 eval_stdlib!(408 local me = self,438 r#"{409 a: 3,439 local me = self,410 b: me.a,440 a: 3,411 }.b"#441 b: me.a,412 );442 }.b"#413 }443 );414444 }415 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly445416 #[test]446 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly417 fn std_assert_ok() {447 #[test]418 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");448 fn std_assert_ok() {419 }449 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");420450 }421 #[test]451422 #[should_panic]452 #[test]423 fn std_assert_failure() {453 #[should_panic]424 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");454 fn std_assert_failure() {425 }455 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");426456 }427 #[test]457428 fn string_is_string() {458 #[test]429 assert_eq!(459 fn string_is_string() {430 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),460 assert_eq!(431 Val::Bool(false)461 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),432 );462 Val::Bool(false)433 }463 );434464 }435 #[test]465436 fn base64_works() {466 #[test]437 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);467 fn base64_works() {438 }468 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);439469 }440 #[test]470441 fn utf8_chars() {471 #[test]442 assert_json_stdlib!(472 fn utf8_chars() {443 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,473 assert_json_stdlib!(444 r#"{"c":128526,"l":1}"#474 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,445 )475 r#"{"c":128526,"l":1}"#446 }476 )447477 }448 #[test]478449 fn json() {479 #[test]450 assert_json_stdlib!(480 fn json() {451 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,481 assert_json_stdlib!(452 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#482 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,453 );483 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#454 }484 );455485 }456 #[test]486457 fn test() {487 #[test]458 assert_json_stdlib!(488 fn test() {459 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,489 assert_json_stdlib!(460 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"490 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,461 );491 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"462 }492 );463493 }464 #[test]494465 fn sjsonnet() {495 #[test]466 eval!(496 fn sjsonnet() {467 r#"497 eval!(468 local x0 = {k: 1};498 r#"469 local x1 = {k: x0.k + x0.k};499 local x0 = {k: 1};470 local x2 = {k: x1.k + x1.k};500 local x1 = {k: x0.k + x0.k};471 local x3 = {k: x2.k + x2.k};501 local x2 = {k: x1.k + x1.k};472 local x4 = {k: x3.k + x3.k};502 local x3 = {k: x2.k + x2.k};473 local x5 = {k: x4.k + x4.k};503 local x4 = {k: x3.k + x3.k};474 local x6 = {k: x5.k + x5.k};504 local x5 = {k: x4.k + x4.k};475 local x7 = {k: x6.k + x6.k};505 local x6 = {k: x5.k + x5.k};476 local x8 = {k: x7.k + x7.k};506 local x7 = {k: x6.k + x6.k};477 local x9 = {k: x8.k + x8.k};507 local x8 = {k: x7.k + x7.k};478 local x10 = {k: x9.k + x9.k};508 local x9 = {k: x8.k + x8.k};479 local x11 = {k: x10.k + x10.k};509 local x10 = {k: x9.k + x9.k};480 local x12 = {k: x11.k + x11.k};510 local x11 = {k: x10.k + x10.k};481 local x13 = {k: x12.k + x12.k};511 local x12 = {k: x11.k + x11.k};482 local x14 = {k: x13.k + x13.k};512 local x13 = {k: x12.k + x12.k};483 local x15 = {k: x14.k + x14.k};513 local x14 = {k: x13.k + x13.k};484 local x16 = {k: x15.k + x15.k};514 local x15 = {k: x14.k + x14.k};485 local x17 = {k: x16.k + x16.k};515 local x16 = {k: x15.k + x15.k};486 local x18 = {k: x17.k + x17.k};516 local x17 = {k: x16.k + x16.k};487 local x19 = {k: x18.k + x18.k};517 local x18 = {k: x17.k + x17.k};488 local x20 = {k: x19.k + x19.k};518 local x19 = {k: x18.k + x18.k};489 local x21 = {k: x20.k + x20.k};519 local x20 = {k: x19.k + x19.k};490 x21.k520 local x21 = {k: x20.k + x20.k};491 "#521 x21.k492 );522 "#493 }523 );524 }525 */494}526}495527crates/jsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use crate::{evaluate_add_op, Binding, Val};1use crate::{evaluate_add_op, Binding, Result, Val};2use jsonnet_parser::Visibility;2use jsonnet_parser::Visibility;3use std::{3use std::{4 cell::RefCell,4 cell::RefCell,32 write!(f, " + ")?;32 write!(f, " + ")?;33 }33 }34 let mut debug = f.debug_struct("ObjValue");34 let mut debug = f.debug_struct("ObjValue");35 debug.field("$ptr", &Rc::as_ptr(&self.0));36 for (name, member) in self.0.this_entries.iter() {35 for (name, member) in self.0.this_entries.iter() {37 debug.field(name, member);36 debug.field(name, member);38 }37 }39 debug.finish_non_exhaustive()38 debug.finish_non_exhaustive()40 // .field("fields", &self.fields())41 // .finish_non_exhaustive()42 }39 }43}40}444171 }68 }72 fields69 fields73 }70 }74 pub fn get(&self, key: &str) -> Option<Val> {71 pub fn get(&self, key: &str) -> Result<Option<Val>> {75 if let Some(v) = self.0.value_cache.borrow().get(key) {72 if let Some(v) = self.0.value_cache.borrow().get(key) {76 return Some(v.clone());73 return Ok(Some(v.clone()));77 }74 }78 let v = self.get_raw(key, self).map(|v| v.unwrap_if_lazy());75 if let Some(v) = self.get_raw(key, self)? {79 if let Some(v) = v.clone() {76 let v = v.unwrap_if_lazy()?;80 self.0.value_cache.borrow_mut().insert(key.to_owned(), v);77 self.081 }78 .value_cache79 .borrow_mut()80 .insert(key.to_owned(), v.clone());82 v81 Ok(Some(v))82 } else {83 Ok(None)84 }83 }85 }84 fn get_raw(&self, key: &str, real_this: &ObjValue) -> Option<Val> {86 fn get_raw(&self, key: &str, real_this: &ObjValue) -> Result<Option<Val>> {85 match (self.0.this_entries.get(key), &self.0.super_obj) {87 match (self.0.this_entries.get(key), &self.0.super_obj) {86 (Some(k), None) => Some(k.invoke.0(88 (Some(k), None) => Ok(Some(k.invoke.0(87 Some(real_this.clone()),89 Some(real_this.clone()),88 self.0.super_obj.clone(),90 self.0.super_obj.clone(),89 )),91 )?)),90 (Some(k), Some(s)) => {92 (Some(k), Some(s)) => {91 let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone());93 let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone())?;92 if k.add {94 if k.add {93 s.get_raw(key, real_this)95 s.get_raw(key, real_this)?94 .map_or(Some(our.clone()), |v| Some(evaluate_add_op(&v, &our)))96 .map_or(Ok(Some(our.clone())), |v| {97 Ok(Some(evaluate_add_op(&v, &our)?))98 })95 } else {99 } else {96 Some(our)100 Ok(Some(our))97 }101 }98 }102 }99 (None, Some(s)) => s.get_raw(key, real_this),103 (None, Some(s)) => s.get_raw(key, real_this),100 (None, None) => None,104 (None, None) => Ok(None),101 }105 }102 }106 }103}107}crates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{lazy_binding, Context, FunctionDefault, FunctionRhs, LazyBinding, ObjValue};1use crate::{2 create_error, lazy_binding, Context, Error, FunctionDefault, FunctionRhs, LazyBinding,3 ObjValue, Result,4};2use closure::closure;5use closure::closure;3use jsonnet_parser::ParamsDesc;6use jsonnet_parser::ParamsDesc;9};12};101311struct LazyValInternals {14struct LazyValInternals {12 pub f: Box<dyn Fn() -> Val>,15 pub f: Box<dyn Fn() -> Result<Val>>,13 pub cached: RefCell<Option<Val>>,16 pub cached: RefCell<Option<Val>>,14}17}15#[derive(Clone)]18#[derive(Clone)]16pub struct LazyVal(Rc<LazyValInternals>);19pub struct LazyVal(Rc<LazyValInternals>);17impl LazyVal {20impl LazyVal {18 pub fn new(f: Box<dyn Fn() -> Val>) -> Self {21 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {19 LazyVal(Rc::new(LazyValInternals {22 LazyVal(Rc::new(LazyValInternals {20 f,23 f,21 cached: RefCell::new(None),24 cached: RefCell::new(None),22 }))25 }))23 }26 }24 pub fn evaluate(&self) -> Val {27 pub fn evaluate(&self) -> Result<Val> {25 {28 {26 let cached = self.0.cached.borrow();29 let cached = self.0.cached.borrow();27 if cached.is_some() {30 if cached.is_some() {28 return cached.clone().unwrap();31 return Ok(cached.clone().unwrap());29 }32 }30 }33 }31 let result = (self.0.f)();34 let result = (self.0.f)()?;32 self.0.cached.borrow_mut().replace(result.clone());35 self.0.cached.borrow_mut().replace(result.clone());33 result36 Ok(result)34 }37 }35}38}36#[macro_export]39#[macro_export]59}62}60impl FuncDesc {63impl FuncDesc {61 // TODO: Check for unset variables64 // TODO: Check for unset variables62 pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Val {65 pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Result<Val> {63 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();66 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();64 let future_ctx = Context::new_future();67 let future_ctx = Context::new_future();656880 new_bindings.insert(83 new_bindings.insert(81 name.as_ref().unwrap().clone(),84 name.as_ref().unwrap().clone(),82 lazy_binding!(85 lazy_binding!(83 closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))86 closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))84 ),87 ),85 );88 );86 }89 }89 new_bindings.insert(92 new_bindings.insert(90 param.0.clone(),93 param.0.clone(),91 lazy_binding!(94 lazy_binding!(92 closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))95 closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))93 ),96 ),94 );97 );95 }98 }96 }99 }97 let ctx = self100 let ctx = self98 .ctx101 .ctx99 .extend(new_bindings, None, None, None)102 .extend(new_bindings, None, None, None)?100 .into_future(future_ctx);103 .into_future(future_ctx);101 self.eval_rhs.0(ctx)104 self.eval_rhs.0(ctx)102 }105 }103}106}107108#[derive(Debug)]109pub enum ValType {110 Bool,111 Null,112 Str,113 Num,114 Arr,115 Obj,116 Func,117}118impl ValType {119 pub fn name(&self) -> &'static str {120 use ValType::*;121 match self {122 Bool => "boolean",123 Null => "null",124 Str => "string",125 Num => "number",126 Arr => "array",127 Obj => "object",128 Func => "function",129 }130 }131}132impl Display for ValType {133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {134 write!(f, "{}", self.name())135 }136}104137105#[derive(Debug, PartialEq, Clone)]138#[derive(Debug, PartialEq, Clone)]106pub enum Val {139pub enum Val {117 Intristic(String, String),150 Intristic(String, String),118}151}119impl Val {152impl Val {120 pub fn try_cast_bool(self) -> bool {153 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {121 match self.unwrap_if_lazy() {154 match self.unwrap_if_lazy()? {122 Val::Bool(v) => v,155 Val::Bool(v) => Ok(v),123 v => panic!("expected bool, got {:?}", v),156 v => create_error(Error::TypeMismatch(157 context,158 vec![ValType::Bool],159 v.value_type()?,160 )),124 }161 }125 }162 }126 pub fn try_cast_str(self) -> String {163 pub fn try_cast_str(self, context: &'static str) -> Result<String> {127 match self.unwrap_if_lazy() {164 match self.unwrap_if_lazy()? {128 Val::Str(v) => v,165 Val::Str(v) => Ok(v),129 v => panic!("expected bool, got {:?}", v),166 v => create_error(Error::TypeMismatch(167 context,168 vec![ValType::Str],169 v.value_type()?,170 )),130 }171 }131 }172 }132 pub fn unwrap_if_lazy(self) -> Self {173 pub fn unwrap_if_lazy(self) -> Result<Self> {133 if let Val::Lazy(v) = self {174 Ok(if let Val::Lazy(v) = self {134 v.evaluate().unwrap_if_lazy()175 v.evaluate()?.unwrap_if_lazy()?135 } else {176 } else {136 self177 self137 }178 })138 }179 }139 pub fn type_of(&self) -> &'static str {180 pub fn value_type(&self) -> Result<ValType> {140 match self {181 Ok(match self {141 Val::Str(..) => "string",182 Val::Str(..) => ValType::Str,142 Val::Num(..) => "number",183 Val::Num(..) => ValType::Num,143 Val::Arr(..) => "array",184 Val::Arr(..) => ValType::Arr,144 Val::Obj(..) => "object",185 Val::Obj(..) => ValType::Obj,145 Val::Func(..) => "function",186 Val::Func(..) => ValType::Func,187 Val::Bool(_) => ValType::Bool,188 Val::Null => ValType::Null,189 Val::Intristic(_, _) => ValType::Func,146 _ => panic!("no native type found"),190 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,147 }191 })148 }192 }149}193}150impl Display for Val {151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {152 match self {153 Val::Str(str) => write!(f, "\"{}\"", str)?,154 Val::Num(n) => write!(f, "{}", n)?,155 Val::Arr(values) => {156 write!(f, "[")?;157 let mut first = true;158 for value in values {159 if first {160 first = false;161 } else {162 write!(f, ",")?;163 }164 write!(f, "{}", value)?;165 }166 write!(f, "]")?;167 }168 Val::Obj(value) => {169 write!(f, "{{")?;170 let mut first = true;171 for field in value.fields() {172 if first {173 first = false;174 } else {175 write!(f, ",")?;176 }177 write!(f, "\"{}\":", field)?;178 write!(f, "{}", value.get(&field).unwrap())?;179 }180 write!(f, "}}")?;181 }182 Val::Lazy(lazy) => {183 write!(f, "{}", lazy.evaluate())?;184 }185 Val::Func(_) => {186 write!(f, "<<FUNC>>")?;187 }188 v => panic!("no json equivalent for {:?}", v),189 };190 Ok(())191 }192}193194pub fn bool_val(v: bool) -> Val {195 Val::Bool(v)196}197194