1use crate::{2 context_creator, create_error, create_error_result, equals, escape_string_json, future_wrapper,3 lazy_val, manifest_json_ex, parse_args, primitive_equals, push, with_state, Context,4 ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,5 ValType,6};7use closure::closure;8use jrsonnet_parser::{9 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,10 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,11 Visibility,12};13use std::{collections::HashMap, rc::Rc};1415pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {16 let b = b.clone();17 if let Some(params) = &b.params {18 let params = params.clone();19 (20 b.name.clone(),21 LazyBinding::Bindable(Rc::new(move |this, super_obj| {22 Ok(lazy_val!(23 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(24 context_creator.0(this.clone(), super_obj.clone())?,25 b.name.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 evaluate_named(38 context_creator.0(this.clone(), super_obj.clone())?,39 &b.value,40 b.name.clone()41 )42 )))43 })),44 )45 }46}4748pub fn evaluate_method(ctx: Context, name: Rc<str>, params: ParamsDesc, body: LocExpr) -> Val {49 Val::Func(Rc::new(FuncDesc {50 name,51 ctx,52 params,53 body,54 }))55}5657pub fn evaluate_field_name(58 context: Context,59 field_name: &jrsonnet_parser::FieldName,60) -> Result<Option<Rc<str>>> {61 Ok(match field_name {62 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),63 jrsonnet_parser::FieldName::Dyn(expr) => {64 let lazy = evaluate(context, expr)?;65 let value = lazy.unwrap_if_lazy()?;66 if matches!(value, Val::Null) {67 None68 } else {69 Some(value.try_cast_str("dynamic field name")?)70 }71 }72 })73}7475pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76 Ok(match (op, b) {77 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,78 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),79 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),80 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),81 (op, o) => create_error_result(Error::UnaryOperatorDoesNotOperateOnType(82 op,83 o.value_type()?,84 ))?,85 })86}8788pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {89 Ok(match (a, b) {90 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),9192 93 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),94 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9596 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?).into()),97 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s).into()),9899 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),100 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),101 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,102 _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(103 BinaryOpType::Add,104 a.value_type()?,105 b.value_type()?,106 ))?,107 })108}109110pub fn evaluate_binary_op_special(111 context: Context,112 a: &LocExpr,113 op: BinaryOpType,114 b: &LocExpr,115) -> Result<Val> {116 Ok(117 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {118 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),119 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),120 (a, op, eb) => {121 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?122 }123 },124 )125}126127pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {128 Ok(match (a, op, b) {129 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,130131 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),132133 134 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),135 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),136137 138 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),139 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),140 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),141 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),142143 144 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,145 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {146 if *v2 <= f64::EPSILON {147 create_error_result(crate::Error::DivisionByZero)?148 }149 Val::new_checked_num(v1 / v2)?150 }151152 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,153154 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),155 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),156 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),157 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),158159 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {160 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)161 }162 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {163 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)164 }165 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {166 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)167 }168 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {169 if *v2 < 0.0 {170 create_error_result(Error::RuntimeError("shift by negative exponent".into()))?171 }172 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)173 }174 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {175 if *v2 < 0.0 {176 create_error_result(Error::RuntimeError("shift by negative exponent".into()))?177 }178 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)179 }180181 _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(182 op,183 a.value_type()?,184 b.value_type()?,185 ))?,186 })187}188189future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);190future_wrapper!(ObjValue, FutureObjValue);191192pub fn evaluate_comp<T>(193 context: Context,194 value: &impl Fn(Context) -> Result<T>,195 specs: &[CompSpec],196) -> Result<Option<Vec<T>>> {197 Ok(match specs.get(0) {198 None => Some(vec![value(context)?]),199 Some(CompSpec::IfSpec(IfSpecData(cond))) => {200 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {201 evaluate_comp(context, value, &specs[1..])?202 } else {203 None204 }205 }206 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {207 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {208 Val::Arr(list) => {209 let mut out = Vec::new();210 for item in list.iter() {211 let item = item.unwrap_if_lazy()?;212 out.push(evaluate_comp(213 context.with_var(var.clone(), item.clone())?,214 value,215 &specs[1..],216 )?);217 }218 Some(out.into_iter().flatten().flatten().collect())219 }220 _ => create_error_result(Error::InComprehensionCanOnlyIterateOverArray)?,221 }222 }223 })224}225226pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {227 let new_bindings = FutureNewBindings::new();228 let future_this = FutureObjValue::new();229 let context_creator = context_creator!(230 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {231 Ok(context.extend_unbound(232 new_bindings.clone().unwrap(),233 context.dollar().clone().or_else(||this.clone()),234 Some(this.unwrap()),235 super_obj236 )?)237 })238 );239 {240 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();241 for (n, b) in members242 .iter()243 .filter_map(|m| match m {244 Member::BindStmt(b) => Some(b.clone()),245 _ => None,246 })247 .map(|b| evaluate_binding(&b, context_creator.clone()))248 {249 bindings.insert(n, b);250 }251 new_bindings.fill(bindings);252 }253254 let mut new_members = HashMap::new();255 for member in members.iter() {256 match member {257 Member::Field(FieldMember {258 name,259 plus,260 params: None,261 visibility,262 value,263 }) => {264 let name = evaluate_field_name(context.clone(), &name)?;265 if name.is_none() {266 continue;267 }268 let name = name.unwrap();269 new_members.insert(270 name.clone(),271 ObjMember {272 add: *plus,273 visibility: *visibility,274 invoke: LazyBinding::Bindable(Rc::new(275 closure!(clone name, clone value, clone context_creator, |this, super_obj| {276 Ok(LazyVal::new_resolved(evaluate(277 context_creator.0(this, super_obj)?,278 &value,279 )?))280 }),281 )),282 location: value.1.clone(),283 },284 );285 }286 Member::Field(FieldMember {287 name,288 params: Some(params),289 value,290 ..291 }) => {292 let name = evaluate_field_name(context.clone(), &name)?;293 if name.is_none() {294 continue;295 }296 let name = name.unwrap();297 new_members.insert(298 name.clone(),299 ObjMember {300 add: false,301 visibility: Visibility::Hidden,302 invoke: LazyBinding::Bindable(Rc::new(303 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {304 305 Ok(LazyVal::new_resolved(evaluate_method(306 context_creator.0(this, super_obj)?,307 name.clone(),308 params.clone(),309 value.clone(),310 )))311 }),312 )),313 location: value.1.clone(),314 },315 );316 }317 Member::BindStmt(_) => {}318 Member::AssertStmt(_) => {}319 }320 }321 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))322}323324pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {325 Ok(match object {326 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,327 ObjBody::ObjComp(obj) => {328 let future_this = FutureObjValue::new();329 let mut new_members = HashMap::new();330 for (k, v) in evaluate_comp(331 context.clone(),332 &|ctx| {333 let new_bindings = FutureNewBindings::new();334 let context_creator = context_creator!(335 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {336 Ok(context.extend_unbound(337 new_bindings.clone().unwrap(),338 context.dollar().clone().or_else(||this.clone()),339 None,340 super_obj341 )?)342 })343 );344 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();345 for (n, b) in obj346 .pre_locals347 .iter()348 .chain(obj.post_locals.iter())349 .map(|b| evaluate_binding(b, context_creator.clone()))350 {351 bindings.insert(n, b);352 }353 let bindings = new_bindings.fill(bindings);354 let ctx = ctx.extend_unbound(bindings, None, None, None)?;355 let key = evaluate(ctx.clone(), &obj.key)?;356 let value = LazyBinding::Bindable(Rc::new(357 closure!(clone ctx, clone obj.value, |this, _super_obj| {358 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))359 }),360 ));361362 Ok((key, value))363 },364 &obj.compspecs,365 )?366 .unwrap()367 {368 match k {369 Val::Null => {}370 Val::Str(n) => {371 new_members.insert(372 n,373 ObjMember {374 add: false,375 visibility: Visibility::Normal,376 invoke: v,377 location: obj.value.1.clone(),378 },379 );380 }381 v => create_error_result(Error::FieldMustBeStringGot(v.value_type()?))?,382 }383 }384385 future_this.fill(ObjValue::new(None, Rc::new(new_members)))386 }387 })388}389390391392macro_rules! noinline {393 ($e:expr) => {394 (#[inline(never)]395 move || $e)()396 };397}398399pub fn evaluate_apply(400 context: Context,401 value: &LocExpr,402 args: &ArgsDesc,403 loc: &Option<ExprLocation>,404 tailstrict: bool,405) -> Result<Val> {406 let lazy = evaluate(context.clone(), value)?;407 let value = lazy.unwrap_if_lazy()?;408 Ok(match value {409 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {410 411 ("std", "length") => noinline!(parse_args!(context, "std.length", args, 1, [412 0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];413 ], {414 Ok(match x {415 Val::Str(n) => Val::Num(n.chars().count() as f64),416 Val::Arr(i) => Val::Num(i.len() as f64),417 Val::Obj(o) => Val::Num(418 o.fields_visibility()419 .into_iter()420 .filter(|(_k, v)| *v)421 .count() as f64,422 ),423 _ => unreachable!(),424 })425 }))?,426 427 ("std", "type") => parse_args!(context, "std.type", args, 1, [428 0, x, vec![];429 ], {430 Val::Str(x.value_type()?.name().into())431 }),432 433 ("std", "makeArray") => noinline!(parse_args!(context, "std.makeArray", args, 2, [434 0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];435 1, func: [Val::Func]!!Val::Func, vec![ValType::Func];436 ], {437 if sz < 0.0 {438 create_error_result(crate::error::Error::RuntimeError(format!("makeArray requires size >= 0, got {}", sz).into()))?;439 }440 let mut out = Vec::with_capacity(sz as usize);441 for i in 0..sz as usize {442 out.push(func.evaluate_values(443 Context::new(),444 &[Val::Num(i as f64)]445 )?)446 }447 Ok(Val::Arr(Rc::new(out)))448 }))?,449 450 ("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [451 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];452 ], {453 assert!(454 str.chars().count() == 1,455 "std.codepoint should receive single char string"456 );457 Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)458 }),459 460 ("std", "objectFieldsEx") => {461 noinline!(parse_args!(context, "std.objectFieldsEx",args, 2, [462 0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];463 1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];464 ], {465 let mut out = obj.fields_visibility()466 .into_iter()467 .filter(|(_k, v)| *v || inc_hidden)468 .map(|(k, _v)|k)469 .collect::<Vec<_>>();470 out.sort();471 Ok(Val::Arr(Rc::new(out.into_iter().map(Val::Str).collect())))472 }))?473 }474 475 ("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [476 0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];477 1, f: [Val::Str]!!Val::Str, vec![ValType::Str];478 2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];479 ], {480 Val::Bool(481 obj.fields_visibility()482 .into_iter()483 .filter(|(_k, v)| *v || inc_hidden)484 .any(|(k, _v)| *k == *f),485 )486 }),487 ("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [488 0, a, vec![];489 1, b, vec![];490 ], {491 Val::Bool(primitive_equals(&a, &b)?)492 }),493 494 ("std", "equals") => parse_args!(context, "std.equals", args, 2, [495 0, a, vec![];496 1, b, vec![];497 ], {498 Val::Bool(equals(&a, &b)?)499 }),500 ("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [501 0, a: [Val::Num]!!Val::Num, vec![ValType::Num];502 1, b: [Val::Num]!!Val::Num, vec![ValType::Num];503 ], {504 Val::Num(a % b)505 }),506 ("std", "floor") => parse_args!(context, "std.floor", args, 1, [507 0, x: [Val::Num]!!Val::Num, vec![ValType::Num];508 ], {509 Val::Num(x.floor())510 }),511 ("std", "trace") => parse_args!(context, "std.trace", args, 2, [512 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];513 1, rest, vec![];514 ], {515 eprint!("TRACE: ");516 if let Some(loc) = loc {517 with_state(|s|{518 let locs = s.map_source_locations(&loc.0, &[loc.1]);519 eprint!("{}:{} ", loc.0.display(), locs[0].line);520 });521 }522 eprintln!("{}", str);523 rest524 }),525 ("std", "pow") => parse_args!(context, "std.modulo", args, 2, [526 0, x: [Val::Num]!!Val::Num, vec![ValType::Num];527 1, n: [Val::Num]!!Val::Num, vec![ValType::Num];528 ], {529 Val::Num(x.powf(n))530 }),531 ("std", "extVar") => parse_args!(context, "std.extVar", args, 2, [532 0, x: [Val::Str]!!Val::Str, vec![ValType::Str];533 ], {534 with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(535 || create_error(crate::Error::UndefinedExternalVariable(x)),536 )?537 }),538 ("std", "filter") => noinline!(parse_args!(context, "std.filter", args, 2, [539 0, func: [Val::Func]!!Val::Func, vec![ValType::Func];540 1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];541 ], {542 Ok(Val::Arr(Rc::new(543 arr.iter()544 .cloned()545 .filter(|e| {546 func547 .evaluate_values(context.clone(), &[e.clone()])548 .unwrap()549 .try_cast_bool("filter predicate")550 .unwrap()551 })552 .collect(),553 )))554 }))?,555 ("std", "char") => parse_args!(context, "std.char", args, 1, [556 0, n: [Val::Num]!!Val::Num, vec![ValType::Num];557 ], {558 let mut out = String::new();559 out.push(std::char::from_u32(n as u32).unwrap());560 Val::Str(out.into())561 }),562 ("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [563 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];564 ], {565 Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect()))566 }),567 ("std", "md5") => noinline!(parse_args!(context, "std.md5", args, 1, [568 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];569 ], {570 Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))571 }))?,572 573 ("std", "base64") => parse_args!(context, "std.base64", args, 1, [574 0, input: [Val::Str | Val::Arr], vec![ValType::Arr, ValType::Str];575 ], {576 Val::Str(match input {577 Val::Str(s) => {578 base64::encode(s.bytes().collect::<Vec<_>>()).into()579 },580 Val::Arr(a) => {581 base64::encode(a.iter().map(|v| {582 Ok(v.clone().try_cast_num("base64 array")? as u8)583 }).collect::<Result<Vec<_>>>()?).into()584 },585 _ => unreachable!()586 })587 }),588 589 ("std", "join") => noinline!(parse_args!(context, "std.join", args, 2, [590 0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];591 1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];592 ], {593 Ok(match sep {594 Val::Arr(joiner_items) => {595 let mut out = Vec::new();596597 let mut first = true;598 for item in arr.iter().cloned() {599 if let Val::Arr(items) = item.unwrap_if_lazy()? {600 if !first {601 out.reserve(joiner_items.len());602 out.extend(joiner_items.iter().cloned());603 }604 first = false;605 out.reserve(items.len());606 out.extend(items.iter().cloned());607 } else {608 create_error_result(crate::Error::RuntimeError("in std.join all items should be arrays".into()))?;609 }610 }611612 Val::Arr(Rc::new(out))613 },614 Val::Str(sep) => {615 let mut out = String::new();616617 let mut first = true;618 for item in arr.iter().cloned() {619 if let Val::Str(item) = item.unwrap_if_lazy()? {620 if !first {621 out += &sep;622 }623 first = false;624 out += &item;625 } else {626 create_error_result(crate::Error::RuntimeError("in std.join all items should be strings".into()))?;627 }628 }629630 Val::Str(out.into())631 },632 _ => unreachable!()633 })634 }))?,635 636 ("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [637 0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];638 ], {639 Val::Str(escape_string_json(&str_).into())640 }),641 642 ("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [643 0, value, vec![];644 1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];645 ], {646 Val::Str(manifest_json_ex(&value, &indent)?.into())647 }),648 (ns, name) => {649 create_error_result(crate::Error::IntristicNotFound(ns.into(), name.into()))?650 }651 },652 Val::Func(f) => {653 let body = || f.evaluate(context, args, tailstrict);654 if tailstrict {655 body()?656 } else {657 push(loc, || format!("function <{}> call", f.name), body)?658 }659 }660 v => create_error_result(crate::Error::OnlyFunctionsCanBeCalledGot(v.value_type()?))?,661 })662}663664pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {665 use Expr::*;666 let LocExpr(expr, _loc) = lexpr;667 Ok(match &**expr {668 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),669 _ => evaluate(context, lexpr)?,670 })671}672673pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {674 use Expr::*;675 let LocExpr(expr, loc) = expr;676 Ok(match &**expr {677 Literal(LiteralType::This) => Val::Obj(678 context679 .this()680 .clone()681 .ok_or_else(|| create_error(crate::Error::CantUseSelfOutsideOfObject))?,682 ),683 Literal(LiteralType::Dollar) => Val::Obj(684 context685 .dollar()686 .clone()687 .ok_or_else(|| create_error(crate::Error::NoTopLevelObjectFound))?,688 ),689 Literal(LiteralType::True) => Val::Bool(true),690 Literal(LiteralType::False) => Val::Bool(false),691 Literal(LiteralType::Null) => Val::Null,692 Parened(e) => evaluate(context, e)?,693 Str(v) => Val::Str(v.clone()),694 Num(v) => Val::new_checked_num(*v)?,695 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,696 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,697 Var(name) => push(698 loc,699 || format!("variable <{}>", name),700 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),701 )?,702 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {703 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;704 context705 .super_obj()706 .clone()707 .expect("no super found")708 .get_raw(&name, &context.this().clone().expect("no this found"))?709 .expect("value not found")710 }711 Index(value, index) => {712 match (713 evaluate(context.clone(), value)?.unwrap_if_lazy()?,714 evaluate(context, index)?,715 ) {716 (Val::Obj(v), Val::Str(s)) => {717 if let Some(v) = v.get(s.clone())? {718 v.unwrap_if_lazy()?719 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {720 Val::Intristic(n, s)721 } else {722 create_error_result(crate::Error::NoSuchField(s))?723 }724 }725 (Val::Obj(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(726 ValType::Obj,727 ValType::Str,728 n.value_type()?,729 ))?,730731 (Val::Arr(v), Val::Num(n)) => {732 if n.fract() > f64::EPSILON {733 create_error_result(crate::Error::FractionalIndex)?734 }735 v.get(n as usize)736 .ok_or_else(|| {737 create_error(crate::Error::ArrayBoundsError(n as usize, v.len()))738 })?739 .clone()740 .unwrap_if_lazy()?741 }742 (Val::Arr(_), Val::Str(n)) => {743 create_error_result(crate::Error::AttemptedIndexAnArrayWithString(n))?744 }745 (Val::Arr(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(746 ValType::Arr,747 ValType::Num,748 n.value_type()?,749 ))?,750751 (Val::Str(s), Val::Num(n)) => Val::Str(752 s.chars()753 .skip(n as usize)754 .take(1)755 .collect::<String>()756 .into(),757 ),758 (Val::Str(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(759 ValType::Str,760 ValType::Num,761 n.value_type()?,762 ))?,763764 (v, _) => create_error_result(crate::Error::CantIndexInto(v.value_type()?))?,765 }766 }767 LocalExpr(bindings, returned) => {768 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();769 let future_context = Context::new_future();770771 let context_creator = context_creator!(772 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))773 );774775 for (k, v) in bindings776 .iter()777 .map(|b| evaluate_binding(b, context_creator.clone()))778 {779 new_bindings.insert(k, v);780 }781782 let context = context783 .extend_unbound(new_bindings, None, None, None)?784 .into_future(future_context);785 evaluate(context, &returned.clone())?786 }787 Arr(items) => {788 let mut out = Vec::with_capacity(items.len());789 for item in items {790 out.push(Val::Lazy(lazy_val!(791 closure!(clone context, clone item, || {792 evaluate(context.clone(), &item)793 })794 )));795 }796 Val::Arr(Rc::new(out))797 }798 ArrComp(expr, compspecs) => Val::Arr(799 800 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),801 ),802 Obj(body) => Val::Obj(evaluate_object(context, body)?),803 ObjExtend(s, t) => evaluate_add_op(804 &evaluate(context.clone(), s)?,805 &Val::Obj(evaluate_object(context, t)?),806 )?,807 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,808 Function(params, body) => {809 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())810 }811 AssertExpr(AssertStmt(value, msg), returned) => {812 let assertion_result = push(813 &value.1,814 || "assertion condition".to_owned(),815 || {816 evaluate(context.clone(), &value)?817 .try_cast_bool("assertion condition should be boolean")818 },819 )?;820 if assertion_result {821 evaluate(context, returned)?822 } else if let Some(msg) = msg {823 create_error_result(crate::Error::AssertionFailed(evaluate(context, msg)?))?824 } else {825 create_error_result(crate::Error::AssertionFailed(Val::Null))?826 }827 }828 Error(e) => push(829 &loc,830 || "error statement".to_owned(),831 || {832 create_error_result(crate::Error::RuntimeError(833 evaluate(context, e)?.try_cast_str("error text should be string")?,834 ))?835 },836 )?,837 IfElse {838 cond,839 cond_then,840 cond_else,841 } => {842 if evaluate(context.clone(), &cond.0)?843 .try_cast_bool("if condition should be boolean")?844 {845 evaluate(context, cond_then)?846 } else {847 match cond_else {848 Some(v) => evaluate(context, v)?,849 None => Val::Null,850 }851 }852 }853 Import(path) => {854 let mut tmp = loc855 .clone()856 .expect("imports can't be used without loc_data")857 .0;858 let import_location = Rc::make_mut(&mut tmp);859 import_location.pop();860 with_state(|s| s.import_file(&import_location, path))?861 }862 ImportStr(path) => {863 let mut tmp = loc864 .clone()865 .expect("imports can't be used without loc_data")866 .0;867 let import_location = Rc::make_mut(&mut tmp);868 import_location.pop();869 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)870 }871 Literal(LiteralType::Super) => return create_error_result(crate::Error::StandaloneSuper),872 })873}