difftreelog
feat(evaluator) add importStr
in: master
2 files changed
crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use crate::{2 context_creator, create_error, future_wrapper, lazy_val, push, with_state, Context,3 ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jsonnet_parser::{7 el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,8 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,9 Visibility,10};11use std::{12 collections::{BTreeMap, HashMap},13 rc::Rc,14};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {17 let b = b.clone();18 if let Some(params) = &b.params {19 let params = params.clone();20 (21 b.name.clone(),22 LazyBinding::Bindable(Rc::new(move |this, super_obj| {23 Ok(lazy_val!(24 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(25 context_creator.0(this.clone(), super_obj.clone())?,26 params.clone(),27 b.value.clone(),28 )))29 ))30 })),31 )32 } else {33 (34 b.name.clone(),35 LazyBinding::Bindable(Rc::new(move |this, super_obj| {36 Ok(lazy_val!(closure!(clone context_creator, clone b, ||37 push(b.value.clone(), "thunk".to_owned(), ||{38 evaluate(39 context_creator.0(this.clone(), super_obj.clone())?,40 &b.value41 )42 })43 )))44 })),45 )46 }47}4849pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {50 Val::Func(FuncDesc { ctx, params, body })51}5253pub fn evaluate_field_name(54 context: Context,55 field_name: &jsonnet_parser::FieldName,56) -> Result<Option<String>> {57 Ok(match field_name {58 jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),59 jsonnet_parser::FieldName::Dyn(expr) => {60 let value = evaluate(context, expr)?.unwrap_if_lazy()?;61 if matches!(value, Val::Null) {62 None63 } else {64 Some(value.try_cast_str("dynamic field name")?)65 }66 }67 })68}6970pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {71 Ok(match (op, b) {72 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,73 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),74 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),75 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),76 (op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),77 })78}7980pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {81 Ok(match (a, b) {82 (Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),8384 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),85 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),8687 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),88 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),89 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),90 _ => panic!("can't add: {:?} and {:?}", a, b),91 })92}9394pub fn evaluate_binary_op_special(95 context: Context,96 a: &LocExpr,97 op: BinaryOpType,98 b: &LocExpr,99) -> Result<Val> {100 Ok(101 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {102 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),103 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),104 (a, op, eb) => {105 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?106 }107 },108 )109}110111pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {112 Ok(match (a, op, b) {113 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,114115 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),116117 // Bool X Bool118 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),119 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),120121 // Str X Str122 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),123 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),124 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),125 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),126127 // Num X Num128 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),129 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {130 if *v2 <= f64::EPSILON {131 create_error(crate::Error::DivisionByZero)?132 }133 Val::Num(v1 / v2)134 }135136 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),137138 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),139 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),140 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),141 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),142143 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {144 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)145 }146 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {147 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)148 }149 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {150 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)151 }152 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {153 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)154 }155 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {156 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)157 }158159 _ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),160 })161}162163future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);164future_wrapper!(ObjValue, FutureObjValue);165166#[inline(always)]167pub fn evaluate_comp<T>(168 context: Context,169 value: &impl Fn(Context) -> Result<T>,170 specs: &[CompSpec],171) -> Result<Option<Vec<T>>> {172 Ok(match specs.get(0) {173 None => Some(vec![value(context)?]),174 Some(CompSpec::IfSpec(IfSpecData(cond))) => {175 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {176 evaluate_comp(context, value, &specs[1..])?177 } else {178 None179 }180 }181 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {182 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {183 Val::Arr(list) => {184 let mut out = Vec::new();185 for item in list {186 let item = item.clone().unwrap_if_lazy()?;187 out.push(evaluate_comp(188 context.with_var(var.clone(), item)?,189 value,190 &specs[1..],191 )?);192 }193 Some(out.into_iter().flatten().flatten().collect())194 }195 _ => panic!("for expression evaluated to non-iterable value"),196 }197 }198 })199}200201// TODO: Asserts202pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {203 Ok(match object {204 ObjBody::MemberList(members) => {205 let new_bindings = FutureNewBindings::new();206 let future_this = FutureObjValue::new();207 let context_creator = context_creator!(208 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {209 Ok(context.clone().extend_unbound(210 new_bindings.clone().unwrap(),211 context.clone().dollar().clone().or_else(||this.clone()),212 Some(this.unwrap()),213 super_obj214 )?)215 })216 );217 {218 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();219 for (n, b) in members220 .iter()221 .filter_map(|m| match m {222 Member::BindStmt(b) => Some(b.clone()),223 _ => None,224 })225 .map(|b| evaluate_binding(&b, context_creator.clone()))226 {227 bindings.insert(n, b);228 }229 new_bindings.fill(bindings);230 }231232 let mut new_members = BTreeMap::new();233 for member in members.into_iter() {234 match member {235 Member::Field(FieldMember {236 name,237 plus,238 params: None,239 visibility,240 value,241 }) => {242 let name = evaluate_field_name(context.clone(), &name)?;243 if name.is_none() {244 continue;245 }246 let name = name.unwrap();247 new_members.insert(248 name.clone(),249 ObjMember {250 add: plus,251 visibility: visibility.clone(),252 invoke: LazyBinding::Bindable(Rc::new(253 closure!(clone name, clone value, clone context_creator, |this, super_obj| {254 Ok(LazyVal::new_resolved(push(value.clone(), "object ".to_owned()+&name+" field", ||{255 let context = context_creator.0(this, super_obj)?;256 evaluate(257 context,258 &value,259 )?.unwrap_if_lazy()260 })?))261 }),262 )),263 },264 );265 }266 Member::Field(FieldMember {267 name,268 params: Some(params),269 value,270 ..271 }) => {272 let name = evaluate_field_name(context.clone(), &name)?;273 if name.is_none() {274 continue;275 }276 let name = name.unwrap();277 new_members.insert(278 name,279 ObjMember {280 add: false,281 visibility: Visibility::Hidden,282 invoke: LazyBinding::Bindable(Rc::new(283 closure!(clone value, clone context_creator, |this, super_obj| {284 // TODO: Assert285 Ok(LazyVal::new_resolved(evaluate_method(286 context_creator.0(this, super_obj)?,287 params.clone(),288 value.clone(),289 )))290 }),291 )),292 },293 );294 }295 Member::BindStmt(_) => {}296 Member::AssertStmt(_) => {}297 }298 }299 future_this.fill(ObjValue::new(None, Rc::new(new_members)))300 }301 ObjBody::ObjComp {302 pre_locals,303 key,304 value,305 post_locals,306 compspecs,307 } => {308 let future_this = FutureObjValue::new();309 let mut new_members = BTreeMap::new();310 for (k, v) in evaluate_comp(311 context.clone(),312 &|ctx| {313 let new_bindings = FutureNewBindings::new();314 let context_creator = context_creator!(315 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {316 Ok(context.clone().extend_unbound(317 new_bindings.clone().unwrap(),318 context.clone().dollar().clone().or_else(||this.clone()),319 None,320 super_obj321 )?)322 })323 );324 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();325 for (n, b) in pre_locals326 .iter()327 .chain(post_locals.iter())328 .map(|b| evaluate_binding(b, context_creator.clone()))329 {330 bindings.insert(n, b);331 }332 let bindings = new_bindings.fill(bindings);333 let ctx = ctx.extend_unbound(bindings, None, None, None)?;334 let key = evaluate(ctx.clone(), &key)?;335 let value = LazyBinding::Bindable(Rc::new(336 closure!(clone ctx, clone value, |this, _super_obj| {337 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))338 }),339 ));340341 Ok((key, value))342 },343 &compspecs,344 )?345 .unwrap()346 {347 match k {348 Val::Null => {}349 Val::Str(n) => {350 new_members.insert(351 n,352 ObjMember {353 add: false,354 visibility: Visibility::Normal,355 invoke: v,356 },357 );358 }359 v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,360 }361 }362363 future_this.fill(ObjValue::new(None, Rc::new(new_members)))364 }365 })366}367368#[inline(always)]369pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {370 use Expr::*;371 let locexpr = expr.clone();372 let LocExpr(expr, loc) = expr;373 Ok(match &**expr {374 Literal(LiteralType::This) => Val::Obj(375 context376 .this()377 .clone()378 .unwrap_or_else(|| panic!("this not found")),379 ),380 Literal(LiteralType::Dollar) => Val::Obj(381 context382 .dollar()383 .clone()384 .unwrap_or_else(|| panic!("dollar not found")),385 ),386 Literal(LiteralType::True) => Val::Bool(true),387 Literal(LiteralType::False) => Val::Bool(false),388 Literal(LiteralType::Null) => Val::Null,389 Parened(e) => evaluate(context, e)?,390 Str(v) => Val::Str(v.clone()),391 Num(v) => Val::Num(*v),392 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,393 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,394 Var(name) => push(locexpr, "var".to_owned(), || {395 Val::Lazy(context.binding(&name)).unwrap_if_lazy()396 })?,397 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {398 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;399 context400 .super_obj()401 .clone()402 .expect("no super found")403 .get_raw(&name, &context.this().clone().expect("no this found"))?404 .expect("value not found")405 }406 Index(value, index) => {407 match (408 evaluate(context.clone(), value)?.unwrap_if_lazy()?,409 evaluate(context, index)?,410 ) {411 (Val::Obj(v), Val::Str(s)) => {412 if let Some(v) = v.get(&s)? {413 v.unwrap_if_lazy()?414 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {415 Val::Intristic(n, s)416 } else {417 create_error(crate::Error::NoSuchField(s))?418 }419 }420 (Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(421 ValType::Obj,422 ValType::Str,423 n.value_type()?,424 ))?,425426 (Val::Arr(v), Val::Num(n)) => {427 if n.fract() > f64::EPSILON {428 create_error(crate::Error::FractionalIndex)?429 }430 v.get(n as usize)431 .unwrap_or_else(|| panic!("out of bounds"))432 .clone()433 .unwrap_if_lazy()?434 }435 (Val::Arr(_), Val::Str(n)) => {436 create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?437 }438 (Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(439 ValType::Arr,440 ValType::Num,441 n.value_type()?,442 ))?,443444 (Val::Str(s), Val::Num(n)) => {445 Val::Str(s.chars().skip(n as usize).take(1).collect())446 }447 (Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(448 ValType::Str,449 ValType::Num,450 n.value_type()?,451 ))?,452453 (v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,454 }455 }456 LocalExpr(bindings, returned) => {457 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();458 let future_context = Context::new_future();459460 let context_creator = context_creator!(461 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))462 );463464 for (k, v) in bindings465 .iter()466 .map(|b| evaluate_binding(b, context_creator.clone()))467 {468 new_bindings.insert(k, v);469 }470471 let context = context472 .extend_unbound(new_bindings, None, None, None)?473 .into_future(future_context);474 evaluate(context, &returned.clone())?475 }476 Arr(items) => {477 let mut out = Vec::with_capacity(items.len());478 for item in items {479 out.push(Val::Lazy(lazy_val!(480 closure!(clone context, clone item, || {481 evaluate(context.clone(), &item)482 })483 )));484 }485 Val::Arr(out)486 }487 ArrComp(expr, compspecs) => Val::Arr(488 // First compspec should be forspec, so no "None" possible here489 evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),490 ),491 Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),492 ObjExtend(s, t) => evaluate_add_op(493 &evaluate(context.clone(), s)?,494 &Val::Obj(evaluate_object(context, t.clone())?),495 )?,496 Apply(value, args, tailstrict) => {497 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;498 match value {499 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {500 // arr/string/function501 ("std", "length") => {502 assert_eq!(args.len(), 1);503 let expr = &args.get(0).unwrap().1;504 match evaluate(context, expr)? {505 Val::Str(n) => Val::Num(n.chars().count() as f64),506 Val::Arr(i) => Val::Num(i.len() as f64),507 Val::Obj(o) => Val::Num(508 o.fields_visibility()509 .into_iter()510 .filter(|(_k, v)| *v)511 .count() as f64,512 ),513 v => panic!("can't get length of {:?}", v),514 }515 }516 // any517 ("std", "type") => {518 assert_eq!(args.len(), 1);519 let expr = &args.get(0).unwrap().1;520 Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())521 }522 // length, idx=>any523 ("std", "makeArray") => {524 assert_eq!(args.len(), 2);525 if let (Val::Num(v), Val::Func(d)) = (526 evaluate(context.clone(), &args[0].1)?,527 evaluate(context, &args[1].1)?,528 ) {529 assert!(v >= 0.0);530 let mut out = Vec::with_capacity(v as usize);531 for i in 0..v as usize {532 let call_ctx =533 Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;534 out.push(d.evaluate(535 call_ctx,536 &ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),537 true,538 )?)539 }540 Val::Arr(out)541 } else {542 panic!("bad makeArray call");543 }544 }545 // string546 ("std", "codepoint") => {547 assert_eq!(args.len(), 1);548 if let Val::Str(s) = evaluate(context, &args[0].1)? {549 assert!(550 s.chars().count() == 1,551 "std.codepoint should receive single char string"552 );553 Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)554 } else {555 panic!("bad codepoint call");556 }557 }558 // object, includeHidden559 ("std", "objectFieldsEx") => {560 assert_eq!(args.len(), 2);561 if let (Val::Obj(body), Val::Bool(include_hidden)) = (562 evaluate(context.clone(), &args[0].1)?,563 evaluate(context, &args[1].1)?,564 ) {565 Val::Arr(566 body.fields_visibility()567 .into_iter()568 .filter(|(_k, v)| *v || include_hidden)569 .map(|(k, _v)| Val::Str(k))570 .collect(),571 )572 } else {573 panic!("bad objectFieldsEx call");574 }575 }576 // object, field, includeHidden577 ("std", "objectHasEx") => {578 assert_eq!(args.len(), 3);579 if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (580 evaluate(context.clone(), &args[0].1)?,581 evaluate(context.clone(), &args[1].1)?,582 evaluate(context, &args[2].1)?,583 ) {584 Val::Bool(585 body.fields_visibility()586 .into_iter()587 .filter(|(_k, v)| *v || include_hidden)588 .any(|(k, _v)| k == name),589 )590 } else {591 panic!("bad objectHasEx call");592 }593 }594 ("std", "primitiveEquals") => {595 assert_eq!(args.len(), 2);596 let (a, b) = (597 evaluate(context.clone(), &args[0].1)?,598 evaluate(context, &args[1].1)?,599 );600 Val::Bool(a == b)601 }602 ("std", "modulo") => {603 assert_eq!(args.len(), 2);604 if let (Val::Num(a), Val::Num(b)) = (605 evaluate(context.clone(), &args[0].1)?,606 evaluate(context, &args[1].1)?,607 ) {608 Val::Num(a % b)609 } else {610 panic!("bad modulo call");611 }612 }613 ("std", "floor") => {614 assert_eq!(args.len(), 1);615 if let Val::Num(a) = evaluate(context, &args[0].1)? {616 Val::Num(a.floor())617 } else {618 panic!("bad floor call");619 }620 }621 ("std", "trace") => {622 assert_eq!(args.len(), 2);623 if let (Val::Str(a), b) = (624 evaluate(context.clone(), &args[0].1)?,625 evaluate(context, &args[1].1)?,626 ) {627 // TODO: Line numbers as in original jsonnet628 println!("TRACE: {}", a);629 b630 } else {631 panic!("bad trace call");632 }633 }634 ("std", "pow") => {635 assert_eq!(args.len(), 2);636 if let (Val::Num(a), Val::Num(b)) = (637 evaluate(context.clone(), &args[0].1)?,638 evaluate(context, &args[1].1)?,639 ) {640 Val::Num(a.powf(b))641 } else {642 panic!("bad pow call");643 }644 }645 ("std", "extVar") => {646 assert_eq!(args.len(), 1);647 if let Val::Str(a) = evaluate(context, &args[0].1)? {648 with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(649 || {650 create_error::<()>(crate::Error::UndefinedExternalVariable(a))651 .err()652 .unwrap()653 },654 )?655 } else {656 panic!("bad extVar call");657 }658 }659 (ns, name) => panic!("Intristic not found: {}.{}", ns, name),660 },661 Val::Func(f) => {662 let body = #[inline(always)]663 || f.evaluate(context, args, *tailstrict);664 if *tailstrict {665 body()?666 } else {667 push(locexpr, "function call".to_owned(), body)?668 }669 }670 _ => panic!("{:?} is not a function", value),671 }672 }673 Function(params, body) => evaluate_method(context, params.clone(), body.clone()),674 AssertExpr(AssertStmt(value, msg), returned) => {675 let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {676 evaluate(context.clone(), &value)?677 .try_cast_bool("assertion condition should be boolean")678 })?;679 if assertion_result {680 push(681 returned.clone(),682 "assert 'return' branch".to_owned(),683 || evaluate(context, returned),684 )?685 } else if let Some(msg) = msg {686 panic!(687 "assertion failed ({:?}): {}",688 value,689 evaluate(context, msg)?.try_cast_str("assertion message should be string")?690 );691 } else {692 panic!("assertion failed ({:?}): no message", value);693 }694 }695 Error(e) => create_error(crate::Error::RuntimeError(696 evaluate(context, e)?.try_cast_str("error text should be string")?,697 ))?,698 IfElse {699 cond,700 cond_then,701 cond_else,702 } => {703 let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {704 evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")705 })?;706 if condition_result {707 push(708 cond_then.clone(),709 "if condition 'then' branch".to_owned(),710 || evaluate(context, cond_then),711 )?712 } else {713 match cond_else {714 Some(v) => evaluate(context, v)?,715 None => Val::Null,716 }717 }718 }719 Import(path) => {720 let mut lib_path = loc721 .clone()722 .expect("imports can't be used without loc_data")723 .0724 .clone();725 lib_path.pop();726 lib_path.push(path);727 with_state(|s| s.import_file(&lib_path))?728 }729 _ => panic!(730 "evaluation not implemented: {:?}",731 LocExpr(expr.clone(), loc.clone())732 ),733 })734}1use crate::{2 context_creator, create_error, future_wrapper, lazy_val, push, with_state, Context,3 ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4 ValType,5};6use closure::closure;7use jsonnet_parser::{8 el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,11};12use std::{13 collections::{BTreeMap, HashMap},14 rc::Rc,15};1617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {18 let b = b.clone();19 if let Some(params) = &b.params {20 let params = params.clone();21 (22 b.name.clone(),23 LazyBinding::Bindable(Rc::new(move |this, super_obj| {24 Ok(lazy_val!(25 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(26 context_creator.0(this.clone(), super_obj.clone())?,27 params.clone(),28 b.value.clone(),29 )))30 ))31 })),32 )33 } else {34 (35 b.name.clone(),36 LazyBinding::Bindable(Rc::new(move |this, super_obj| {37 Ok(lazy_val!(closure!(clone context_creator, clone b, ||38 push(b.value.clone(), "thunk".to_owned(), ||{39 evaluate(40 context_creator.0(this.clone(), super_obj.clone())?,41 &b.value42 )43 })44 )))45 })),46 )47 }48}4950pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {51 Val::Func(FuncDesc { ctx, params, body })52}5354pub fn evaluate_field_name(55 context: Context,56 field_name: &jsonnet_parser::FieldName,57) -> Result<Option<String>> {58 Ok(match field_name {59 jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),60 jsonnet_parser::FieldName::Dyn(expr) => {61 let value = evaluate(context, expr)?.unwrap_if_lazy()?;62 if matches!(value, Val::Null) {63 None64 } else {65 Some(value.try_cast_str("dynamic field name")?)66 }67 }68 })69}7071pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {72 Ok(match (op, b) {73 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,74 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),75 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),76 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),77 (op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),78 })79}8081pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {82 Ok(match (a, b) {83 (Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),8485 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),86 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),8788 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),89 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),90 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),91 _ => panic!("can't add: {:?} and {:?}", a, b),92 })93}9495pub fn evaluate_binary_op_special(96 context: Context,97 a: &LocExpr,98 op: BinaryOpType,99 b: &LocExpr,100) -> Result<Val> {101 Ok(102 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {103 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),104 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),105 (a, op, eb) => {106 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?107 }108 },109 )110}111112pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {113 Ok(match (a, op, b) {114 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,115116 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),117118 // Bool X Bool119 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),120 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),121122 // Str X Str123 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),124 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),125 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),126 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),127128 // Num X Num129 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),130 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {131 if *v2 <= f64::EPSILON {132 create_error(crate::Error::DivisionByZero)?133 }134 Val::Num(v1 / v2)135 }136137 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),138139 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),140 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),141 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),142 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),143144 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {145 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)146 }147 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {148 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)149 }150 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {151 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)152 }153 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {154 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)155 }156 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {157 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)158 }159160 _ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),161 })162}163164future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);165future_wrapper!(ObjValue, FutureObjValue);166167#[inline(always)]168pub fn evaluate_comp<T>(169 context: Context,170 value: &impl Fn(Context) -> Result<T>,171 specs: &[CompSpec],172) -> Result<Option<Vec<T>>> {173 Ok(match specs.get(0) {174 None => Some(vec![value(context)?]),175 Some(CompSpec::IfSpec(IfSpecData(cond))) => {176 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {177 evaluate_comp(context, value, &specs[1..])?178 } else {179 None180 }181 }182 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {183 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {184 Val::Arr(list) => {185 let mut out = Vec::new();186 for item in list {187 let item = item.clone().unwrap_if_lazy()?;188 out.push(evaluate_comp(189 context.with_var(var.clone(), item)?,190 value,191 &specs[1..],192 )?);193 }194 Some(out.into_iter().flatten().flatten().collect())195 }196 _ => panic!("for expression evaluated to non-iterable value"),197 }198 }199 })200}201202// TODO: Asserts203pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {204 Ok(match object {205 ObjBody::MemberList(members) => {206 let new_bindings = FutureNewBindings::new();207 let future_this = FutureObjValue::new();208 let context_creator = context_creator!(209 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {210 Ok(context.clone().extend_unbound(211 new_bindings.clone().unwrap(),212 context.clone().dollar().clone().or_else(||this.clone()),213 Some(this.unwrap()),214 super_obj215 )?)216 })217 );218 {219 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();220 for (n, b) in members221 .iter()222 .filter_map(|m| match m {223 Member::BindStmt(b) => Some(b.clone()),224 _ => None,225 })226 .map(|b| evaluate_binding(&b, context_creator.clone()))227 {228 bindings.insert(n, b);229 }230 new_bindings.fill(bindings);231 }232233 let mut new_members = BTreeMap::new();234 for member in members.into_iter() {235 match member {236 Member::Field(FieldMember {237 name,238 plus,239 params: None,240 visibility,241 value,242 }) => {243 let name = evaluate_field_name(context.clone(), &name)?;244 if name.is_none() {245 continue;246 }247 let name = name.unwrap();248 new_members.insert(249 name.clone(),250 ObjMember {251 add: plus,252 visibility: visibility.clone(),253 invoke: LazyBinding::Bindable(Rc::new(254 closure!(clone name, clone value, clone context_creator, |this, super_obj| {255 Ok(LazyVal::new_resolved(push(value.clone(), "object ".to_owned()+&name+" field", ||{256 let context = context_creator.0(this, super_obj)?;257 evaluate(258 context,259 &value,260 )?.unwrap_if_lazy()261 })?))262 }),263 )),264 },265 );266 }267 Member::Field(FieldMember {268 name,269 params: Some(params),270 value,271 ..272 }) => {273 let name = evaluate_field_name(context.clone(), &name)?;274 if name.is_none() {275 continue;276 }277 let name = name.unwrap();278 new_members.insert(279 name,280 ObjMember {281 add: false,282 visibility: Visibility::Hidden,283 invoke: LazyBinding::Bindable(Rc::new(284 closure!(clone value, clone context_creator, |this, super_obj| {285 // TODO: Assert286 Ok(LazyVal::new_resolved(evaluate_method(287 context_creator.0(this, super_obj)?,288 params.clone(),289 value.clone(),290 )))291 }),292 )),293 },294 );295 }296 Member::BindStmt(_) => {}297 Member::AssertStmt(_) => {}298 }299 }300 future_this.fill(ObjValue::new(None, Rc::new(new_members)))301 }302 ObjBody::ObjComp {303 pre_locals,304 key,305 value,306 post_locals,307 compspecs,308 } => {309 let future_this = FutureObjValue::new();310 let mut new_members = BTreeMap::new();311 for (k, v) in evaluate_comp(312 context.clone(),313 &|ctx| {314 let new_bindings = FutureNewBindings::new();315 let context_creator = context_creator!(316 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {317 Ok(context.clone().extend_unbound(318 new_bindings.clone().unwrap(),319 context.clone().dollar().clone().or_else(||this.clone()),320 None,321 super_obj322 )?)323 })324 );325 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();326 for (n, b) in pre_locals327 .iter()328 .chain(post_locals.iter())329 .map(|b| evaluate_binding(b, context_creator.clone()))330 {331 bindings.insert(n, b);332 }333 let bindings = new_bindings.fill(bindings);334 let ctx = ctx.extend_unbound(bindings, None, None, None)?;335 let key = evaluate(ctx.clone(), &key)?;336 let value = LazyBinding::Bindable(Rc::new(337 closure!(clone ctx, clone value, |this, _super_obj| {338 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))339 }),340 ));341342 Ok((key, value))343 },344 &compspecs,345 )?346 .unwrap()347 {348 match k {349 Val::Null => {}350 Val::Str(n) => {351 new_members.insert(352 n,353 ObjMember {354 add: false,355 visibility: Visibility::Normal,356 invoke: v,357 },358 );359 }360 v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,361 }362 }363364 future_this.fill(ObjValue::new(None, Rc::new(new_members)))365 }366 })367}368369#[inline(always)]370pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {371 use Expr::*;372 let locexpr = expr.clone();373 let LocExpr(expr, loc) = expr;374 Ok(match &**expr {375 Literal(LiteralType::This) => Val::Obj(376 context377 .this()378 .clone()379 .unwrap_or_else(|| panic!("this not found")),380 ),381 Literal(LiteralType::Dollar) => Val::Obj(382 context383 .dollar()384 .clone()385 .unwrap_or_else(|| panic!("dollar not found")),386 ),387 Literal(LiteralType::True) => Val::Bool(true),388 Literal(LiteralType::False) => Val::Bool(false),389 Literal(LiteralType::Null) => Val::Null,390 Parened(e) => evaluate(context, e)?,391 Str(v) => Val::Str(v.clone()),392 Num(v) => Val::Num(*v),393 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,394 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,395 Var(name) => push(locexpr, "var".to_owned(), || {396 Val::Lazy(context.binding(&name)).unwrap_if_lazy()397 })?,398 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {399 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;400 context401 .super_obj()402 .clone()403 .expect("no super found")404 .get_raw(&name, &context.this().clone().expect("no this found"))?405 .expect("value not found")406 }407 Index(value, index) => {408 match (409 evaluate(context.clone(), value)?.unwrap_if_lazy()?,410 evaluate(context, index)?,411 ) {412 (Val::Obj(v), Val::Str(s)) => {413 if let Some(v) = v.get(&s)? {414 v.unwrap_if_lazy()?415 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {416 Val::Intristic(n, s)417 } else {418 create_error(crate::Error::NoSuchField(s))?419 }420 }421 (Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(422 ValType::Obj,423 ValType::Str,424 n.value_type()?,425 ))?,426427 (Val::Arr(v), Val::Num(n)) => {428 if n.fract() > f64::EPSILON {429 create_error(crate::Error::FractionalIndex)?430 }431 v.get(n as usize)432 .unwrap_or_else(|| panic!("out of bounds"))433 .clone()434 .unwrap_if_lazy()?435 }436 (Val::Arr(_), Val::Str(n)) => {437 create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?438 }439 (Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(440 ValType::Arr,441 ValType::Num,442 n.value_type()?,443 ))?,444445 (Val::Str(s), Val::Num(n)) => {446 Val::Str(s.chars().skip(n as usize).take(1).collect())447 }448 (Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(449 ValType::Str,450 ValType::Num,451 n.value_type()?,452 ))?,453454 (v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,455 }456 }457 LocalExpr(bindings, returned) => {458 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();459 let future_context = Context::new_future();460461 let context_creator = context_creator!(462 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))463 );464465 for (k, v) in bindings466 .iter()467 .map(|b| evaluate_binding(b, context_creator.clone()))468 {469 new_bindings.insert(k, v);470 }471472 let context = context473 .extend_unbound(new_bindings, None, None, None)?474 .into_future(future_context);475 evaluate(context, &returned.clone())?476 }477 Arr(items) => {478 let mut out = Vec::with_capacity(items.len());479 for item in items {480 out.push(Val::Lazy(lazy_val!(481 closure!(clone context, clone item, || {482 evaluate(context.clone(), &item)483 })484 )));485 }486 Val::Arr(out)487 }488 ArrComp(expr, compspecs) => Val::Arr(489 // First compspec should be forspec, so no "None" possible here490 evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),491 ),492 Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),493 ObjExtend(s, t) => evaluate_add_op(494 &evaluate(context.clone(), s)?,495 &Val::Obj(evaluate_object(context, t.clone())?),496 )?,497 Apply(value, args, tailstrict) => {498 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;499 match value {500 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {501 // arr/string/function502 ("std", "length") => {503 assert_eq!(args.len(), 1);504 let expr = &args.get(0).unwrap().1;505 match evaluate(context, expr)? {506 Val::Str(n) => Val::Num(n.chars().count() as f64),507 Val::Arr(i) => Val::Num(i.len() as f64),508 Val::Obj(o) => Val::Num(509 o.fields_visibility()510 .into_iter()511 .filter(|(_k, v)| *v)512 .count() as f64,513 ),514 v => panic!("can't get length of {:?}", v),515 }516 }517 // any518 ("std", "type") => {519 assert_eq!(args.len(), 1);520 let expr = &args.get(0).unwrap().1;521 Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())522 }523 // length, idx=>any524 ("std", "makeArray") => {525 assert_eq!(args.len(), 2);526 if let (Val::Num(v), Val::Func(d)) = (527 evaluate(context.clone(), &args[0].1)?,528 evaluate(context, &args[1].1)?,529 ) {530 assert!(v >= 0.0);531 let mut out = Vec::with_capacity(v as usize);532 for i in 0..v as usize {533 let call_ctx =534 Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;535 out.push(d.evaluate(536 call_ctx,537 &ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),538 true,539 )?)540 }541 Val::Arr(out)542 } else {543 panic!("bad makeArray call");544 }545 }546 // string547 ("std", "codepoint") => {548 assert_eq!(args.len(), 1);549 if let Val::Str(s) = evaluate(context, &args[0].1)? {550 assert!(551 s.chars().count() == 1,552 "std.codepoint should receive single char string"553 );554 Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)555 } else {556 panic!("bad codepoint call");557 }558 }559 // object, includeHidden560 ("std", "objectFieldsEx") => {561 assert_eq!(args.len(), 2);562 if let (Val::Obj(body), Val::Bool(include_hidden)) = (563 evaluate(context.clone(), &args[0].1)?,564 evaluate(context, &args[1].1)?,565 ) {566 Val::Arr(567 body.fields_visibility()568 .into_iter()569 .filter(|(_k, v)| *v || include_hidden)570 .map(|(k, _v)| Val::Str(k))571 .collect(),572 )573 } else {574 panic!("bad objectFieldsEx call");575 }576 }577 // object, field, includeHidden578 ("std", "objectHasEx") => {579 assert_eq!(args.len(), 3);580 if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (581 evaluate(context.clone(), &args[0].1)?,582 evaluate(context.clone(), &args[1].1)?,583 evaluate(context, &args[2].1)?,584 ) {585 Val::Bool(586 body.fields_visibility()587 .into_iter()588 .filter(|(_k, v)| *v || include_hidden)589 .any(|(k, _v)| k == name),590 )591 } else {592 panic!("bad objectHasEx call");593 }594 }595 ("std", "primitiveEquals") => {596 assert_eq!(args.len(), 2);597 let (a, b) = (598 evaluate(context.clone(), &args[0].1)?,599 evaluate(context, &args[1].1)?,600 );601 Val::Bool(a == b)602 }603 ("std", "modulo") => {604 assert_eq!(args.len(), 2);605 if let (Val::Num(a), Val::Num(b)) = (606 evaluate(context.clone(), &args[0].1)?,607 evaluate(context, &args[1].1)?,608 ) {609 Val::Num(a % b)610 } else {611 panic!("bad modulo call");612 }613 }614 ("std", "floor") => {615 assert_eq!(args.len(), 1);616 if let Val::Num(a) = evaluate(context, &args[0].1)? {617 Val::Num(a.floor())618 } else {619 panic!("bad floor call");620 }621 }622 ("std", "trace") => {623 assert_eq!(args.len(), 2);624 if let (Val::Str(a), b) = (625 evaluate(context.clone(), &args[0].1)?,626 evaluate(context, &args[1].1)?,627 ) {628 // TODO: Line numbers as in original jsonnet629 println!("TRACE: {}", a);630 b631 } else {632 panic!("bad trace call");633 }634 }635 ("std", "pow") => {636 assert_eq!(args.len(), 2);637 if let (Val::Num(a), Val::Num(b)) = (638 evaluate(context.clone(), &args[0].1)?,639 evaluate(context, &args[1].1)?,640 ) {641 Val::Num(a.powf(b))642 } else {643 panic!("bad pow call");644 }645 }646 ("std", "extVar") => {647 assert_eq!(args.len(), 1);648 if let Val::Str(a) = evaluate(context, &args[0].1)? {649 with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(650 || {651 create_error::<()>(crate::Error::UndefinedExternalVariable(a))652 .err()653 .unwrap()654 },655 )?656 } else {657 panic!("bad extVar call");658 }659 }660 (ns, name) => panic!("Intristic not found: {}.{}", ns, name),661 },662 Val::Func(f) => {663 let body = #[inline(always)]664 || f.evaluate(context, args, *tailstrict);665 if *tailstrict {666 body()?667 } else {668 push(locexpr, "function call".to_owned(), body)?669 }670 }671 _ => panic!("{:?} is not a function", value),672 }673 }674 Function(params, body) => evaluate_method(context, params.clone(), body.clone()),675 AssertExpr(AssertStmt(value, msg), returned) => {676 let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {677 evaluate(context.clone(), &value)?678 .try_cast_bool("assertion condition should be boolean")679 })?;680 if assertion_result {681 push(682 returned.clone(),683 "assert 'return' branch".to_owned(),684 || evaluate(context, returned),685 )?686 } else if let Some(msg) = msg {687 panic!(688 "assertion failed ({:?}): {}",689 value,690 evaluate(context, msg)?.try_cast_str("assertion message should be string")?691 );692 } else {693 panic!("assertion failed ({:?}): no message", value);694 }695 }696 Error(e) => create_error(crate::Error::RuntimeError(697 evaluate(context, e)?.try_cast_str("error text should be string")?,698 ))?,699 IfElse {700 cond,701 cond_then,702 cond_else,703 } => {704 let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {705 evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")706 })?;707 if condition_result {708 push(709 cond_then.clone(),710 "if condition 'then' branch".to_owned(),711 || evaluate(context, cond_then),712 )?713 } else {714 match cond_else {715 Some(v) => evaluate(context, v)?,716 None => Val::Null,717 }718 }719 }720 Import(path) => {721 let mut lib_path = loc722 .clone()723 .expect("imports can't be used without loc_data")724 .0725 .clone();726 lib_path.pop();727 lib_path.push(path);728 with_state(|s| s.import_file(&lib_path))?729 }730 ImportStr(path) => {731 let mut file_path = loc732 .clone()733 .expect("imports can't be used without loc_data")734 .0735 .clone();736 file_path.pop();737 file_path.push(path);738 Val::Str(with_state(|s| s.import_file_str(&file_path))?)739 }740 })741}crates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -68,6 +68,7 @@
/// Contains file source codes and evaluated results for imports and pretty
/// printing stacktraces
files: RefCell<HashMap<PathBuf, FileData>>,
+ str_files: RefCell<HashMap<PathBuf, String>>,
globals: RefCell<HashMap<String, Val>>,
/// Values to use with std.extVar
@@ -177,6 +178,13 @@
}
self.evaluate_file_in_current_state(path)
}
+ pub(crate) fn import_file_str(&self, path: &PathBuf) -> Result<String> {
+ if !self.0.str_files.borrow().contains_key(path) {
+ let file_str = (self.0.settings.import_resolver)(path);
+ self.0.str_files.borrow_mut().insert(path.clone(), file_str);
+ }
+ Ok(self.0.str_files.borrow().get(path).cloned().unwrap())
+ }
pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {
let parsed = parse(