1use crate::{2 context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,3 ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jrsonnet_interner::IStr;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 jrsonnet_types::ValType;13use rustc_hash::FxHashMap;14use std::{collections::HashMap, rc::Rc};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, 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 b.name.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 evaluate_named(39 context_creator.0(this.clone(), super_obj.clone())?,40 &b.value,41 b.name.clone()42 )43 )))44 })),45 )46 }47}4849pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {50 Val::Func(Rc::new(FuncVal::Normal(FuncDesc {51 name,52 ctx,53 params,54 body,55 })))56}5758pub fn evaluate_field_name(59 context: Context,60 field_name: &jrsonnet_parser::FieldName,61) -> Result<Option<IStr>> {62 Ok(match field_name {63 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),64 jrsonnet_parser::FieldName::Dyn(expr) => {65 let value = evaluate(context, expr)?;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 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),78 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),79 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),80 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),81 })82}8384pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {85 Ok(match (a, b) {86 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),8788 89 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),90 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9192 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),93 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9495 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),96 (Val::Arr(a), Val::Arr(b)) => {97 let mut out = Vec::with_capacity(a.len() + b.len());98 out.extend(a.iter_lazy());99 out.extend(b.iter_lazy());100 Val::Arr(out.into())101 }102 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,103 _ => throw!(BinaryOperatorDoesNotOperateOnValues(104 BinaryOpType::Add,105 a.value_type(),106 b.value_type(),107 )),108 })109}110111pub fn evaluate_binary_op_special(112 context: Context,113 a: &LocExpr,114 op: BinaryOpType,115 b: &LocExpr,116) -> Result<Val> {117 Ok(match (evaluate(context.clone(), a)?, 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) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,121 })122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125 Ok(match (a, op, b) {126 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130 131 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134 135 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140 141 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,142 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143 if *v2 <= f64::EPSILON {144 throw!(DivisionByZero)145 }146 Val::new_checked_num(v1 / v2)?147 }148149 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,150151 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158 }159 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161 }162 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164 }165 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166 if *v2 < 0.0 {167 throw!(RuntimeError("shift by negative exponent".into()))168 }169 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)170 }171 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {172 if *v2 < 0.0 {173 throw!(RuntimeError("shift by negative exponent".into()))174 }175 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)176 }177178 _ => throw!(BinaryOperatorDoesNotOperateOnValues(179 op,180 a.value_type(),181 b.value_type(),182 )),183 })184}185186future_wrapper!(HashMap<IStr, LazyBinding>, FutureNewBindings);187future_wrapper!(ObjValue, FutureObjValue);188189pub fn evaluate_comp<T>(190 context: Context,191 value: &impl Fn(Context) -> Result<T>,192 specs: &[CompSpec],193) -> Result<Option<Vec<T>>> {194 Ok(match specs.get(0) {195 None => Some(vec![value(context)?]),196 Some(CompSpec::IfSpec(IfSpecData(cond))) => {197 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {198 evaluate_comp(context, value, &specs[1..])?199 } else {200 None201 }202 }203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {204 Val::Arr(list) => {205 let mut out = Vec::new();206 for item in list.iter() {207 out.push(evaluate_comp(208 context.clone().with_var(var.clone(), item?.clone()),209 value,210 &specs[1..],211 )?);212 }213 Some(out.into_iter().flatten().flatten().collect())214 }215 _ => throw!(InComprehensionCanOnlyIterateOverArray),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.clone().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<IStr, 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(evaluate(271 context_creator.0(this, super_obj)?,272 &value,273 )?))274 }),275 )),276 location: value.1.clone(),277 },278 );279 }280 Member::Field(FieldMember {281 name,282 params: Some(params),283 value,284 ..285 }) => {286 let name = evaluate_field_name(context.clone(), name)?;287 if name.is_none() {288 continue;289 }290 let name = name.unwrap();291 new_members.insert(292 name.clone(),293 ObjMember {294 add: false,295 visibility: Visibility::Hidden,296 invoke: LazyBinding::Bindable(Rc::new(297 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {298 299 Ok(LazyVal::new_resolved(evaluate_method(300 context_creator.0(this, super_obj)?,301 name.clone(),302 params.clone(),303 value.clone(),304 )))305 }),306 )),307 location: value.1.clone(),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.clone().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<IStr, 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.clone().extend(FxHashMap::default(), 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 location: obj.value.1.clone(),372 },373 );374 }375 v => throw!(FieldMustBeStringGot(v.value_type())),376 }377 }378379 future_this.fill(ObjValue::new(None, Rc::new(new_members)))380 }381 })382}383384pub fn evaluate_apply(385 context: Context,386 value: &LocExpr,387 args: &ArgsDesc,388 loc: &Option<ExprLocation>,389 tailstrict: bool,390) -> Result<Val> {391 let value = evaluate(context.clone(), value)?;392 Ok(match value {393 Val::Func(f) => {394 let body = || f.evaluate(context, loc, args, tailstrict);395 if tailstrict {396 body()?397 } else {398 push(loc, || format!("function <{}> call", f.name()), body)?399 }400 }401 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),402 })403}404405pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {406 use Expr::*;407 let LocExpr(expr, _loc) = lexpr;408 Ok(match &**expr {409 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),410 _ => evaluate(context, lexpr)?,411 })412}413414pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {415 use Expr::*;416 let LocExpr(expr, loc) = expr;417 Ok(match &**expr {418 Literal(LiteralType::This) => {419 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)420 }421 Literal(LiteralType::Dollar) => {422 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)423 }424 Literal(LiteralType::True) => Val::Bool(true),425 Literal(LiteralType::False) => Val::Bool(false),426 Literal(LiteralType::Null) => Val::Null,427 Parened(e) => evaluate(context, e)?,428 Str(v) => Val::Str(v.clone()),429 Num(v) => Val::new_checked_num(*v)?,430 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,431 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,432 Var(name) => push(433 loc,434 || format!("variable <{}>", name),435 || Ok(context.binding(name.clone())?.evaluate()?),436 )?,437 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {438 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;439 context440 .super_obj()441 .clone()442 .expect("no super found")443 .get_raw(name, Some(&context.this().clone().expect("no this found")))?444 .expect("value not found")445 }446 Index(value, index) => {447 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {448 (Val::Obj(v), Val::Str(s)) => {449 let sn = s.clone();450 push(451 loc,452 || format!("field <{}> access", sn),453 || {454 if let Some(v) = v.get(s.clone())? {455 Ok(v)456 } else if v.get("__intrinsic_namespace__".into())?.is_some() {457 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))458 } else {459 throw!(NoSuchField(s))460 }461 },462 )?463 }464 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(465 ValType::Obj,466 ValType::Str,467 n.value_type(),468 )),469470 (Val::Arr(v), Val::Num(n)) => {471 if n.fract() > f64::EPSILON {472 throw!(FractionalIndex)473 }474 v.get(n as usize)?475 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?476 .clone()477 }478 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),479 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(480 ValType::Arr,481 ValType::Num,482 n.value_type(),483 )),484485 (Val::Str(s), Val::Num(n)) => Val::Str(486 s.chars()487 .skip(n as usize)488 .take(1)489 .collect::<String>()490 .into(),491 ),492 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(493 ValType::Str,494 ValType::Num,495 n.value_type(),496 )),497498 (v, _) => throw!(CantIndexInto(v.value_type())),499 }500 }501 LocalExpr(bindings, returned) => {502 let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();503 let future_context = Context::new_future();504505 let context_creator = context_creator!(506 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))507 );508509 for (k, v) in bindings510 .iter()511 .map(|b| evaluate_binding(b, context_creator.clone()))512 {513 new_bindings.insert(k, v);514 }515516 let context = context517 .extend_unbound(new_bindings, None, None, None)?518 .into_future(future_context);519 evaluate(context, &returned.clone())?520 }521 Arr(items) => {522 let mut out = Vec::with_capacity(items.len());523 for item in items {524 out.push(LazyVal::new(Box::new(525 closure!(clone context, clone item, || {526 evaluate(context.clone(), &item)527 }),528 )));529 }530 Val::Arr(out.into())531 }532 ArrComp(expr, comp_specs) => Val::Arr(533 534 evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?535 .unwrap()536 .into(),537 ),538 Obj(body) => Val::Obj(evaluate_object(context, body)?),539 ObjExtend(s, t) => evaluate_add_op(540 &evaluate(context.clone(), s)?,541 &Val::Obj(evaluate_object(context, t)?),542 )?,543 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,544 Function(params, body) => {545 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())546 }547 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),548 AssertExpr(AssertStmt(value, msg), returned) => {549 let assertion_result = push(550 &value.1,551 || "assertion condition".to_owned(),552 || {553 evaluate(context.clone(), value)?554 .try_cast_bool("assertion condition should be of type `boolean`")555 },556 )?;557 if assertion_result {558 evaluate(context, returned)?559 } else {560 push(561 &value.1,562 || "assertion failure".to_owned(),563 || {564 if let Some(msg) = msg {565 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));566 } else {567 throw!(AssertionFailed(Val::Null.to_string()?));568 }569 },570 )?571 }572 }573 ErrorStmt(e) => push(574 loc,575 || "error statement".to_owned(),576 || {577 throw!(RuntimeError(578 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,579 ))580 },581 )?,582 IfElse {583 cond,584 cond_then,585 cond_else,586 } => {587 if push(588 loc,589 || "if condition".to_owned(),590 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),591 )? {592 evaluate(context, cond_then)?593 } else {594 match cond_else {595 Some(v) => evaluate(context, v)?,596 None => Val::Null,597 }598 }599 }600 Import(path) => {601 let mut tmp = loc602 .clone()603 .expect("imports cannot be used without loc_data")604 .0;605 let import_location = Rc::make_mut(&mut tmp);606 import_location.pop();607 push(608 loc,609 || format!("import {:?}", path),610 || with_state(|s| s.import_file(import_location, path)),611 )?612 }613 ImportStr(path) => {614 let mut tmp = loc615 .clone()616 .expect("imports cannot be used without loc_data")617 .0;618 let import_location = Rc::make_mut(&mut tmp);619 import_location.pop();620 Val::Str(with_state(|s| s.import_file_str(import_location, path))?)621 }622 Literal(LiteralType::Super) => throw!(StandaloneSuper),623 })624}