1use crate::{2 context_creator, create_error, create_error_result, escape_string_json, future_wrapper,3 lazy_val, manifest_json_ex, parse_args, push, with_state, Context, ContextCreator, Error,4 FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val, ValType,5};6use closure::closure;7use jrsonnet_parser::{8 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,11};12use std::{collections::HashMap, rc::Rc};1314pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {15 let b = b.clone();16 if let Some(params) = &b.params {17 let params = params.clone();18 (19 b.name.clone(),20 LazyBinding::Bindable(Rc::new(move |this, super_obj| {21 Ok(lazy_val!(22 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(23 context_creator.0(this.clone(), super_obj.clone())?,24 params.clone(),25 b.value.clone(),26 )))27 ))28 })),29 )30 } else {31 (32 b.name.clone(),33 LazyBinding::Bindable(Rc::new(move |this, super_obj| {34 Ok(lazy_val!(closure!(clone context_creator, clone b, ||35 push(&b.value.1, "thunk", ||{36 evaluate(37 context_creator.0(this.clone(), super_obj.clone())?,38 &b.value39 )40 })41 )))42 })),43 )44 }45}4647pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {48 Val::Func(FuncDesc { ctx, params, body })49}5051pub fn evaluate_field_name(52 context: Context,53 field_name: &jrsonnet_parser::FieldName,54) -> Result<Option<Rc<str>>> {55 Ok(match field_name {56 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),57 jrsonnet_parser::FieldName::Dyn(expr) => {58 let lazy = evaluate(context, expr)?;59 let value = lazy.unwrap_if_lazy()?;60 if matches!(value, Val::Null) {61 None62 } else {63 Some(value.try_cast_str("dynamic field name")?)64 }65 }66 })67}6869pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {70 Ok(match (op, b) {71 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,72 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),73 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),74 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),75 (op, o) => create_error_result(Error::UnaryOperatorDoesNotOperateOnType(76 op,77 o.value_type()?,78 ))?,79 })80}8182pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {83 Ok(match (a, b) {84 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8586 87 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),88 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),8990 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?).into()),91 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s).into()),9293 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),94 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),95 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,96 _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(97 BinaryOpType::Add,98 a.value_type()?,99 b.value_type()?,100 ))?,101 })102}103104pub fn evaluate_binary_op_special(105 context: Context,106 a: &LocExpr,107 op: BinaryOpType,108 b: &LocExpr,109) -> Result<Val> {110 Ok(111 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {112 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),113 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),114 (a, op, eb) => {115 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?116 }117 },118 )119}120121pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {122 Ok(match (a, op, b) {123 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,124125 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),126127 128 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),129 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),130131 132 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),133 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),134 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),135 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),136137 138 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,139 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {140 if *v2 <= f64::EPSILON {141 create_error_result(crate::Error::DivisionByZero)?142 }143 Val::new_checked_num(v1 / v2)?144 }145146 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,147148 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),149 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),150 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),151 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),152153 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {154 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)155 }156 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {157 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)158 }159 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {160 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)161 }162 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {163 if *v2 < 0.0 {164 create_error_result(Error::RuntimeError("shift by negative exponent".into()))?165 }166 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)167 }168 (Val::Num(v1), BinaryOpType::Rhs, 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 }174175 _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(176 op,177 a.value_type()?,178 b.value_type()?,179 ))?,180 })181}182183future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);184future_wrapper!(ObjValue, FutureObjValue);185186pub fn evaluate_comp<T>(187 context: Context,188 value: &impl Fn(Context) -> Result<T>,189 specs: &[CompSpec],190) -> Result<Option<Vec<T>>> {191 Ok(match specs.get(0) {192 None => Some(vec![value(context)?]),193 Some(CompSpec::IfSpec(IfSpecData(cond))) => {194 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {195 evaluate_comp(context, value, &specs[1..])?196 } else {197 None198 }199 }200 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {201 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {202 Val::Arr(list) => {203 let mut out = Vec::new();204 for item in list.iter() {205 let item = item.unwrap_if_lazy()?;206 out.push(evaluate_comp(207 context.with_var(var.clone(), item.clone())?,208 value,209 &specs[1..],210 )?);211 }212 Some(out.into_iter().flatten().flatten().collect())213 }214 _ => create_error_result(Error::InComprehensionCanOnlyIterateOverArray)?,215 }216 }217 })218}219220pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {221 let new_bindings = FutureNewBindings::new();222 let future_this = FutureObjValue::new();223 let context_creator = context_creator!(224 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {225 Ok(context.extend_unbound(226 new_bindings.clone().unwrap(),227 context.dollar().clone().or_else(||this.clone()),228 Some(this.unwrap()),229 super_obj230 )?)231 })232 );233 {234 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();235 for (n, b) in members236 .iter()237 .filter_map(|m| match m {238 Member::BindStmt(b) => Some(b.clone()),239 _ => None,240 })241 .map(|b| evaluate_binding(&b, context_creator.clone()))242 {243 bindings.insert(n, b);244 }245 new_bindings.fill(bindings);246 }247248 let mut new_members = HashMap::new();249 for member in members.iter() {250 match member {251 Member::Field(FieldMember {252 name,253 plus,254 params: None,255 visibility,256 value,257 }) => {258 let name = evaluate_field_name(context.clone(), &name)?;259 if name.is_none() {260 continue;261 }262 let name = name.unwrap();263 new_members.insert(264 name.clone(),265 ObjMember {266 add: *plus,267 visibility: *visibility,268 invoke: LazyBinding::Bindable(Rc::new(269 closure!(clone name, clone value, clone context_creator, |this, super_obj| {270 Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{271 let context = context_creator.0(this, super_obj)?;272 evaluate(273 context,274 &value,275 )276 })?))277 }),278 )),279 },280 );281 }282 Member::Field(FieldMember {283 name,284 params: Some(params),285 value,286 ..287 }) => {288 let name = evaluate_field_name(context.clone(), &name)?;289 if name.is_none() {290 continue;291 }292 let name = name.unwrap();293 new_members.insert(294 name,295 ObjMember {296 add: false,297 visibility: Visibility::Hidden,298 invoke: LazyBinding::Bindable(Rc::new(299 closure!(clone value, clone context_creator, clone params, |this, super_obj| {300 301 Ok(LazyVal::new_resolved(evaluate_method(302 context_creator.0(this, super_obj)?,303 params.clone(),304 value.clone(),305 )))306 }),307 )),308 },309 );310 }311 Member::BindStmt(_) => {}312 Member::AssertStmt(_) => {}313 }314 }315 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))316}317318pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {319 Ok(match object {320 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,321 ObjBody::ObjComp(obj) => {322 let future_this = FutureObjValue::new();323 let mut new_members = HashMap::new();324 for (k, v) in evaluate_comp(325 context.clone(),326 &|ctx| {327 let new_bindings = FutureNewBindings::new();328 let context_creator = context_creator!(329 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {330 Ok(context.extend_unbound(331 new_bindings.clone().unwrap(),332 context.dollar().clone().or_else(||this.clone()),333 None,334 super_obj335 )?)336 })337 );338 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();339 for (n, b) in obj340 .pre_locals341 .iter()342 .chain(obj.post_locals.iter())343 .map(|b| evaluate_binding(b, context_creator.clone()))344 {345 bindings.insert(n, b);346 }347 let bindings = new_bindings.fill(bindings);348 let ctx = ctx.extend_unbound(bindings, None, None, None)?;349 let key = evaluate(ctx.clone(), &obj.key)?;350 let value = LazyBinding::Bindable(Rc::new(351 closure!(clone ctx, clone obj.value, |this, _super_obj| {352 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))353 }),354 ));355356 Ok((key, value))357 },358 &obj.compspecs,359 )?360 .unwrap()361 {362 match k {363 Val::Null => {}364 Val::Str(n) => {365 new_members.insert(366 n,367 ObjMember {368 add: false,369 visibility: Visibility::Normal,370 invoke: v,371 },372 );373 }374 v => create_error_result(Error::FieldMustBeStringGot(v.value_type()?))?,375 }376 }377378 future_this.fill(ObjValue::new(None, Rc::new(new_members)))379 }380 })381}382383384385macro_rules! noinline {386 ($e:expr) => {387 (#[inline(never)]388 move || $e)()389 };390}391392pub fn evaluate_apply(393 context: Context,394 value: &LocExpr,395 args: &ArgsDesc,396 loc: &Option<ExprLocation>,397 tailstrict: bool,398) -> Result<Val> {399 let lazy = evaluate(context.clone(), value)?;400 let value = lazy.unwrap_if_lazy()?;401 Ok(match value {402 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {403 404 ("std", "length") => noinline!(parse_args!(context, "std.length", args, 1, [405 0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];406 ], {407 Ok(match x {408 Val::Str(n) => Val::Num(n.chars().count() as f64),409 Val::Arr(i) => Val::Num(i.len() as f64),410 Val::Obj(o) => Val::Num(411 o.fields_visibility()412 .into_iter()413 .filter(|(_k, v)| *v)414 .count() as f64,415 ),416 _ => unreachable!(),417 })418 }))?,419 420 ("std", "type") => parse_args!(context, "std.type", args, 1, [421 0, x, vec![];422 ], {423 Val::Str(x.value_type()?.name().into())424 }),425 426 ("std", "makeArray") => noinline!(parse_args!(context, "std.makeArray", args, 2, [427 0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];428 1, func: [Val::Func]!!Val::Func, vec![ValType::Func];429 ], {430 assert!(sz >= 0.0);431 let mut out = Vec::with_capacity(sz as usize);432 for i in 0..sz as usize {433 out.push(func.evaluate_values(434 Context::new(),435 &[Val::Num(i as f64)]436 )?)437 }438 Ok(Val::Arr(Rc::new(out)))439 }))?,440 441 ("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [442 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];443 ], {444 assert!(445 str.chars().count() == 1,446 "std.codepoint should receive single char string"447 );448 Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)449 }),450 451 ("std", "objectFieldsEx") => {452 noinline!(parse_args!(context, "std.objectFieldsEx",args, 2, [453 0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];454 1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];455 ], {456 let mut out = obj.fields_visibility()457 .into_iter()458 .filter(|(_k, v)| *v || inc_hidden)459 .map(|(k, _v)|k)460 .collect::<Vec<_>>();461 out.sort();462 Ok(Val::Arr(Rc::new(out.into_iter().map(Val::Str).collect())))463 }))?464 }465 466 ("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [467 0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];468 1, f: [Val::Str]!!Val::Str, vec![ValType::Str];469 2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];470 ], {471 Val::Bool(472 obj.fields_visibility()473 .into_iter()474 .filter(|(_k, v)| *v || inc_hidden)475 .any(|(k, _v)| *k == *f),476 )477 }),478 ("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [479 0, a, vec![];480 1, b, vec![];481 ], {482 Val::Bool(a == b)483 }),484 ("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [485 0, a: [Val::Num]!!Val::Num, vec![ValType::Num];486 1, b: [Val::Num]!!Val::Num, vec![ValType::Num];487 ], {488 Val::Num(a % b)489 }),490 ("std", "floor") => parse_args!(context, "std.floor", args, 1, [491 0, x: [Val::Num]!!Val::Num, vec![ValType::Num];492 ], {493 Val::Num(x.floor())494 }),495 ("std", "trace") => parse_args!(context, "std.trace", args, 2, [496 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];497 1, rest, vec![];498 ], {499 eprint!("TRACE: ");500 if let Some(loc) = loc {501 with_state(|s|{502 let locs = s.map_source_locations(&loc.0, &[loc.1]);503 eprint!("{}:{} ", loc.0.display(), locs[0].line);504 });505 }506 eprintln!("{}", str);507 rest508 }),509 ("std", "pow") => parse_args!(context, "std.modulo", args, 2, [510 0, x: [Val::Num]!!Val::Num, vec![ValType::Num];511 1, n: [Val::Num]!!Val::Num, vec![ValType::Num];512 ], {513 Val::Num(x.powf(n))514 }),515 ("std", "extVar") => parse_args!(context, "std.extVar", args, 2, [516 0, x: [Val::Str]!!Val::Str, vec![ValType::Str];517 ], {518 with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(519 || create_error(crate::Error::UndefinedExternalVariable(x)),520 )?521 }),522 ("std", "filter") => noinline!(parse_args!(context, "std.filter", args, 2, [523 0, func: [Val::Func]!!Val::Func, vec![ValType::Func];524 1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];525 ], {526 Ok(Val::Arr(Rc::new(527 arr.iter()528 .cloned()529 .filter(|e| {530 func531 .evaluate_values(context.clone(), &[e.clone()])532 .unwrap()533 .try_cast_bool("filter predicate")534 .unwrap()535 })536 .collect(),537 )))538 }))?,539 ("std", "char") => parse_args!(context, "std.char", args, 1, [540 0, n: [Val::Num]!!Val::Num, vec![ValType::Num];541 ], {542 let mut out = String::new();543 out.push(std::char::from_u32(n as u32).unwrap());544 Val::Str(out.into())545 }),546 ("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [547 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];548 ], {549 Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect()))550 }),551 ("std", "md5") => noinline!(parse_args!(context, "std.md5", args, 1, [552 0, str: [Val::Str]!!Val::Str, vec![ValType::Str];553 ], {554 Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))555 }))?,556 557 ("std", "join") => noinline!(parse_args!(context, "std.join", args, 2, [558 0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];559 1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];560 ], {561 Ok(match sep {562 Val::Arr(joiner_items) => {563 let mut out = Vec::new();564565 let mut first = true;566 for item in arr.iter().cloned() {567 if let Val::Arr(items) = item.unwrap_if_lazy()? {568 if !first {569 out.reserve(joiner_items.len());570 out.extend(joiner_items.iter().cloned());571 }572 first = false;573 out.reserve(items.len());574 out.extend(items.iter().cloned());575 } else {576 create_error_result(crate::Error::RuntimeError("in std.join all items should be arrays".into()))?;577 }578 }579580 Val::Arr(Rc::new(out))581 },582 Val::Str(sep) => {583 let mut out = String::new();584585 let mut first = true;586 for item in arr.iter().cloned() {587 if let Val::Str(item) = item.unwrap_if_lazy()? {588 if !first {589 out += &sep;590 }591 first = false;592 out += &item;593 } else {594 create_error_result(crate::Error::RuntimeError("in std.join all items should be strings".into()))?;595 }596 }597598 Val::Str(out.into())599 },600 _ => unreachable!()601 })602 }))?,603 604 ("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [605 0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];606 ], {607 Val::Str(escape_string_json(&str_).into())608 }),609 610 ("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [611 0, value, vec![];612 1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];613 ], {614 Val::Str(manifest_json_ex(&value, &indent)?.into())615 }),616 (ns, name) => {617 create_error_result(crate::Error::IntristicNotFound(ns.into(), name.into()))?618 }619 },620 Val::Func(f) => {621 let body = || f.evaluate(context, args, tailstrict);622 if tailstrict {623 body()?624 } else {625 push(loc, "function call", body)?626 }627 }628 v => create_error_result(crate::Error::OnlyFunctionsCanBeCalledGot(v.value_type()?))?,629 })630}631632pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {633 use Expr::*;634 let LocExpr(expr, loc) = expr;635 Ok(match &**expr {636 Literal(LiteralType::This) => Val::Obj(637 context638 .this()639 .clone()640 .ok_or_else(|| create_error(crate::Error::CantUseSelfOutsideOfObject))?,641 ),642 Literal(LiteralType::Dollar) => Val::Obj(643 context644 .dollar()645 .clone()646 .ok_or_else(|| create_error(crate::Error::NoTopLevelObjectFound))?,647 ),648 Literal(LiteralType::True) => Val::Bool(true),649 Literal(LiteralType::False) => Val::Bool(false),650 Literal(LiteralType::Null) => Val::Null,651 Parened(e) => evaluate(context, e)?,652 Str(v) => Val::Str(v.clone()),653 Num(v) => Val::new_checked_num(*v)?,654 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,655 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,656 Var(name) => push(loc, "var", || {657 Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?)658 })?,659 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {660 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;661 context662 .super_obj()663 .clone()664 .expect("no super found")665 .get_raw(&name, &context.this().clone().expect("no this found"))?666 .expect("value not found")667 }668 Index(value, index) => {669 match (670 evaluate(context.clone(), value)?.unwrap_if_lazy()?,671 evaluate(context, index)?,672 ) {673 (Val::Obj(v), Val::Str(s)) => {674 if let Some(v) = v.get(s.clone())? {675 v.unwrap_if_lazy()?676 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {677 Val::Intristic(n, s)678 } else {679 create_error_result(crate::Error::NoSuchField(s))?680 }681 }682 (Val::Obj(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(683 ValType::Obj,684 ValType::Str,685 n.value_type()?,686 ))?,687688 (Val::Arr(v), Val::Num(n)) => {689 if n.fract() > f64::EPSILON {690 create_error_result(crate::Error::FractionalIndex)?691 }692 v.get(n as usize)693 .ok_or_else(|| {694 create_error(crate::Error::ArrayBoundsError(n as usize, v.len()))695 })?696 .clone()697 .unwrap_if_lazy()?698 }699 (Val::Arr(_), Val::Str(n)) => {700 create_error_result(crate::Error::AttemptedIndexAnArrayWithString(n))?701 }702 (Val::Arr(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(703 ValType::Arr,704 ValType::Num,705 n.value_type()?,706 ))?,707708 (Val::Str(s), Val::Num(n)) => Val::Str(709 s.chars()710 .skip(n as usize)711 .take(1)712 .collect::<String>()713 .into(),714 ),715 (Val::Str(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(716 ValType::Str,717 ValType::Num,718 n.value_type()?,719 ))?,720721 (v, _) => create_error_result(crate::Error::CantIndexInto(v.value_type()?))?,722 }723 }724 LocalExpr(bindings, returned) => {725 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();726 let future_context = Context::new_future();727728 let context_creator = context_creator!(729 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))730 );731732 for (k, v) in bindings733 .iter()734 .map(|b| evaluate_binding(b, context_creator.clone()))735 {736 new_bindings.insert(k, v);737 }738739 let context = context740 .extend_unbound(new_bindings, None, None, None)?741 .into_future(future_context);742 evaluate(context, &returned.clone())?743 }744 Arr(items) => {745 let mut out = Vec::with_capacity(items.len());746 for item in items {747 out.push(Val::Lazy(lazy_val!(748 closure!(clone context, clone item, || {749 evaluate(context.clone(), &item)750 })751 )));752 }753 Val::Arr(Rc::new(out))754 }755 ArrComp(expr, compspecs) => Val::Arr(756 757 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),758 ),759 Obj(body) => Val::Obj(evaluate_object(context, body)?),760 ObjExtend(s, t) => evaluate_add_op(761 &evaluate(context.clone(), s)?,762 &Val::Obj(evaluate_object(context, t)?),763 )?,764 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,765 Function(params, body) => evaluate_method(context, params.clone(), body.clone()),766 AssertExpr(AssertStmt(value, msg), returned) => {767 let assertion_result = push(&value.1, "assertion condition", || {768 evaluate(context.clone(), &value)?769 .try_cast_bool("assertion condition should be boolean")770 })?;771 if assertion_result {772 evaluate(context, returned)?773 } else if let Some(msg) = msg {774 create_error_result(crate::Error::AssertionFailed(evaluate(context, msg)?))?775 } else {776 create_error_result(crate::Error::AssertionFailed(Val::Null))?777 }778 }779 Error(e) => create_error_result(crate::Error::RuntimeError(780 evaluate(context, e)?.try_cast_str("error text should be string")?,781 ))?,782 IfElse {783 cond,784 cond_then,785 cond_else,786 } => {787 if evaluate(context.clone(), &cond.0)?788 .try_cast_bool("if condition should be boolean")?789 {790 evaluate(context, cond_then)?791 } else {792 match cond_else {793 Some(v) => evaluate(context, v)?,794 None => Val::Null,795 }796 }797 }798 Import(path) => {799 let mut tmp = loc800 .clone()801 .expect("imports can't be used without loc_data")802 .0;803 let import_location = Rc::make_mut(&mut tmp);804 import_location.pop();805 with_state(|s| s.import_file(&import_location, path))?806 }807 ImportStr(path) => {808 let mut tmp = loc809 .clone()810 .expect("imports can't be used without loc_data")811 .0;812 let import_location = Rc::make_mut(&mut tmp);813 import_location.pop();814 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)815 }816 Literal(LiteralType::Super) => return create_error_result(crate::Error::StandaloneSuper),817 })818}