difftreelog
refactor Option<&ExprLocation> -> &Option<_>
in: master
6 files changed
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -22,7 +22,7 @@
fn std_format(str: IStr, vals: Val) -> Result<Val> {
push(
- &Some(ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
+ Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
|| format!("std.format of {}", str),
|| {
Ok(match vals {
@@ -34,7 +34,7 @@
)
}
-type Builtin = fn(context: Context, loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val>;
+type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;
type BuiltinsType = HashMap<Box<str>, Builtin>;
@@ -78,7 +78,7 @@
};
}
-fn builtin_length(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_length(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "length", args, 1, [
0, x: ty!((string | object | array));
], {
@@ -96,7 +96,7 @@
})
}
-fn builtin_type(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_type(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "type", args, 1, [
0, x: ty!(any);
], {
@@ -106,7 +106,7 @@
fn builtin_make_array(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "makeArray", args, 2, [
@@ -126,7 +126,7 @@
fn builtin_codepoint(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "codepoint", args, 1, [
@@ -138,7 +138,7 @@
fn builtin_object_fields_ex(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "objectFieldsEx", args, 2, [
@@ -157,7 +157,7 @@
fn builtin_object_has_ex(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "objectHasEx", args, 3, [
@@ -175,7 +175,7 @@
}
// faster
-fn builtin_slice(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_slice(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "slice", args, 4, [
0, indexable: ty!((string | array));
1, index: ty!((number | null));
@@ -216,7 +216,7 @@
// faster
fn builtin_primitive_equals(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "primitiveEquals", args, 2, [
@@ -228,7 +228,7 @@
}
// faster
-fn builtin_equals(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_equals(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "equals", args, 2, [
0, a: ty!(any);
1, b: ty!(any);
@@ -237,7 +237,7 @@
})
}
-fn builtin_modulo(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_modulo(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "modulo", args, 2, [
0, a: ty!(number) => Val::Num;
1, b: ty!(number) => Val::Num;
@@ -246,7 +246,7 @@
})
}
-fn builtin_mod(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_mod(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "mod", args, 2, [
0, a: ty!((number | string));
1, b: ty!(any);
@@ -259,7 +259,7 @@
})
}
-fn builtin_floor(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_floor(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "floor", args, 1, [
0, x: ty!(number) => Val::Num;
], {
@@ -267,7 +267,7 @@
})
}
-fn builtin_log(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_log(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "log", args, 1, [
0, n: ty!(number) => Val::Num;
], {
@@ -275,7 +275,7 @@
})
}
-fn builtin_pow(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_pow(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "pow", args, 2, [
0, x: ty!(number) => Val::Num;
1, n: ty!(number) => Val::Num;
@@ -284,7 +284,7 @@
})
}
-fn builtin_ext_var(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_ext_var(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "extVar", args, 1, [
0, x: ty!(string) => Val::Str;
], {
@@ -292,7 +292,7 @@
})
}
-fn builtin_native(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_native(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "native", args, 1, [
0, x: ty!(string) => Val::Str;
], {
@@ -300,7 +300,7 @@
})
}
-fn builtin_filter(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_filter(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "filter", args, 2, [
0, func: ty!(function) => Val::Func;
1, arr: ty!(array) => Val::Arr;
@@ -318,7 +318,7 @@
})
}
-fn builtin_foldl(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_foldl(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "foldl", args, 3, [
0, func: ty!(function) => Val::Func;
1, arr: ty!(array) => Val::Arr;
@@ -332,7 +332,7 @@
})
}
-fn builtin_foldr(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_foldr(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "foldr", args, 3, [
0, func: ty!(function) => Val::Func;
1, arr: ty!(array) => Val::Arr;
@@ -349,7 +349,7 @@
#[allow(non_snake_case)]
fn builtin_sort_impl(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "sort", args, 2, [
@@ -364,7 +364,7 @@
}
// faster
-fn builtin_format(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_format(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "format", args, 2, [
0, str: ty!(string) => Val::Str;
1, vals: ty!(any)
@@ -373,7 +373,7 @@
})
}
-fn builtin_range(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_range(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "range", args, 2, [
0, from: ty!(number) => Val::Num;
1, to: ty!(number) => Val::Num;
@@ -386,7 +386,7 @@
})
}
-fn builtin_char(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_char(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "char", args, 1, [
0, n: ty!(number) => Val::Num;
], {
@@ -400,7 +400,7 @@
fn builtin_encode_utf8(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "encodeUTF8", args, 1, [
@@ -410,7 +410,7 @@
})
}
-fn builtin_md5(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_md5(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "md5", args, 1, [
0, str: ty!(string) => Val::Str;
], {
@@ -418,7 +418,7 @@
})
}
-fn builtin_trace(context: Context, loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_trace(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "trace", args, 2, [
0, str: ty!(string) => Val::Str;
1, rest: ty!(any);
@@ -435,7 +435,7 @@
})
}
-fn builtin_base64(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_base64(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "base64", args, 1, [
0, input: ty!((string | (Array<number>)));
], {
@@ -453,7 +453,7 @@
})
}
-fn builtin_join(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_join(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "join", args, 2, [
0, sep: ty!((string | array));
1, arr: ty!(array) => Val::Arr;
@@ -513,7 +513,7 @@
// faster
fn builtin_escape_string_json(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "escapeStringJson", args, 1, [
@@ -526,7 +526,7 @@
// faster
fn builtin_manifest_json_ex(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "manifestJsonEx", args, 2, [
@@ -541,7 +541,7 @@
}
// faster
-fn builtin_reverse(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_reverse(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "reverse", args, 1, [
0, value: ty!(array) => Val::Arr;
], {
@@ -549,7 +549,7 @@
})
}
-fn builtin_id(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_id(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "id", args, 1, [
0, v: ty!(any);
], {
@@ -560,7 +560,7 @@
// faster
fn builtin_str_replace(
context: Context,
- _loc: &Option<ExprLocation>,
+ _loc: Option<&ExprLocation>,
args: &ArgsDesc,
) -> Result<Val> {
parse_args!(context, "strReplace", args, 3, [
@@ -583,10 +583,9 @@
})
}
-#[allow(clippy::cognitive_complexity)]
pub fn call_builtin(
context: Context,
- loc: &Option<ExprLocation>,
+ loc: Option<&ExprLocation>,
name: &str,
args: &ArgsDesc,
) -> Result<Val> {
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_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 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)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 // Bool X Bool131 (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 // Str X Str135 (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 // Num X Num141 (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 // TODO: Assert299 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 // First comp_spec should be for_spec, so no "None" possible here534 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}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 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)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 // Bool X Bool131 (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 // Str X Str135 (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 // Num X Num141 (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 // TODO: Assert299 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.as_ref(),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.as_ref(),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 // First comp_spec should be for_spec, so no "None" possible here534 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.as_ref(), *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.as_ref(),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.as_ref(),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.as_ref(),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.as_ref(),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.as_ref(),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}crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -160,7 +160,7 @@
throw!(IntrinsicArgumentReorderingIsNotSupportedYet);
}
}
- let $name = push(&None, || format!("evaluating argument"), || {
+ let $name = push(None, || format!("evaluating argument"), || {
let value = evaluate($ctx.clone(), &$name.1)?;
$ty.check(&value)?;
Ok(value)
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -128,7 +128,7 @@
EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
}
pub(crate) fn push<T>(
- e: &Option<ExprLocation>,
+ e: Option<&ExprLocation>,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -78,7 +78,7 @@
}
fn push_type(
- location: &Option<ExprLocation>,
+ location: Option<&ExprLocation>,
error_reason: impl Fn() -> String,
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
@@ -162,7 +162,7 @@
Val::Arr(a) => {
for (i, item) in a.iter().enumerate() {
push_type(
- &None,
+ None,
|| format!("array index {}", i),
|| ValuePathItem::Index(i as u64),
|| Ok(elem_type.check(&item.clone()?)?),
@@ -176,7 +176,7 @@
Val::Arr(a) => {
for (i, item) in a.iter().enumerate() {
push_type(
- &None,
+ None,
|| format!("array index {}", i),
|| ValuePathItem::Index(i as u64),
|| Ok(elem_type.check(&item.clone()?)?),
@@ -191,7 +191,7 @@
for (k, v) in elems.iter() {
if let Some(got_v) = obj.get((*k).into())? {
push_type(
- &None,
+ None,
|| format!("property {}", k),
|| ValuePathItem::Field((*k).into()),
|| v.check(&got_v),
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -102,7 +102,7 @@
pub fn evaluate(
&self,
call_ctx: Context,
- loc: &Option<ExprLocation>,
+ loc: Option<&ExprLocation>,
args: &ArgsDesc,
tailstrict: bool,
) -> Result<Val> {