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.1, "thunk", ||{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 86 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o)),87 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n)),8889 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),90 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),9192 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),93 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),94 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),95 _ => panic!("can't add: {:?} and {:?}", a, b),96 })97}9899pub fn evaluate_binary_op_special(100 context: Context,101 a: &LocExpr,102 op: BinaryOpType,103 b: &LocExpr,104) -> Result<Val> {105 Ok(106 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {107 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),108 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),109 (a, op, eb) => {110 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?111 }112 },113 )114}115116pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {117 Ok(match (a, op, b) {118 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,119120 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),121122 123 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),124 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),125126 127 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),128 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),129 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),130 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),131132 133 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),134 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {135 if *v2 <= f64::EPSILON {136 create_error(crate::Error::DivisionByZero)?137 }138 Val::Num(v1 / v2)139 }140141 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),142143 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),144 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),145 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),146 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),147148 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {149 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)150 }151 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {152 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)153 }154 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {155 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)156 }157 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {158 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)159 }160 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {161 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)162 }163164 _ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),165 })166}167168future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);169future_wrapper!(ObjValue, FutureObjValue);170171pub fn evaluate_comp<T>(172 context: Context,173 value: &impl Fn(Context) -> Result<T>,174 specs: &[CompSpec],175) -> Result<Option<Vec<T>>> {176 Ok(match specs.get(0) {177 None => Some(vec![value(context)?]),178 Some(CompSpec::IfSpec(IfSpecData(cond))) => {179 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {180 evaluate_comp(context, value, &specs[1..])?181 } else {182 None183 }184 }185 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {186 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {187 Val::Arr(list) => {188 let mut out = Vec::new();189 for item in list {190 let item = item.clone().unwrap_if_lazy()?;191 out.push(evaluate_comp(192 context.with_var(var.clone(), item)?,193 value,194 &specs[1..],195 )?);196 }197 Some(out.into_iter().flatten().flatten().collect())198 }199 _ => panic!("for expression evaluated to non-iterable value"),200 }201 }202 })203}204205206pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {207 Ok(match object {208 ObjBody::MemberList(members) => {209 let new_bindings = FutureNewBindings::new();210 let future_this = FutureObjValue::new();211 let context_creator = context_creator!(212 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {213 Ok(context.extend_unbound(214 new_bindings.clone().unwrap(),215 context.dollar().clone().or_else(||this.clone()),216 Some(this.unwrap()),217 super_obj218 )?)219 })220 );221 {222 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();223 for (n, b) in members224 .iter()225 .filter_map(|m| match m {226 Member::BindStmt(b) => Some(b.clone()),227 _ => None,228 })229 .map(|b| evaluate_binding(&b, context_creator.clone()))230 {231 bindings.insert(n, b);232 }233 new_bindings.fill(bindings);234 }235236 let mut new_members = BTreeMap::new();237 for member in members.into_iter() {238 match member {239 Member::Field(FieldMember {240 name,241 plus,242 params: None,243 visibility,244 value,245 }) => {246 let name = evaluate_field_name(context.clone(), &name)?;247 if name.is_none() {248 continue;249 }250 let name = name.unwrap();251 new_members.insert(252 name.clone(),253 ObjMember {254 add: plus,255 visibility: visibility.clone(),256 invoke: LazyBinding::Bindable(Rc::new(257 closure!(clone name, clone value, clone context_creator, |this, super_obj| {258 Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{259 let context = context_creator.0(this, super_obj)?;260 evaluate(261 context,262 &value,263 )?.unwrap_if_lazy()264 })?))265 }),266 )),267 },268 );269 }270 Member::Field(FieldMember {271 name,272 params: Some(params),273 value,274 ..275 }) => {276 let name = evaluate_field_name(context.clone(), &name)?;277 if name.is_none() {278 continue;279 }280 let name = name.unwrap();281 new_members.insert(282 name,283 ObjMember {284 add: false,285 visibility: Visibility::Hidden,286 invoke: LazyBinding::Bindable(Rc::new(287 closure!(clone value, clone context_creator, |this, super_obj| {288 289 Ok(LazyVal::new_resolved(evaluate_method(290 context_creator.0(this, super_obj)?,291 params.clone(),292 value.clone(),293 )))294 }),295 )),296 },297 );298 }299 Member::BindStmt(_) => {}300 Member::AssertStmt(_) => {}301 }302 }303 future_this.fill(ObjValue::new(None, Rc::new(new_members)))304 }305 ObjBody::ObjComp {306 pre_locals,307 key,308 value,309 post_locals,310 compspecs,311 } => {312 let future_this = FutureObjValue::new();313 let mut new_members = BTreeMap::new();314 for (k, v) in evaluate_comp(315 context.clone(),316 &|ctx| {317 let new_bindings = FutureNewBindings::new();318 let context_creator = context_creator!(319 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {320 Ok(context.extend_unbound(321 new_bindings.clone().unwrap(),322 context.dollar().clone().or_else(||this.clone()),323 None,324 super_obj325 )?)326 })327 );328 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();329 for (n, b) in pre_locals330 .iter()331 .chain(post_locals.iter())332 .map(|b| evaluate_binding(b, context_creator.clone()))333 {334 bindings.insert(n, b);335 }336 let bindings = new_bindings.fill(bindings);337 let ctx = ctx.extend_unbound(bindings, None, None, None)?;338 let key = evaluate(ctx.clone(), &key)?;339 let value = LazyBinding::Bindable(Rc::new(340 closure!(clone ctx, clone value, |this, _super_obj| {341 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))342 }),343 ));344345 Ok((key, value))346 },347 &compspecs,348 )?349 .unwrap()350 {351 match k {352 Val::Null => {}353 Val::Str(n) => {354 new_members.insert(355 n,356 ObjMember {357 add: false,358 visibility: Visibility::Normal,359 invoke: v,360 },361 );362 }363 v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,364 }365 }366367 future_this.fill(ObjValue::new(None, Rc::new(new_members)))368 }369 })370}371372pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {373 use Expr::*;374 let LocExpr(expr, loc) = expr;375 Ok(match &**expr {376 Literal(LiteralType::This) => Val::Obj(377 context378 .this()379 .clone()380 .unwrap_or_else(|| panic!("this not found")),381 ),382 Literal(LiteralType::Dollar) => Val::Obj(383 context384 .dollar()385 .clone()386 .unwrap_or_else(|| panic!("dollar not found")),387 ),388 Literal(LiteralType::True) => Val::Bool(true),389 Literal(LiteralType::False) => Val::Bool(false),390 Literal(LiteralType::Null) => Val::Null,391 Parened(e) => evaluate(context, e)?,392 Str(v) => Val::Str(v.clone()),393 Num(v) => Val::Num(*v),394 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,395 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,396 Var(name) => push(loc, "var", || {397 Val::Lazy(context.binding(&name)?).unwrap_if_lazy()398 })?,399 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {400 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;401 context402 .super_obj()403 .clone()404 .expect("no super found")405 .get_raw(&name, &context.this().clone().expect("no this found"))?406 .expect("value not found")407 }408 Index(value, index) => {409 match (410 evaluate(context.clone(), value)?.unwrap_if_lazy()?,411 evaluate(context, index)?,412 ) {413 (Val::Obj(v), Val::Str(s)) => {414 if let Some(v) = v.get(&s)? {415 v.unwrap_if_lazy()?416 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {417 Val::Intristic(n, s)418 } else {419 create_error(crate::Error::NoSuchField(s))?420 }421 }422 (Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(423 ValType::Obj,424 ValType::Str,425 n.value_type()?,426 ))?,427428 (Val::Arr(v), Val::Num(n)) => {429 if n.fract() > f64::EPSILON {430 create_error(crate::Error::FractionalIndex)?431 }432 v.get(n as usize)433 .unwrap_or_else(|| panic!("out of bounds"))434 .clone()435 .unwrap_if_lazy()?436 }437 (Val::Arr(_), Val::Str(n)) => {438 create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?439 }440 (Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(441 ValType::Arr,442 ValType::Num,443 n.value_type()?,444 ))?,445446 (Val::Str(s), Val::Num(n)) => {447 Val::Str(s.chars().skip(n as usize).take(1).collect())448 }449 (Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(450 ValType::Str,451 ValType::Num,452 n.value_type()?,453 ))?,454455 (v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,456 }457 }458 LocalExpr(bindings, returned) => {459 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();460 let future_context = Context::new_future();461462 let context_creator = context_creator!(463 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))464 );465466 for (k, v) in bindings467 .iter()468 .map(|b| evaluate_binding(b, context_creator.clone()))469 {470 new_bindings.insert(k, v);471 }472473 let context = context474 .extend_unbound(new_bindings, None, None, None)?475 .into_future(future_context);476 evaluate(context, &returned.clone())?477 }478 Arr(items) => {479 let mut out = Vec::with_capacity(items.len());480 for item in items {481 out.push(Val::Lazy(lazy_val!(482 closure!(clone context, clone item, || {483 evaluate(context.clone(), &item)484 })485 )));486 }487 Val::Arr(out)488 }489 ArrComp(expr, compspecs) => Val::Arr(490 491 evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),492 ),493 Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),494 ObjExtend(s, t) => evaluate_add_op(495 &evaluate(context.clone(), s)?,496 &Val::Obj(evaluate_object(context, t.clone())?),497 )?,498 Apply(value, args, tailstrict) => {499 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;500 match value {501 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {502 503 ("std", "length") => {504 assert_eq!(args.len(), 1);505 let expr = &args.get(0).unwrap().1;506 match evaluate(context, expr)? {507 Val::Str(n) => Val::Num(n.chars().count() as f64),508 Val::Arr(i) => Val::Num(i.len() as f64),509 Val::Obj(o) => Val::Num(510 o.fields_visibility()511 .into_iter()512 .filter(|(_k, v)| *v)513 .count() as f64,514 ),515 v => panic!("can't get length of {:?}", v),516 }517 }518 519 ("std", "type") => {520 assert_eq!(args.len(), 1);521 let expr = &args.get(0).unwrap().1;522 Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())523 }524 525 ("std", "makeArray") => {526 assert_eq!(args.len(), 2);527 if let (Val::Num(v), Val::Func(d)) = (528 evaluate(context.clone(), &args[0].1)?,529 evaluate(context, &args[1].1)?,530 ) {531 assert!(v >= 0.0);532 let mut out = Vec::with_capacity(v as usize);533 for i in 0..v as usize {534 let call_ctx =535 Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;536 out.push(d.evaluate(537 call_ctx,538 &ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),539 true,540 )?)541 }542 Val::Arr(out)543 } else {544 panic!("bad makeArray call");545 }546 }547 548 ("std", "codepoint") => {549 assert_eq!(args.len(), 1);550 if let Val::Str(s) = evaluate(context, &args[0].1)? {551 assert!(552 s.chars().count() == 1,553 "std.codepoint should receive single char string"554 );555 Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)556 } else {557 panic!("bad codepoint call");558 }559 }560 561 ("std", "objectFieldsEx") => {562 assert_eq!(args.len(), 2);563 if let (Val::Obj(body), Val::Bool(include_hidden)) = (564 evaluate(context.clone(), &args[0].1)?,565 evaluate(context, &args[1].1)?,566 ) {567 Val::Arr(568 body.fields_visibility()569 .into_iter()570 .filter(|(_k, v)| *v || include_hidden)571 .map(|(k, _v)| Val::Str(k))572 .collect(),573 )574 } else {575 panic!("bad objectFieldsEx call");576 }577 }578 579 ("std", "objectHasEx") => {580 assert_eq!(args.len(), 3);581 if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (582 evaluate(context.clone(), &args[0].1)?,583 evaluate(context.clone(), &args[1].1)?,584 evaluate(context, &args[2].1)?,585 ) {586 Val::Bool(587 body.fields_visibility()588 .into_iter()589 .filter(|(_k, v)| *v || include_hidden)590 .any(|(k, _v)| k == name),591 )592 } else {593 panic!("bad objectHasEx call");594 }595 }596 ("std", "primitiveEquals") => {597 assert_eq!(args.len(), 2);598 let (a, b) = (599 evaluate(context.clone(), &args[0].1)?,600 evaluate(context, &args[1].1)?,601 );602 Val::Bool(a == b)603 }604 ("std", "modulo") => {605 assert_eq!(args.len(), 2);606 if let (Val::Num(a), Val::Num(b)) = (607 evaluate(context.clone(), &args[0].1)?,608 evaluate(context, &args[1].1)?,609 ) {610 Val::Num(a % b)611 } else {612 panic!("bad modulo call");613 }614 }615 ("std", "floor") => {616 assert_eq!(args.len(), 1);617 if let Val::Num(a) = evaluate(context, &args[0].1)? {618 Val::Num(a.floor())619 } else {620 panic!("bad floor call");621 }622 }623 ("std", "trace") => {624 assert_eq!(args.len(), 2);625 if let (Val::Str(a), b) = (626 evaluate(context.clone(), &args[0].1)?,627 evaluate(context, &args[1].1)?,628 ) {629 630 println!("TRACE: {}", a);631 b632 } else {633 panic!("bad trace call");634 }635 }636 ("std", "pow") => {637 assert_eq!(args.len(), 2);638 if let (Val::Num(a), Val::Num(b)) = (639 evaluate(context.clone(), &args[0].1)?,640 evaluate(context, &args[1].1)?,641 ) {642 Val::Num(a.powf(b))643 } else {644 panic!("bad pow call");645 }646 }647 ("std", "extVar") => {648 assert_eq!(args.len(), 1);649 if let Val::Str(a) = evaluate(context, &args[0].1)? {650 with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(651 || {652 create_error::<()>(crate::Error::UndefinedExternalVariable(a))653 .err()654 .unwrap()655 },656 )?657 } else {658 panic!("bad extVar call");659 }660 }661 ("std", "filter") => {662 assert_eq!(args.len(), 2);663 if let (Val::Func(predicate), Val::Arr(arr)) = (664 evaluate(context.clone(), &args[0].1)?,665 evaluate(context.clone(), &args[1].1)?,666 ) {667 Val::Arr(668 arr.into_iter()669 .filter(|e| {670 predicate671 .evaluate_values(context.clone(), &[e.clone()])672 .unwrap()673 .try_cast_bool("filter predicate")674 .unwrap()675 })676 .collect(),677 )678 } else {679 panic!("bad filter call");680 }681 }682 683 ("std", "join") => {684 assert_eq!(args.len(), 2);685 let joiner = evaluate(context.clone(), &args[0].1)?.unwrap_if_lazy()?;686 let items = evaluate(context, &args[1].1)?.unwrap_if_lazy()?;687 match (joiner, items) {688 (Val::Arr(joiner_items), Val::Arr(items)) => {689 690 let mut out = Vec::new();691692 let mut first = true;693 for item in items {694 if let Val::Arr(items) = item.unwrap_if_lazy()? {695 if !first {696 out.extend(joiner_items.iter().cloned());697 }698 first = false;699 out.extend(items);700 } else {701 panic!("all array items should be arrays")702 }703 }704705 Val::Arr(out)706 }707 (Val::Str(joiner), Val::Arr(items)) => {708 let mut out = String::new();709710 let mut first = true;711 for item in items {712 if let Val::Str(item) = item.unwrap_if_lazy()? {713 if !first {714 out += &joiner;715 }716 first = false;717 out += &item;718 } else {719 panic!("all array items should be strings")720 }721 }722723 Val::Str(out)724 }725 (joiner, items) => panic!("bad join call: {:?} {:?}", joiner, items),726 }727 }728 (ns, name) => panic!("Intristic not found: {}.{}", ns, name),729 },730 Val::Func(f) => {731 let body = || f.evaluate(context, args, *tailstrict);732 if *tailstrict {733 body()?734 } else {735 push(loc, "function call", body)?736 }737 }738 _ => panic!("{:?} is not a function", value),739 }740 }741 Function(params, body) => evaluate_method(context, params.clone(), body.clone()),742 AssertExpr(AssertStmt(value, msg), returned) => {743 let assertion_result = push(&value.1, "assertion condition", || {744 evaluate(context.clone(), &value)?745 .try_cast_bool("assertion condition should be boolean")746 })?;747 if assertion_result {748 evaluate(context, returned)?749 } else if let Some(msg) = msg {750 panic!(751 "assertion failed ({:?}): {}",752 value,753 evaluate(context, msg)?.try_cast_str("assertion message should be string")?754 );755 } else {756 panic!("assertion failed ({:?}): no message", value);757 }758 }759 Error(e) => create_error(crate::Error::RuntimeError(760 evaluate(context, e)?.try_cast_str("error text should be string")?,761 ))?,762 IfElse {763 cond,764 cond_then,765 cond_else,766 } => {767 if evaluate(context.clone(), &cond.0)?768 .try_cast_bool("if condition should be boolean")?769 {770 evaluate(context, cond_then)?771 } else {772 match cond_else {773 Some(v) => evaluate(context, v)?,774 None => Val::Null,775 }776 }777 }778 Import(path) => {779 let mut import_location = loc780 .clone()781 .expect("imports can't be used without loc_data")782 .0783 .clone();784 import_location.pop();785 with_state(|s| s.import_file(&import_location, path))?786 }787 ImportStr(path) => {788 let mut import_location = loc789 .clone()790 .expect("imports can't be used without loc_data")791 .0792 .clone();793 import_location.pop();794 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)795 }796 Literal(LiteralType::Super) => return create_error(crate::error::Error::StandaloneSuper),797 })798}