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 rustc_hash::FxHashMap;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(FuncVal::Normal(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) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),82 })83}8485pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {86 Ok(match (a, b) {87 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8889 90 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),91 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9293 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),94 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9596 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),97 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),98 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,99 _ => throw!(BinaryOperatorDoesNotOperateOnValues(100 BinaryOpType::Add,101 a.value_type()?,102 b.value_type()?,103 )),104 })105}106107pub fn evaluate_binary_op_special(108 context: Context,109 a: &LocExpr,110 op: BinaryOpType,111 b: &LocExpr,112) -> Result<Val> {113 Ok(114 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117 (a, op, eb) => {118 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?119 }120 },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<Rc<str>, 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))) => {204 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {205 Val::Arr(list) => {206 let mut out = Vec::new();207 for item in list.iter() {208 let item = item.unwrap_if_lazy()?;209 out.push(evaluate_comp(210 context.clone().with_var(var.clone(), item.clone()),211 value,212 &specs[1..],213 )?);214 }215 Some(out.into_iter().flatten().flatten().collect())216 }217 _ => throw!(InComprehensionCanOnlyIterateOverArray),218 }219 }220 })221}222223pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {224 let new_bindings = FutureNewBindings::new();225 let future_this = FutureObjValue::new();226 let context_creator = context_creator!(227 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {228 Ok(context.clone().extend_unbound(229 new_bindings.clone().unwrap(),230 context.dollar().clone().or_else(||this.clone()),231 Some(this.unwrap()),232 super_obj233 )?)234 })235 );236 {237 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();238 for (n, b) in members239 .iter()240 .filter_map(|m| match m {241 Member::BindStmt(b) => Some(b.clone()),242 _ => None,243 })244 .map(|b| evaluate_binding(&b, context_creator.clone()))245 {246 bindings.insert(n, b);247 }248 new_bindings.fill(bindings);249 }250251 let mut new_members = HashMap::new();252 for member in members.iter() {253 match member {254 Member::Field(FieldMember {255 name,256 plus,257 params: None,258 visibility,259 value,260 }) => {261 let name = evaluate_field_name(context.clone(), &name)?;262 if name.is_none() {263 continue;264 }265 let name = name.unwrap();266 new_members.insert(267 name.clone(),268 ObjMember {269 add: *plus,270 visibility: *visibility,271 invoke: LazyBinding::Bindable(Rc::new(272 closure!(clone name, clone value, clone context_creator, |this, super_obj| {273 Ok(LazyVal::new_resolved(evaluate(274 context_creator.0(this, super_obj)?,275 &value,276 )?))277 }),278 )),279 location: value.1.clone(),280 },281 );282 }283 Member::Field(FieldMember {284 name,285 params: Some(params),286 value,287 ..288 }) => {289 let name = evaluate_field_name(context.clone(), &name)?;290 if name.is_none() {291 continue;292 }293 let name = name.unwrap();294 new_members.insert(295 name.clone(),296 ObjMember {297 add: false,298 visibility: Visibility::Hidden,299 invoke: LazyBinding::Bindable(Rc::new(300 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {301 302 Ok(LazyVal::new_resolved(evaluate_method(303 context_creator.0(this, super_obj)?,304 name.clone(),305 params.clone(),306 value.clone(),307 )))308 }),309 )),310 location: value.1.clone(),311 },312 );313 }314 Member::BindStmt(_) => {}315 Member::AssertStmt(_) => {}316 }317 }318 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))319}320321pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,324 ObjBody::ObjComp(obj) => {325 let future_this = FutureObjValue::new();326 let mut new_members = HashMap::new();327 for (k, v) in evaluate_comp(328 context.clone(),329 &|ctx| {330 let new_bindings = FutureNewBindings::new();331 let context_creator = context_creator!(332 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {333 Ok(context.clone().extend_unbound(334 new_bindings.clone().unwrap(),335 context.dollar().clone().or_else(||this.clone()),336 None,337 super_obj338 )?)339 })340 );341 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();342 for (n, b) in obj343 .pre_locals344 .iter()345 .chain(obj.post_locals.iter())346 .map(|b| evaluate_binding(b, context_creator.clone()))347 {348 bindings.insert(n, b);349 }350 let bindings = new_bindings.fill(bindings);351 let ctx = ctx.extend_unbound(bindings, None, None, None)?;352 let key = evaluate(ctx.clone(), &obj.key)?;353 let value = LazyBinding::Bindable(Rc::new(354 closure!(clone ctx, clone obj.value, |this, _super_obj| {355 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))356 }),357 ));358359 Ok((key, value))360 },361 &obj.compspecs,362 )?363 .unwrap()364 {365 match k {366 Val::Null => {}367 Val::Str(n) => {368 new_members.insert(369 n,370 ObjMember {371 add: false,372 visibility: Visibility::Normal,373 invoke: v,374 location: obj.value.1.clone(),375 },376 );377 }378 v => throw!(FieldMustBeStringGot(v.value_type()?)),379 }380 }381382 future_this.fill(ObjValue::new(None, Rc::new(new_members)))383 }384 })385}386387pub fn evaluate_apply(388 context: Context,389 value: &LocExpr,390 args: &ArgsDesc,391 loc: &Option<ExprLocation>,392 tailstrict: bool,393) -> Result<Val> {394 let lazy = evaluate(context.clone(), value)?;395 let value = lazy.unwrap_if_lazy()?;396 Ok(match value {397 Val::Func(f) => {398 let body = || f.evaluate(context, loc, args, tailstrict);399 if tailstrict {400 body()?401 } else {402 push(loc, || format!("function <{}> call", f.name()), body)?403 }404 }405 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),406 })407}408409pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {410 use Expr::*;411 let LocExpr(expr, _loc) = lexpr;412 Ok(match &**expr {413 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),414 _ => evaluate(context, lexpr)?,415 })416}417418pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {419 use Expr::*;420 let LocExpr(expr, loc) = expr;421 Ok(match &**expr {422 Literal(LiteralType::This) => Val::Obj(423 context424 .this()425 .clone()426 .ok_or_else(|| CantUseSelfOutsideOfObject)?,427 ),428 Literal(LiteralType::Dollar) => Val::Obj(429 context430 .dollar()431 .clone()432 .ok_or_else(|| NoTopLevelObjectFound)?,433 ),434 Literal(LiteralType::True) => Val::Bool(true),435 Literal(LiteralType::False) => Val::Bool(false),436 Literal(LiteralType::Null) => Val::Null,437 Parened(e) => evaluate(context, e)?,438 Str(v) => Val::Str(v.clone()),439 Num(v) => Val::new_checked_num(*v)?,440 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,442 Var(name) => push(443 loc,444 || format!("variable <{}>", name),445 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),446 )?,447 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {448 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;449 context450 .super_obj()451 .clone()452 .expect("no super found")453 .get_raw(name, &context.this().clone().expect("no this found"))?454 .expect("value not found")455 }456 Index(value, index) => {457 match (458 evaluate(context.clone(), value)?.unwrap_if_lazy()?,459 evaluate(context, index)?,460 ) {461 (Val::Obj(v), Val::Str(s)) => {462 let sn = s.clone();463 push(464 &loc,465 || format!("field <{}> access", sn),466 || {467 if let Some(v) = v.get(s.clone())? {468 Ok(v.unwrap_if_lazy()?)469 } else if let Some(Val::Str(n)) =470 v.get("__intristic_namespace__".into())?471 {472 Ok(Val::Func(Rc::new(FuncVal::Intristic(n, s))))473 } else {474 throw!(NoSuchField(s))475 }476 },477 )?478 }479 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(480 ValType::Obj,481 ValType::Str,482 n.value_type()?,483 )),484485 (Val::Arr(v), Val::Num(n)) => {486 if n.fract() > f64::EPSILON {487 throw!(FractionalIndex)488 }489 v.get(n as usize)490 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?491 .clone()492 .unwrap_if_lazy()?493 }494 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),495 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(496 ValType::Arr,497 ValType::Num,498 n.value_type()?,499 )),500501 (Val::Str(s), Val::Num(n)) => Val::Str(502 s.chars()503 .skip(n as usize)504 .take(1)505 .collect::<String>()506 .into(),507 ),508 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(509 ValType::Str,510 ValType::Num,511 n.value_type()?,512 )),513514 (v, _) => throw!(CantIndexInto(v.value_type()?)),515 }516 }517 LocalExpr(bindings, returned) => {518 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();519 let future_context = Context::new_future();520521 let context_creator = context_creator!(522 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))523 );524525 for (k, v) in bindings526 .iter()527 .map(|b| evaluate_binding(b, context_creator.clone()))528 {529 new_bindings.insert(k, v);530 }531532 let context = context533 .extend_unbound(new_bindings, None, None, None)?534 .into_future(future_context);535 evaluate(context, &returned.clone())?536 }537 Arr(items) => {538 let mut out = Vec::with_capacity(items.len());539 for item in items {540 out.push(Val::Lazy(lazy_val!(541 closure!(clone context, clone item, || {542 evaluate(context.clone(), &item)543 })544 )));545 }546 Val::Arr(Rc::new(out))547 }548 ArrComp(expr, compspecs) => Val::Arr(549 550 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),551 ),552 Obj(body) => Val::Obj(evaluate_object(context, body)?),553 ObjExtend(s, t) => evaluate_add_op(554 &evaluate(context.clone(), s)?,555 &Val::Obj(evaluate_object(context, t)?),556 )?,557 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,558 Function(params, body) => {559 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())560 }561 AssertExpr(AssertStmt(value, msg), returned) => {562 let assertion_result = push(563 &value.1,564 || "assertion condition".to_owned(),565 || {566 evaluate(context.clone(), &value)?567 .try_cast_bool("assertion condition should be boolean")568 },569 )?;570 if assertion_result {571 evaluate(context, returned)?572 } else if let Some(msg) = msg {573 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));574 } else {575 throw!(AssertionFailed(Val::Null.to_string()?));576 }577 }578 ErrorStmt(e) => push(579 &loc,580 || "error statement".to_owned(),581 || {582 throw!(RuntimeError(583 evaluate(context, e)?.try_cast_str("error text should be string")?,584 ))585 },586 )?,587 IfElse {588 cond,589 cond_then,590 cond_else,591 } => {592 if evaluate(context.clone(), &cond.0)?593 .try_cast_bool("if condition should be boolean")?594 {595 evaluate(context, cond_then)?596 } else {597 match cond_else {598 Some(v) => evaluate(context, v)?,599 None => Val::Null,600 }601 }602 }603 Import(path) => {604 let mut tmp = loc605 .clone()606 .expect("imports can't be used without loc_data")607 .0;608 let import_location = Rc::make_mut(&mut tmp);609 import_location.pop();610 push(611 loc,612 || format!("import {:?}", path),613 || with_state(|s| s.import_file(&import_location, path)),614 )?615 }616 ImportStr(path) => {617 let mut tmp = loc618 .clone()619 .expect("imports can't be used without loc_data")620 .0;621 let import_location = Rc::make_mut(&mut tmp);622 import_location.pop();623 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)624 }625 Literal(LiteralType::Super) => throw!(StandaloneSuper),626 })627}