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 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 b.name.clone(),25 params.clone(),26 b.value.clone(),27 )))28 ))29 })),30 )31 } else {32 (33 b.name.clone(),34 LazyBinding::Bindable(Rc::new(move |this, super_obj| {35 Ok(lazy_val!(closure!(clone context_creator, clone b, ||36 evaluate_named(37 context_creator.0(this.clone(), super_obj.clone())?,38 &b.value,39 b.name.clone()40 )41 )))42 })),43 )44 }45}4647pub fn evaluate_method(ctx: Context, name: Rc<str>, params: ParamsDesc, body: LocExpr) -> Val {48 Val::Func(FuncVal::Normal(Rc::new(FuncDesc {49 name,50 ctx,51 params,52 body,53 })))54}5556pub fn evaluate_field_name(57 context: Context,58 field_name: &jrsonnet_parser::FieldName,59) -> Result<Option<Rc<str>>> {60 Ok(match field_name {61 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),62 jrsonnet_parser::FieldName::Dyn(expr) => {63 let lazy = evaluate(context, expr)?;64 let value = lazy.unwrap_if_lazy()?;65 if matches!(value, Val::Null) {66 None67 } else {68 Some(value.try_cast_str("dynamic field name")?)69 }70 }71 })72}7374pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {75 Ok(match (op, b) {76 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,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(crate) 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)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),97 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,98 _ => throw!(BinaryOperatorDoesNotOperateOnValues(99 BinaryOpType::Add,100 a.value_type()?,101 b.value_type()?,102 )),103 })104}105106pub fn evaluate_binary_op_special(107 context: Context,108 a: &LocExpr,109 op: BinaryOpType,110 b: &LocExpr,111) -> Result<Val> {112 Ok(113 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {114 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),115 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),116 (a, op, eb) => {117 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?118 }119 },120 )121}122123pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {124 Ok(match (a, op, b) {125 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,126127 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),128129 130 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),131 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),132133 134 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),135 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),136 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),137 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),138139 140 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,141 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {142 if *v2 <= f64::EPSILON {143 throw!(DivisionByZero)144 }145 Val::new_checked_num(v1 / v2)?146 }147148 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,149150 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),151 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),152 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),153 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),154155 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {156 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)157 }158 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {159 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)160 }161 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {162 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)163 }164 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {165 if *v2 < 0.0 {166 throw!(RuntimeError("shift by negative exponent".into()))167 }168 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)169 }170 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {171 if *v2 < 0.0 {172 throw!(RuntimeError("shift by negative exponent".into()))173 }174 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)175 }176177 _ => throw!(BinaryOperatorDoesNotOperateOnValues(178 op,179 a.value_type()?,180 b.value_type()?,181 )),182 })183}184185future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);186future_wrapper!(ObjValue, FutureObjValue);187188pub fn evaluate_comp<T>(189 context: Context,190 value: &impl Fn(Context) -> Result<T>,191 specs: &[CompSpec],192) -> Result<Option<Vec<T>>> {193 Ok(match specs.get(0) {194 None => Some(vec![value(context)?]),195 Some(CompSpec::IfSpec(IfSpecData(cond))) => {196 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {197 evaluate_comp(context, value, &specs[1..])?198 } else {199 None200 }201 }202 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {203 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {204 Val::Arr(list) => {205 let mut out = Vec::new();206 for item in list.iter() {207 let item = item.unwrap_if_lazy()?;208 out.push(evaluate_comp(209 context.clone().with_var(var.clone(), item.clone()),210 value,211 &specs[1..],212 )?);213 }214 Some(out.into_iter().flatten().flatten().collect())215 }216 _ => throw!(InComprehensionCanOnlyIterateOverArray),217 }218 }219 })220}221222pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {223 let new_bindings = FutureNewBindings::new();224 let future_this = FutureObjValue::new();225 let context_creator = context_creator!(226 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {227 Ok(context.clone().extend_unbound(228 new_bindings.clone().unwrap(),229 context.dollar().clone().or_else(||this.clone()),230 Some(this.unwrap()),231 super_obj232 )?)233 })234 );235 {236 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();237 for (n, b) in members238 .iter()239 .filter_map(|m| match m {240 Member::BindStmt(b) => Some(b.clone()),241 _ => None,242 })243 .map(|b| evaluate_binding(&b, context_creator.clone()))244 {245 bindings.insert(n, b);246 }247 new_bindings.fill(bindings);248 }249250 let mut new_members = HashMap::new();251 for member in members.iter() {252 match member {253 Member::Field(FieldMember {254 name,255 plus,256 params: None,257 visibility,258 value,259 }) => {260 let name = evaluate_field_name(context.clone(), &name)?;261 if name.is_none() {262 continue;263 }264 let name = name.unwrap();265 new_members.insert(266 name.clone(),267 ObjMember {268 add: *plus,269 visibility: *visibility,270 invoke: LazyBinding::Bindable(Rc::new(271 closure!(clone name, clone value, clone context_creator, |this, super_obj| {272 Ok(LazyVal::new_resolved(evaluate(273 context_creator.0(this, super_obj)?,274 &value,275 )?))276 }),277 )),278 location: value.1.clone(),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.clone(),295 ObjMember {296 add: false,297 visibility: Visibility::Hidden,298 invoke: LazyBinding::Bindable(Rc::new(299 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {300 301 Ok(LazyVal::new_resolved(evaluate_method(302 context_creator.0(this, super_obj)?,303 name.clone(),304 params.clone(),305 value.clone(),306 )))307 }),308 )),309 location: value.1.clone(),310 },311 );312 }313 Member::BindStmt(_) => {}314 Member::AssertStmt(_) => {}315 }316 }317 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))318}319320pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {321 Ok(match object {322 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,323 ObjBody::ObjComp(obj) => {324 let future_this = FutureObjValue::new();325 let mut new_members = HashMap::new();326 for (k, v) in evaluate_comp(327 context.clone(),328 &|ctx| {329 let new_bindings = FutureNewBindings::new();330 let context_creator = context_creator!(331 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {332 Ok(context.clone().extend_unbound(333 new_bindings.clone().unwrap(),334 context.dollar().clone().or_else(||this.clone()),335 None,336 super_obj337 )?)338 })339 );340 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();341 for (n, b) in obj342 .pre_locals343 .iter()344 .chain(obj.post_locals.iter())345 .map(|b| evaluate_binding(b, context_creator.clone()))346 {347 bindings.insert(n, b);348 }349 let bindings = new_bindings.fill(bindings);350 let ctx = ctx.extend_unbound(bindings, None, None, None)?;351 let key = evaluate(ctx.clone(), &obj.key)?;352 let value = LazyBinding::Bindable(Rc::new(353 closure!(clone ctx, clone obj.value, |this, _super_obj| {354 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(HashMap::new(), None, this, None), &value)?))355 }),356 ));357358 Ok((key, value))359 },360 &obj.compspecs,361 )?362 .unwrap()363 {364 match k {365 Val::Null => {}366 Val::Str(n) => {367 new_members.insert(368 n,369 ObjMember {370 add: false,371 visibility: Visibility::Normal,372 invoke: v,373 location: obj.value.1.clone(),374 },375 );376 }377 v => throw!(FieldMustBeStringGot(v.value_type()?)),378 }379 }380381 future_this.fill(ObjValue::new(None, Rc::new(new_members)))382 }383 })384}385386pub fn evaluate_apply(387 context: Context,388 value: &LocExpr,389 args: &ArgsDesc,390 loc: &Option<ExprLocation>,391 tailstrict: bool,392) -> Result<Val> {393 let lazy = evaluate(context.clone(), value)?;394 let value = lazy.unwrap_if_lazy()?;395 Ok(match value {396 Val::Func(f) => {397 let body = || f.evaluate(context, loc, args, tailstrict);398 if tailstrict {399 body()?400 } else {401 push(loc, || format!("function <{}> call", f.name()), body)?402 }403 }404 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),405 })406}407408pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {409 use Expr::*;410 let LocExpr(expr, _loc) = lexpr;411 Ok(match &**expr {412 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),413 _ => evaluate(context, lexpr)?,414 })415}416417pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {418 use Expr::*;419 let LocExpr(expr, loc) = expr;420 Ok(match &**expr {421 Literal(LiteralType::This) => Val::Obj(422 context423 .this()424 .clone()425 .ok_or_else(|| CantUseSelfOutsideOfObject)?,426 ),427 Literal(LiteralType::Dollar) => Val::Obj(428 context429 .dollar()430 .clone()431 .ok_or_else(|| NoTopLevelObjectFound)?,432 ),433 Literal(LiteralType::True) => Val::Bool(true),434 Literal(LiteralType::False) => Val::Bool(false),435 Literal(LiteralType::Null) => Val::Null,436 Parened(e) => evaluate(context, e)?,437 Str(v) => Val::Str(v.clone()),438 Num(v) => Val::new_checked_num(*v)?,439 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,440 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,441 Var(name) => push(442 loc,443 || format!("variable <{}>", name),444 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),445 )?,446 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {447 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;448 context449 .super_obj()450 .clone()451 .expect("no super found")452 .get_raw(name, &context.this().clone().expect("no this found"))?453 .expect("value not found")454 }455 Index(value, index) => {456 match (457 evaluate(context.clone(), value)?.unwrap_if_lazy()?,458 evaluate(context, index)?,459 ) {460 (Val::Obj(v), Val::Str(s)) => {461 let sn = s.clone();462 push(463 &loc,464 || format!("field <{}> access", sn),465 || {466 if let Some(v) = v.get(s.clone())? {467 Ok(v.unwrap_if_lazy()?)468 } else if let Some(Val::Str(n)) =469 v.get("__intristic_namespace__".into())?470 {471 Ok(Val::Func(FuncVal::Intristic(n, s)))472 } else {473 throw!(NoSuchField(s))474 }475 },476 )?477 }478 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(479 ValType::Obj,480 ValType::Str,481 n.value_type()?,482 )),483484 (Val::Arr(v), Val::Num(n)) => {485 if n.fract() > f64::EPSILON {486 throw!(FractionalIndex)487 }488 v.get(n as usize)489 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?490 .clone()491 .unwrap_if_lazy()?492 }493 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),494 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(495 ValType::Arr,496 ValType::Num,497 n.value_type()?,498 )),499500 (Val::Str(s), Val::Num(n)) => Val::Str(501 s.chars()502 .skip(n as usize)503 .take(1)504 .collect::<String>()505 .into(),506 ),507 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(508 ValType::Str,509 ValType::Num,510 n.value_type()?,511 )),512513 (v, _) => throw!(CantIndexInto(v.value_type()?)),514 }515 }516 LocalExpr(bindings, returned) => {517 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();518 let future_context = Context::new_future();519520 let context_creator = context_creator!(521 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))522 );523524 for (k, v) in bindings525 .iter()526 .map(|b| evaluate_binding(b, context_creator.clone()))527 {528 new_bindings.insert(k, v);529 }530531 let context = context532 .extend_unbound(new_bindings, None, None, None)?533 .into_future(future_context);534 evaluate(context, &returned.clone())?535 }536 Arr(items) => {537 let mut out = Vec::with_capacity(items.len());538 for item in items {539 out.push(Val::Lazy(lazy_val!(540 closure!(clone context, clone item, || {541 evaluate(context.clone(), &item)542 })543 )));544 }545 Val::Arr(Rc::new(out))546 }547 ArrComp(expr, compspecs) => Val::Arr(548 549 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),550 ),551 Obj(body) => Val::Obj(evaluate_object(context, body)?),552 ObjExtend(s, t) => evaluate_add_op(553 &evaluate(context.clone(), s)?,554 &Val::Obj(evaluate_object(context, t)?),555 )?,556 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,557 Function(params, body) => {558 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())559 }560 AssertExpr(AssertStmt(value, msg), returned) => {561 let assertion_result = push(562 &value.1,563 || "assertion condition".to_owned(),564 || {565 evaluate(context.clone(), &value)?566 .try_cast_bool("assertion condition should be boolean")567 },568 )?;569 if assertion_result {570 evaluate(context, returned)?571 } else if let Some(msg) = msg {572 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));573 } else {574 throw!(AssertionFailed(Val::Null.to_string()?));575 }576 }577 ErrorStmt(e) => push(578 &loc,579 || "error statement".to_owned(),580 || {581 throw!(RuntimeError(582 evaluate(context, e)?.try_cast_str("error text should be string")?,583 ))584 },585 )?,586 IfElse {587 cond,588 cond_then,589 cond_else,590 } => {591 if evaluate(context.clone(), &cond.0)?592 .try_cast_bool("if condition should be boolean")?593 {594 evaluate(context, cond_then)?595 } else {596 match cond_else {597 Some(v) => evaluate(context, v)?,598 None => Val::Null,599 }600 }601 }602 Import(path) => {603 let mut tmp = loc604 .clone()605 .expect("imports can't be used without loc_data")606 .0;607 let import_location = Rc::make_mut(&mut tmp);608 import_location.pop();609 push(610 loc,611 || format!("import {:?}", path),612 || with_state(|s| s.import_file(&import_location, path)),613 )?614 }615 ImportStr(path) => {616 let mut tmp = loc617 .clone()618 .expect("imports can't be used without loc_data")619 .0;620 let import_location = Rc::make_mut(&mut tmp);621 import_location.pop();622 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)623 }624 Literal(LiteralType::Super) => throw!(StandaloneSuper),625 })626}