difftreelog
style fix clippy warnings
in: master
9 files changed
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -42,7 +42,7 @@
}
}
Val::Null => buf.push_str("null"),
- Val::Str(s) => buf.push_str(&escape_string_json(&s)),
+ Val::Str(s) => buf.push_str(&escape_string_json(s)),
Val::Num(n) => write!(buf, "{}", n).unwrap(),
Val::Arr(items) => {
buf.push('[');
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -445,7 +445,7 @@
},
Val::Arr(a) => {
base64::encode(a.iter().map(|v| {
- Ok(v?.clone().unwrap_num()? as u8)
+ Ok(v?.unwrap_num()? as u8)
}).collect::<Result<Vec<_>>>()?).into()
},
_ => unreachable!()
@@ -589,7 +589,7 @@
name: &str,
args: &ArgsDesc,
) -> Result<Val> {
- if let Some(f) = BUILTINS.with(|builtins| builtins.get(name).map(|f| *f)) {
+ if let Some(f) = BUILTINS.with(|builtins| builtins.get(name).copied()) {
return Ok(f(context, loc, args)?);
}
throw!(IntrinsicNotFound(name.into()))
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.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) => {544 evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?545 }546 Function(params, body) => {547 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())548 }549 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),550 AssertExpr(AssertStmt(value, msg), returned) => {551 let assertion_result = push(552 value.1.as_ref(),553 || "assertion condition".to_owned(),554 || {555 evaluate(context.clone(), value)?556 .try_cast_bool("assertion condition should be of type `boolean`")557 },558 )?;559 if assertion_result {560 evaluate(context, returned)?561 } else {562 push(563 value.1.as_ref(),564 || "assertion failure".to_owned(),565 || {566 if let Some(msg) = msg {567 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));568 } else {569 throw!(AssertionFailed(Val::Null.to_string()?));570 }571 },572 )?573 }574 }575 ErrorStmt(e) => push(576 loc.as_ref(),577 || "error statement".to_owned(),578 || {579 throw!(RuntimeError(580 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,581 ))582 },583 )?,584 IfElse {585 cond,586 cond_then,587 cond_else,588 } => {589 if push(590 loc.as_ref(),591 || "if condition".to_owned(),592 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),593 )? {594 evaluate(context, cond_then)?595 } else {596 match cond_else {597 Some(v) => evaluate(context, v)?,598 None => Val::Null,599 }600 }601 }602 Import(path) => {603 let mut tmp = loc604 .clone()605 .expect("imports cannot be used without loc_data")606 .0;607 let import_location = Rc::make_mut(&mut tmp);608 import_location.pop();609 push(610 loc.as_ref(),611 || format!("import {:?}", path),612 || with_state(|s| s.import_file(import_location, path)),613 )?614 }615 ImportStr(path) => {616 let mut tmp = loc617 .clone()618 .expect("imports cannot be used without loc_data")619 .0;620 let import_location = Rc::make_mut(&mut tmp);621 import_location.pop();622 Val::Str(with_state(|s| s.import_file_str(import_location, path))?)623 }624 Literal(LiteralType::Super) => throw!(StandaloneSuper),625 })626}crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::type_complexity)]
+
use crate::{error::Result, Val};
use jrsonnet_parser::ParamsDesc;
use std::fmt::Debug;
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -34,7 +34,7 @@
}
let mut debug = f.debug_struct("ObjValue");
for (name, member) in self.0.this_entries.iter() {
- debug.field(&name, member);
+ debug.field(name, member);
}
#[cfg(feature = "unstable")]
{
@@ -140,7 +140,7 @@
.evaluate()?)
}
- pub fn ptr_eq(a: &ObjValue, b: &ObjValue) -> bool {
+ pub fn ptr_eq(a: &Self, b: &Self) -> bool {
Rc::ptr_eq(&a.0, &b.0)
}
}
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -29,7 +29,7 @@
pub struct TypeLocError(Box<TypeError>, ValuePathStack);
impl From<TypeError> for TypeLocError {
fn from(e: TypeError) -> Self {
- TypeLocError(Box::new(e), ValuePathStack(Vec::new()))
+ Self(Box::new(e), ValuePathStack(Vec::new()))
}
}
impl From<TypeLocError> for LocError {
@@ -61,7 +61,7 @@
write!(out, "{}", err)?;
for (i, line) in out.lines().enumerate() {
- if line.trim().len() == 0 {
+ if line.trim().is_empty() {
continue;
}
if i != 0 {
@@ -118,8 +118,8 @@
impl Display for ValuePathItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- ValuePathItem::Field(name) => write!(f, ".{}", name)?,
- ValuePathItem::Index(idx) => write!(f, "[{}]", idx)?,
+ Self::Field(name) => write!(f, ".{}", name)?,
+ Self::Index(idx) => write!(f, "[{}]", idx)?,
}
Ok(())
}
@@ -140,25 +140,25 @@
impl CheckType for ComplexValType {
fn check(&self, value: &Val) -> Result<()> {
match self {
- ComplexValType::Any => Ok(()),
- ComplexValType::Simple(s) => s.check(value),
- ComplexValType::Char => match value {
+ Self::Any => Ok(()),
+ Self::Simple(s) => s.check(value),
+ Self::Char => match value {
Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
},
- ComplexValType::BoundedNumber(from, to) => {
+ Self::BoundedNumber(from, to) => {
if let Val::Num(n) = value {
if from.map(|from| from > *n).unwrap_or(false)
|| to.map(|to| to <= *n).unwrap_or(false)
{
- return Err(TypeError::BoundsFailed(*n, from.clone(), to.clone()).into());
+ return Err(TypeError::BoundsFailed(*n, *from, *to).into());
}
Ok(())
} else {
Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
}
}
- ComplexValType::Array(elem_type) => match value {
+ Self::Array(elem_type) => match value {
Val::Arr(a) => {
for (i, item) in a.iter().enumerate() {
push_type(
@@ -170,9 +170,9 @@
}
Ok(())
}
- v => return Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
},
- ComplexValType::ArrayRef(elem_type) => match value {
+ Self::ArrayRef(elem_type) => match value {
Val::Arr(a) => {
for (i, item) in a.iter().enumerate() {
push_type(
@@ -184,9 +184,9 @@
}
Ok(())
}
- v => return Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
},
- ComplexValType::ObjectRef(elems) => match value {
+ Self::ObjectRef(elems) => match value {
Val::Obj(obj) => {
for (k, v) in elems.iter() {
if let Some(got_v) = obj.get((*k).into())? {
@@ -202,11 +202,11 @@
);
}
}
- return Ok(());
+ Ok(())
}
- v => return Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
},
- ComplexValType::Union(types) => {
+ Self::Union(types) => {
let mut errors = Vec::new();
for ty in types.iter() {
match ty.check(value) {
@@ -219,9 +219,9 @@
},
}
}
- return Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into());
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
}
- ComplexValType::UnionRef(types) => {
+ Self::UnionRef(types) => {
let mut errors = Vec::new();
for ty in types.iter() {
match ty.check(value) {
@@ -234,15 +234,15 @@
},
}
}
- return Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into());
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
}
- ComplexValType::Sum(types) => {
+ Self::Sum(types) => {
for ty in types.iter() {
ty.check(value)?
}
Ok(())
}
- ComplexValType::SumRef(types) => {
+ Self::SumRef(types) => {
for ty in types.iter() {
ty.check(value)?
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -176,14 +176,14 @@
pub enum ArrValue {
Lazy(Rc<Vec<LazyVal>>),
Eager(Rc<Vec<Val>>),
- Extended(Box<(ArrValue, ArrValue)>),
+ Extended(Box<(Self, Self)>),
}
impl ArrValue {
pub fn len(&self) -> usize {
match self {
- ArrValue::Lazy(l) => l.len(),
- ArrValue::Eager(e) => e.len(),
- ArrValue::Extended(v) => v.0.len() + v.1.len(),
+ Self::Lazy(l) => l.len(),
+ Self::Eager(e) => e.len(),
+ Self::Extended(v) => v.0.len() + v.1.len(),
}
}
@@ -193,15 +193,15 @@
pub fn get(&self, index: usize) -> Result<Option<Val>> {
match self {
- ArrValue::Lazy(vec) => {
+ Self::Lazy(vec) => {
if let Some(v) = vec.get(index) {
Ok(Some(v.evaluate()?))
} else {
Ok(None)
}
}
- ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),
- ArrValue::Extended(v) => {
+ Self::Eager(vec) => Ok(vec.get(index).cloned()),
+ Self::Extended(v) => {
let a_len = v.0.len();
if a_len > index {
v.0.get(index)
@@ -214,12 +214,9 @@
pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {
match self {
- ArrValue::Lazy(vec) => vec.get(index).cloned(),
- ArrValue::Eager(vec) => vec
- .get(index)
- .cloned()
- .map(|val| LazyVal::new_resolved(val)),
- ArrValue::Extended(v) => {
+ Self::Lazy(vec) => vec.get(index).cloned(),
+ Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),
+ Self::Extended(v) => {
let a_len = v.0.len();
if a_len > index {
v.0.get_lazy(index)
@@ -232,15 +229,15 @@
pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {
Ok(match self {
- ArrValue::Lazy(vec) => {
+ Self::Lazy(vec) => {
let mut out = Vec::with_capacity(vec.len());
for item in vec.iter() {
out.push(item.evaluate()?);
}
Rc::new(out)
}
- ArrValue::Eager(vec) => vec.clone(),
- ArrValue::Extended(v) => {
+ Self::Eager(vec) => vec.clone(),
+ Self::Extended(_v) => {
let mut out = Vec::with_capacity(self.len());
for item in self.iter() {
out.push(item?);
@@ -252,40 +249,40 @@
pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
- ArrValue::Lazy(l) => l[idx].evaluate(),
- ArrValue::Eager(e) => Ok(e[idx].clone()),
- ArrValue::Extended(_) => self.get(idx).map(|e| e.unwrap()),
+ Self::Lazy(l) => l[idx].evaluate(),
+ Self::Eager(e) => Ok(e[idx].clone()),
+ Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),
})
}
pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
(0..self.len()).map(move |idx| match self {
- ArrValue::Lazy(l) => l[idx].clone(),
- ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
- ArrValue::Extended(_) => self.get_lazy(idx).unwrap(),
+ Self::Lazy(l) => l[idx].clone(),
+ Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
+ Self::Extended(_) => self.get_lazy(idx).unwrap(),
})
}
pub fn reversed(self) -> Self {
match self {
- ArrValue::Lazy(vec) => {
+ Self::Lazy(vec) => {
let mut out = (&vec as &Vec<_>).clone();
out.reverse();
Self::Lazy(Rc::new(out))
}
- ArrValue::Eager(vec) => {
+ Self::Eager(vec) => {
let mut out = (&vec as &Vec<_>).clone();
out.reverse();
Self::Eager(Rc::new(out))
}
- ArrValue::Extended(b) => ArrValue::Extended(Box::new((b.1.reversed(), b.0.reversed()))),
+ Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),
}
}
- pub fn ptr_eq(a: &ArrValue, b: &ArrValue) -> bool {
+ pub fn ptr_eq(a: &Self, b: &Self) -> bool {
match (a, b) {
- (ArrValue::Lazy(a), ArrValue::Lazy(b)) => Rc::ptr_eq(a, b),
- (ArrValue::Eager(a), ArrValue::Eager(b)) => Rc::ptr_eq(a, b),
+ (Self::Lazy(a), Self::Lazy(b)) => Rc::ptr_eq(a, b),
+ (Self::Eager(a), Self::Eager(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
@@ -359,7 +356,7 @@
self.assert_type(context, ValType::Num)?;
self.unwrap_num()
}
- pub fn value_type(&self) -> ValType {
+ pub const fn value_type(&self) -> ValType {
match self {
Self::Str(..) => ValType::Str,
Self::Num(..) => ValType::Num,
@@ -378,7 +375,7 @@
Self::Null => "null".into(),
Self::Str(s) => s.clone(),
v => manifest_json_ex(
- &v,
+ v,
&ManifestJsonOptions {
padding: "",
mtype: ManifestType::ToString,
@@ -556,7 +553,7 @@
(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(
"primitiveEquals operates on primitive types, got object".into(),
)),
- (a, b) if is_function_like(&a) && is_function_like(&b) => {
+ (a, b) if is_function_like(a) && is_function_like(b) => {
throw!(RuntimeError("cannot test equality of functions".into()))
}
(_, _) => false,
@@ -598,6 +595,6 @@
}
Ok(true)
}
- (a, b) => Ok(primitive_equals(&a, &b)?),
+ (a, b) => Ok(primitive_equals(a, b)?),
}
}
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -68,7 +68,7 @@
IStr(STR_POOL.with(|pool| {
let mut pool = pool.borrow_mut();
if let Some((k, _)) = pool.get_key_value(str) {
- return k.clone();
+ k.clone()
} else {
let rc: Rc<str> = str.into();
pool.insert(rc.clone(), ());
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -133,10 +133,8 @@
union: &[ComplexValType],
) -> std::fmt::Result {
for (i, v) in union.iter().enumerate() {
- let should_add_braces = match v {
- ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union => true,
- _ => false,
- };
+ let should_add_braces =
+ matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);
if i != 0 {
write!(f, " {} ", if is_union { '|' } else { '&' })?;
}