difftreelog
style increase clippy linting level
in: master
15 files changed
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -314,7 +314,7 @@
for _ in 0..zp2 {
out.push('0');
}
- out.push_str(&prefix);
+ out.push_str(prefix);
for digit in digits.into_iter().rev() {
let ch = NUMBERS[digit as usize] as char;
@@ -399,7 +399,10 @@
}
return;
}
- let frac = (n.fract() * 10.0_f64.powf(precision as f64) + 0.5).floor();
+ let frac = n
+ .fract()
+ .mul_add(10.0_f64.powf(precision as f64), 0.5)
+ .floor();
if trailing || frac > 0.0 {
out.push('.');
let mut frac_str = String::new();
@@ -605,7 +608,7 @@
}
pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {
- let codes = parse_codes(&str)?;
+ let codes = parse_codes(str)?;
let mut out = String::new();
for code in codes {
@@ -659,7 +662,7 @@
}
pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
- let codes = parse_codes(&str)?;
+ let codes = parse_codes(str)?;
let mut out = String::new();
for code in codes {
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -20,7 +20,7 @@
pub mtype: ManifestType,
}
-pub(crate) fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
+pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
let mut out = String::new();
manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
Ok(out)
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -16,6 +16,7 @@
pub mod manifest;
pub mod sort;
+#[allow(clippy::cognitive_complexity)]
pub fn call_builtin(
context: Context,
loc: &Option<ExprLocation>,
@@ -23,7 +24,7 @@
name: &str,
args: &ArgsDesc,
) -> Result<Val> {
- Ok(match (ns, &name as &str) {
+ Ok(match (ns, name as &str) {
// arr/string/function
("std", "length") => parse_args!(context, "std.length", args, 1, [
0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -22,7 +22,7 @@
}
jrsonnet_parser::parse(
- &jrsonnet_stdlib::STDLIB_STR,
+ jrsonnet_stdlib::STDLIB_STR,
&ParserSettings {
loc_data: true,
file_name: Rc::new(PathBuf::from("std.jsonnet")),
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -48,8 +48,8 @@
&self.0.super_obj
}
- pub fn new() -> Context {
- Context(Rc::new(ContextInternals {
+ pub fn new() -> Self {
+ Self(Rc::new(ContextInternals {
dollar: None,
this: None,
super_obj: None,
@@ -65,14 +65,14 @@
.cloned()
.ok_or_else(|| UnknownVariable(name))?)
}
- pub fn into_future(self, ctx: FutureContext) -> Context {
+ pub fn into_future(self, ctx: FutureContext) -> Self {
{
ctx.0.borrow_mut().replace(self);
}
ctx.unwrap()
}
- pub fn with_var(self, name: Rc<str>, value: Val) -> Context {
+ pub fn with_var(self, name: Rc<str>, value: Val) -> Self {
let mut new_bindings =
FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
new_bindings.insert(name, resolved_lazy_val!(value));
@@ -85,7 +85,7 @@
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
- ) -> Context {
+ ) -> Self {
match Rc::try_unwrap(self.0) {
Ok(mut ctx) => {
// Extended context aren't used by anything else, we can freely mutate it without cloning
@@ -101,7 +101,7 @@
if !new_bindings.is_empty() {
ctx.bindings = ctx.bindings.extend(new_bindings);
}
- Context(Rc::new(ctx))
+ Self(Rc::new(ctx))
}
Err(ctx) => {
let dollar = new_dollar.or_else(|| ctx.dollar.clone());
@@ -112,7 +112,7 @@
} else {
ctx.bindings.clone().extend(new_bindings)
};
- Context(Rc::new(ContextInternals {
+ Self(Rc::new(ContextInternals {
dollar,
this,
super_obj,
@@ -127,7 +127,7 @@
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
- ) -> Result<Context> {
+ ) -> Result<Self> {
let this = new_this.or_else(|| self.0.this.clone());
let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
let mut new =
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -95,10 +95,10 @@
Self(Box::new((e, StackTrace(vec![]))))
}
- pub fn error(&self) -> &Error {
+ pub const fn error(&self) -> &Error {
&(self.0).0
}
- pub fn trace(&self) -> &StackTrace {
+ pub const fn trace(&self) -> &StackTrace {
&(self.0).1
}
pub fn trace_mut(&mut self) -> &mut StackTrace {
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 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 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)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 // 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<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 // TODO: Assert302 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("__intrinsic_namespace__".into())?471 {472 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(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, comp_specs) => Val::Arr(549 // First comp_spec should be for_spec, so no "None" possible here550 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.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 of type `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 of type `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 of type `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 cannot 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 cannot 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}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 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 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)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 // 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<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 // TODO: Assert302 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("__intrinsic_namespace__".into())?471 {472 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(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, comp_specs) => Val::Arr(549 // First comp_spec should be for_spec, so no "None" possible here550 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.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 of type `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 of type `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 of type `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 cannot 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 cannot 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}crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -75,7 +75,7 @@
let idx = params
.iter()
.position(|p| *p.0 == **name)
- .ok_or_else(|| UnknownFunctionParameter((&name as &str).to_owned()))?;
+ .ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
if idx >= params.len() {
throw!(TooManyArgsFunctionHas(params.len()));
@@ -111,7 +111,7 @@
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
}
-pub(crate) fn place_args(
+pub fn place_args(
ctx: Context,
body_ctx: Option<Context>,
params: &ParamsDesc,
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -41,6 +41,7 @@
panic!("`as_any($self)` is not supported by dummy resolver")
}
}
+#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
fn default() -> Self {
Box::new(DummyImportResolver)
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -14,10 +14,10 @@
type Error = LocError;
fn try_from(v: &Val) -> Result<Self> {
Ok(match v {
- Val::Bool(b) => Value::Bool(*b),
- Val::Null => Value::Null,
- Val::Str(s) => Value::String((&s as &str).into()),
- Val::Num(n) => Value::Number(if n.fract() <= f64::EPSILON {
+ Val::Bool(b) => Self::Bool(*b),
+ Val::Null => Self::Null,
+ Val::Str(s) => Self::String((s as &str).into()),
+ Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {
(*n as i64).into()
} else {
Number::from_f64(*n).expect("to json number")
@@ -28,7 +28,7 @@
for item in a.iter() {
out.push(item.try_into()?);
}
- Value::Array(out)
+ Self::Array(out)
}
Val::Obj(o) => {
let mut out = Map::new();
@@ -38,7 +38,7 @@
(&o.get(key)?.expect("field exists")).try_into()?,
);
}
- Value::Object(out)
+ Self::Object(out)
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
})
@@ -48,16 +48,16 @@
impl From<&Value> for Val {
fn from(v: &Value) -> Self {
match v {
- Value::Null => Val::Null,
- Value::Bool(v) => Val::Bool(*v),
- Value::Number(n) => Val::Num(n.as_f64().expect("as f64")),
- Value::String(s) => Val::Str((s as &str).into()),
+ Value::Null => Self::Null,
+ Value::Bool(v) => Self::Bool(*v),
+ Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),
+ Value::String(s) => Self::Str((s as &str).into()),
Value::Array(a) => {
let mut out = Vec::with_capacity(a.len());
for v in a {
out.push(v.into());
}
- Val::Arr(Rc::new(out))
+ Self::Arr(Rc::new(out))
}
Value::Object(o) => {
let mut entries = HashMap::with_capacity(o.len());
@@ -72,7 +72,7 @@
},
);
}
- Val::Obj(ObjValue::new(None, Rc::new(entries)))
+ Self::Obj(ObjValue::new(None, Rc::new(entries)))
}
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,6 @@
#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
+#![warn(clippy::all, clippy::nursery)]
mod builtin;
mod ctx;
@@ -49,8 +50,8 @@
impl LazyBinding {
pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
match self {
- LazyBinding::Bindable(v) => v(this, super_obj),
- LazyBinding::Bound(v) => Ok(v.clone()),
+ Self::Bindable(v) => v(this, super_obj),
+ Self::Bound(v) => Ok(v.clone()),
}
}
}
@@ -77,7 +78,7 @@
}
impl Default for EvaluationSettings {
fn default() -> Self {
- EvaluationSettings {
+ Self {
max_stack: 200,
max_trace: 20,
globals: Default::default(),
@@ -130,7 +131,7 @@
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
if let Some(v) = e {
- with_state(|s| s.push(&v, frame_desc, f))
+ with_state(|s| s.push(v, frame_desc, f))
} else {
f()
}
@@ -359,10 +360,10 @@
/// Raw methods evaluate passed values but don't perform TLA execution
impl EvaluationState {
pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
- self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))
+ self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
}
pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
- self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))
+ self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
}
/// Parses and evaluates the given snippet
pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -15,10 +15,10 @@
match Rc::try_unwrap(self.0) {
Ok(mut map) => {
map.current.extend(new_layer);
- LayeredHashMap(Rc::new(map))
+ Self(Rc::new(map))
}
- Err(this) => LayeredHashMap(Rc::new(LayeredHashMapInternals {
- parent: Some(LayeredHashMap(this)),
+ Err(this) => Self(Rc::new(LayeredHashMapInternals {
+ parent: Some(Self(this)),
current: new_layer,
})),
}
@@ -31,20 +31,20 @@
{
(self.0)
.current
- .get(&key)
+ .get(key)
.or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
}
}
impl<K: Hash, V> Clone for LayeredHashMap<K, V> {
fn clone(&self) -> Self {
- LayeredHashMap(self.0.clone())
+ Self(self.0.clone())
}
}
impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {
fn default() -> Self {
- LayeredHashMap(Rc::new(LayeredHashMapInternals {
+ Self(Rc::new(LayeredHashMapInternals {
parent: None,
current: FxHashMap::default(),
}))
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -47,23 +47,20 @@
}
impl ObjValue {
- pub fn new(
- super_obj: Option<ObjValue>,
- this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
- ) -> ObjValue {
- ObjValue(Rc::new(ObjValueInternals {
+ pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {
+ Self(Rc::new(ObjValueInternals {
super_obj,
this_entries,
value_cache: RefCell::new(HashMap::new()),
}))
}
- pub fn new_empty() -> ObjValue {
+ pub fn new_empty() -> Self {
Self::new(None, Rc::new(HashMap::new()))
}
- pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {
+ pub fn with_super(&self, super_obj: Self) -> Self {
match &self.0.super_obj {
- None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),
- Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
+ None => Self::new(Some(super_obj), self.0.this_entries.clone()),
+ Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
}
}
pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {
@@ -71,7 +68,7 @@
s.enum_fields(handler);
}
for (name, member) in self.0.this_entries.iter() {
- handler(&name, &member.visibility);
+ handler(name, &member.visibility);
}
}
pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {
@@ -107,7 +104,7 @@
pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
Ok(self.get_raw(key, self)?)
}
- pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {
+ pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {
let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -135,7 +132,7 @@
.insert(cache_key, value.clone());
Ok(value)
}
- fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {
+ fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {
Ok(v.invoke
.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
.evaluate()?)
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -17,9 +17,9 @@
impl PathResolver {
pub fn resolve(&self, from: &PathBuf) -> String {
match self {
- PathResolver::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
- PathResolver::Absolute => from.to_string_lossy().into_owned(),
- PathResolver::Relative(base) => {
+ Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
+ Self::Absolute => from.to_string_lossy().into_owned(),
+ Self::Relative(base) => {
if from.is_relative() {
return from.to_string_lossy().into_owned();
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -25,10 +25,10 @@
pub struct LazyVal(Rc<RefCell<LazyValInternals>>);
impl LazyVal {
pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
- LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
+ Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
}
pub fn new_resolved(val: Val) -> Self {
- LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
+ Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
}
pub fn evaluate(&self) -> Result<Val> {
let new_value = match &*self.0.borrow() {
@@ -84,22 +84,22 @@
impl PartialEq for FuncVal {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
- (FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,
- (FuncVal::Intrinsic(ans, an), FuncVal::Intrinsic(bns, bn)) => ans == bns && an == bn,
- (FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,
+ (Self::Normal(a), Self::Normal(b)) => a == b,
+ (Self::Intrinsic(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && an == bn,
+ (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,
(..) => false,
}
}
}
impl FuncVal {
pub fn is_ident(&self) -> bool {
- matches!(&self, FuncVal::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
+ matches!(&self, Self::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
}
pub fn name(&self) -> Rc<str> {
match self {
- FuncVal::Normal(normal) => normal.name.clone(),
- FuncVal::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
- FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),
+ Self::Normal(normal) => normal.name.clone(),
+ Self::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
+ Self::NativeExt(n, _) => format!("native.{}", n).into(),
}
}
pub fn evaluate(
@@ -110,7 +110,7 @@
tailstrict: bool,
) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = parse_function_call(
call_ctx,
Some(func.ctx.clone()),
@@ -120,8 +120,8 @@
)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),
- FuncVal::NativeExt(_name, handler) => {
+ Self::Intrinsic(ns, name) => call_builtin(call_ctx, loc, ns, name, args),
+ Self::NativeExt(_name, handler) => {
let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;
let mut out_args = Vec::with_capacity(handler.params.len());
for p in handler.params.0.iter() {
@@ -139,7 +139,7 @@
tailstrict: bool,
) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = parse_function_call_map(
call_ctx,
Some(func.ctx.clone()),
@@ -149,19 +149,19 @@
)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(_, _) => todo!(),
- FuncVal::NativeExt(_, _) => todo!(),
+ Self::Intrinsic(_, _) => todo!(),
+ Self::NativeExt(_, _) => todo!(),
}
}
pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(_, _) => todo!(),
- FuncVal::NativeExt(_, _) => todo!(),
+ Self::Intrinsic(_, _) => todo!(),
+ Self::NativeExt(_, _) => todo!(),
}
}
}
@@ -177,7 +177,7 @@
Func,
}
impl ValType {
- pub fn name(&self) -> &'static str {
+ pub const fn name(&self) -> &'static str {
use ValType::*;
match self {
Bool => "boolean",
@@ -227,9 +227,9 @@
impl Val {
/// Creates `Val::Num` after checking for numeric overflow.
/// As numbers are `f64`, we can just check for their finity.
- pub fn new_checked_num(num: f64) -> Result<Val> {
+ pub fn new_checked_num(num: f64) -> Result<Self> {
if num.is_finite() {
- Ok(Val::Num(num))
+ Ok(Self::Num(num))
} else {
throw!(RuntimeError("overflow".into()))
}
@@ -245,24 +245,24 @@
}
pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
self.assert_type(context, ValType::Bool)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))
}
pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {
self.assert_type(context, ValType::Str)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))
}
pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
self.assert_type(context, ValType::Num)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))
}
pub fn inplace_unwrap(&mut self) -> Result<()> {
- while let Val::Lazy(lazy) = self {
+ while let Self::Lazy(lazy) = self {
*self = lazy.evaluate()?;
}
Ok(())
}
pub fn unwrap_if_lazy(&self) -> Result<Self> {
- Ok(if let Val::Lazy(v) = self {
+ Ok(if let Self::Lazy(v) = self {
v.evaluate()?.unwrap_if_lazy()?
} else {
self.clone()
@@ -270,27 +270,27 @@
}
pub fn value_type(&self) -> Result<ValType> {
Ok(match self {
- Val::Str(..) => ValType::Str,
- Val::Num(..) => ValType::Num,
- Val::Arr(..) => ValType::Arr,
- Val::Obj(..) => ValType::Obj,
- Val::Bool(_) => ValType::Bool,
- Val::Null => ValType::Null,
- Val::Func(..) => ValType::Func,
- Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
+ Self::Str(..) => ValType::Str,
+ Self::Num(..) => ValType::Num,
+ Self::Arr(..) => ValType::Arr,
+ Self::Obj(..) => ValType::Obj,
+ Self::Bool(_) => ValType::Bool,
+ Self::Null => ValType::Null,
+ Self::Func(..) => ValType::Func,
+ Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
})
}
pub fn to_string(&self) -> Result<Rc<str>> {
Ok(match self.unwrap_if_lazy()? {
- Val::Bool(true) => "true".into(),
- Val::Bool(false) => "false".into(),
- Val::Null => "null".into(),
- Val::Str(s) => s,
+ Self::Bool(true) => "true".into(),
+ Self::Bool(false) => "false".into(),
+ Self::Null => "null".into(),
+ Self::Str(s) => s,
v => manifest_json_ex(
&v,
&ManifestJsonOptions {
- padding: &"",
+ padding: "",
mtype: ManifestType::ToString,
},
)?
@@ -301,7 +301,7 @@
/// Expects value to be object, outputs (key, manifested value) pairs
pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {
let obj = match self {
- Val::Obj(obj) => obj,
+ Self::Obj(obj) => obj,
_ => throw!(MultiManifestOutputIsNotAObject),
};
let keys = obj.visible_fields();
@@ -319,7 +319,7 @@
/// Expects value to be array, outputs manifested values
pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {
let arr = match self {
- Val::Arr(a) => a,
+ Self::Arr(a) => a,
_ => throw!(StreamManifestOutputIsNotAArray),
};
let mut out = Vec::with_capacity(arr.len());
@@ -333,7 +333,7 @@
Ok(match ty {
ManifestFormat::YamlStream(format) => {
let arr = match self {
- Val::Arr(a) => a,
+ Self::Arr(a) => a,
_ => throw!(StreamManifestOutputIsNotAArray),
};
let mut out = String::new();
@@ -358,7 +358,7 @@
ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,
ManifestFormat::Json(padding) => self.to_json(*padding)?,
ManifestFormat::String => match self {
- Val::Str(s) => s.clone(),
+ Self::Str(s) => s.clone(),
_ => throw!(StringManifestOutputIsNotAString),
},
})
@@ -384,7 +384,7 @@
#[cfg(feature = "faster")]
pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
manifest_json_ex(
- &self,
+ self,
&ManifestJsonOptions {
padding: &" ".repeat(padding),
mtype: ManifestType::Std,
@@ -441,7 +441,7 @@
}
}
-fn is_function_like(val: &Val) -> bool {
+const fn is_function_like(val: &Val) -> bool {
matches!(val, Val::Func(_))
}