difftreelog
feat push stack in assertion failure
in: master
1 file changed
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use 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_parser::{7 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,8 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,9 Visibility,10};11use jrsonnet_types::ValType;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 value = evaluate(context, expr)?;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 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),77 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),78 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),79 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),80 })81}8283pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {84 Ok(match (a, b) {85 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),8687 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)88 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),89 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9091 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),92 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9394 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),95 (Val::Arr(a), Val::Arr(b)) => {96 let mut out = Vec::with_capacity(a.len() + b.len());97 out.extend(a.iter_lazy());98 out.extend(b.iter_lazy());99 Val::Arr(out.into())100 }101 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,102 _ => throw!(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(match (evaluate(context.clone(), a)?, op, b) {117 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),118 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),119 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,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 // Bool X Bool130 (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 // Str X Str134 (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 // Num X Num140 (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))) => match evaluate(context.clone(), expr)? {203 Val::Arr(list) => {204 let mut out = Vec::new();205 for item in list.iter() {206 out.push(evaluate_comp(207 context.clone().with_var(var.clone(), item?.clone()),208 value,209 &specs[1..],210 )?);211 }212 Some(out.into_iter().flatten().flatten().collect())213 }214 _ => throw!(InComprehensionCanOnlyIterateOverArray),215 },216 })217}218219pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {220 let new_bindings = FutureNewBindings::new();221 let future_this = FutureObjValue::new();222 let context_creator = context_creator!(223 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {224 Ok(context.clone().extend_unbound(225 new_bindings.clone().unwrap(),226 context.dollar().clone().or_else(||this.clone()),227 Some(this.unwrap()),228 super_obj229 )?)230 })231 );232 {233 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();234 for (n, b) in members235 .iter()236 .filter_map(|m| match m {237 Member::BindStmt(b) => Some(b.clone()),238 _ => None,239 })240 .map(|b| evaluate_binding(&b, context_creator.clone()))241 {242 bindings.insert(n, b);243 }244 new_bindings.fill(bindings);245 }246247 let mut new_members = HashMap::new();248 for member in members.iter() {249 match member {250 Member::Field(FieldMember {251 name,252 plus,253 params: None,254 visibility,255 value,256 }) => {257 let name = evaluate_field_name(context.clone(), name)?;258 if name.is_none() {259 continue;260 }261 let name = name.unwrap();262 new_members.insert(263 name.clone(),264 ObjMember {265 add: *plus,266 visibility: *visibility,267 invoke: LazyBinding::Bindable(Rc::new(268 closure!(clone name, clone value, clone context_creator, |this, super_obj| {269 Ok(LazyVal::new_resolved(evaluate(270 context_creator.0(this, super_obj)?,271 &value,272 )?))273 }),274 )),275 location: value.1.clone(),276 },277 );278 }279 Member::Field(FieldMember {280 name,281 params: Some(params),282 value,283 ..284 }) => {285 let name = evaluate_field_name(context.clone(), name)?;286 if name.is_none() {287 continue;288 }289 let name = name.unwrap();290 new_members.insert(291 name.clone(),292 ObjMember {293 add: false,294 visibility: Visibility::Hidden,295 invoke: LazyBinding::Bindable(Rc::new(296 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {297 // TODO: Assert298 Ok(LazyVal::new_resolved(evaluate_method(299 context_creator.0(this, super_obj)?,300 name.clone(),301 params.clone(),302 value.clone(),303 )))304 }),305 )),306 location: value.1.clone(),307 },308 );309 }310 Member::BindStmt(_) => {}311 Member::AssertStmt(_) => {}312 }313 }314 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))315}316317pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {318 Ok(match object {319 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,320 ObjBody::ObjComp(obj) => {321 let future_this = FutureObjValue::new();322 let mut new_members = HashMap::new();323 for (k, v) in evaluate_comp(324 context.clone(),325 &|ctx| {326 let new_bindings = FutureNewBindings::new();327 let context_creator = context_creator!(328 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {329 Ok(context.clone().extend_unbound(330 new_bindings.clone().unwrap(),331 context.dollar().clone().or_else(||this.clone()),332 None,333 super_obj334 )?)335 })336 );337 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();338 for (n, b) in obj339 .pre_locals340 .iter()341 .chain(obj.post_locals.iter())342 .map(|b| evaluate_binding(b, context_creator.clone()))343 {344 bindings.insert(n, b);345 }346 let bindings = new_bindings.fill(bindings);347 let ctx = ctx.extend_unbound(bindings, None, None, None)?;348 let key = evaluate(ctx.clone(), &obj.key)?;349 let value = LazyBinding::Bindable(Rc::new(350 closure!(clone ctx, clone obj.value, |this, _super_obj| {351 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))352 }),353 ));354355 Ok((key, value))356 },357 &obj.compspecs,358 )?359 .unwrap()360 {361 match k {362 Val::Null => {}363 Val::Str(n) => {364 new_members.insert(365 n,366 ObjMember {367 add: false,368 visibility: Visibility::Normal,369 invoke: v,370 location: obj.value.1.clone(),371 },372 );373 }374 v => throw!(FieldMustBeStringGot(v.value_type())),375 }376 }377378 future_this.fill(ObjValue::new(None, Rc::new(new_members)))379 }380 })381}382383pub fn evaluate_apply(384 context: Context,385 value: &LocExpr,386 args: &ArgsDesc,387 loc: &Option<ExprLocation>,388 tailstrict: bool,389) -> Result<Val> {390 let value = evaluate(context.clone(), value)?;391 Ok(match value {392 Val::Func(f) => {393 let body = || f.evaluate(context, loc, args, tailstrict);394 if tailstrict {395 body()?396 } else {397 push(loc, || format!("function <{}> call", f.name()), body)?398 }399 }400 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),401 })402}403404pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {405 use Expr::*;406 let LocExpr(expr, _loc) = lexpr;407 Ok(match &**expr {408 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),409 _ => evaluate(context, lexpr)?,410 })411}412413pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {414 use Expr::*;415 let LocExpr(expr, loc) = expr;416 Ok(match &**expr {417 Literal(LiteralType::This) => {418 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)419 }420 Literal(LiteralType::Dollar) => {421 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)422 }423 Literal(LiteralType::True) => Val::Bool(true),424 Literal(LiteralType::False) => Val::Bool(false),425 Literal(LiteralType::Null) => Val::Null,426 Parened(e) => evaluate(context, e)?,427 Str(v) => Val::Str(v.clone()),428 Num(v) => Val::new_checked_num(*v)?,429 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,430 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,431 Var(name) => push(432 loc,433 || format!("variable <{}>", name),434 || Ok(context.binding(name.clone())?.evaluate()?),435 )?,436 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {437 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;438 context439 .super_obj()440 .clone()441 .expect("no super found")442 .get_raw(name, Some(&context.this().clone().expect("no this found")))?443 .expect("value not found")444 }445 Index(value, index) => {446 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {447 (Val::Obj(v), Val::Str(s)) => {448 let sn = s.clone();449 push(450 loc,451 || format!("field <{}> access", sn),452 || {453 if let Some(v) = v.get(s.clone())? {454 Ok(v)455 } else if v.get("__intrinsic_namespace__".into())?.is_some() {456 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))457 } else {458 throw!(NoSuchField(s))459 }460 },461 )?462 }463 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(464 ValType::Obj,465 ValType::Str,466 n.value_type(),467 )),468469 (Val::Arr(v), Val::Num(n)) => {470 if n.fract() > f64::EPSILON {471 throw!(FractionalIndex)472 }473 v.get(n as usize)?474 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?475 .clone()476 }477 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),478 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(479 ValType::Arr,480 ValType::Num,481 n.value_type(),482 )),483484 (Val::Str(s), Val::Num(n)) => Val::Str(485 s.chars()486 .skip(n as usize)487 .take(1)488 .collect::<String>()489 .into(),490 ),491 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(492 ValType::Str,493 ValType::Num,494 n.value_type(),495 )),496497 (v, _) => throw!(CantIndexInto(v.value_type())),498 }499 }500 LocalExpr(bindings, returned) => {501 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();502 let future_context = Context::new_future();503504 let context_creator = context_creator!(505 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))506 );507508 for (k, v) in bindings509 .iter()510 .map(|b| evaluate_binding(b, context_creator.clone()))511 {512 new_bindings.insert(k, v);513 }514515 let context = context516 .extend_unbound(new_bindings, None, None, None)?517 .into_future(future_context);518 evaluate(context, &returned.clone())?519 }520 Arr(items) => {521 let mut out = Vec::with_capacity(items.len());522 for item in items {523 out.push(LazyVal::new(Box::new(524 closure!(clone context, clone item, || {525 evaluate(context.clone(), &item)526 }),527 )));528 }529 Val::Arr(out.into())530 }531 ArrComp(expr, comp_specs) => Val::Arr(532 // First comp_spec should be for_spec, so no "None" possible here533 evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?534 .unwrap()535 .into(),536 ),537 Obj(body) => Val::Obj(evaluate_object(context, body)?),538 ObjExtend(s, t) => evaluate_add_op(539 &evaluate(context.clone(), s)?,540 &Val::Obj(evaluate_object(context, t)?),541 )?,542 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,543 Function(params, body) => {544 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())545 }546 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),547 AssertExpr(AssertStmt(value, msg), returned) => {548 let assertion_result = push(549 &value.1,550 || "assertion condition".to_owned(),551 || {552 evaluate(context.clone(), value)?553 .try_cast_bool("assertion condition should be of type `boolean`")554 },555 )?;556 if assertion_result {557 evaluate(context, returned)?558 } else if let Some(msg) = msg {559 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));560 } else {561 throw!(AssertionFailed(Val::Null.to_string()?));562 }563 }564 ErrorStmt(e) => push(565 loc,566 || "error statement".to_owned(),567 || {568 throw!(RuntimeError(569 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,570 ))571 },572 )?,573 IfElse {574 cond,575 cond_then,576 cond_else,577 } => {578 if push(579 loc,580 || "if condition".to_owned(),581 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),582 )? {583 evaluate(context, cond_then)?584 } else {585 match cond_else {586 Some(v) => evaluate(context, v)?,587 None => Val::Null,588 }589 }590 }591 Import(path) => {592 let mut tmp = loc593 .clone()594 .expect("imports cannot be used without loc_data")595 .0;596 let import_location = Rc::make_mut(&mut tmp);597 import_location.pop();598 push(599 loc,600 || format!("import {:?}", path),601 || with_state(|s| s.import_file(import_location, path)),602 )?603 }604 ImportStr(path) => {605 let mut tmp = loc606 .clone()607 .expect("imports cannot be used without loc_data")608 .0;609 let import_location = Rc::make_mut(&mut tmp);610 import_location.pop();611 Val::Str(with_state(|s| s.import_file_str(import_location, path))?)612 }613 Literal(LiteralType::Super) => throw!(StandaloneSuper),614 })615}