difftreelog
style fix clippy warnings
in: master
36 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -43,7 +43,7 @@
}
n_args.push(None);
let mut success = 1;
- let v = unsafe { (self.cb)(self.ctx, n_args.as_ptr().cast(), &mut success) };
+ let v = unsafe { (self.cb)(self.ctx, n_args.as_ptr().cast(), &raw mut success) };
let v = unsafe { *Box::from_raw(v) };
if success == 1 {
Ok(v)
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -7,6 +7,7 @@
#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
+#[allow(clippy::struct_field_names)]
pub struct TlaOpts {
/// Add top level string argument.
/// Top level arguments will be passed to function before manifestification stage.
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -77,7 +77,7 @@
let i = i?;
if filter(&i)? {
out.push(i);
- };
+ }
}
Ok(Self::eager(out))
}
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -38,7 +38,7 @@
}
impl ArrayLike for SliceArray {
fn len(&self) -> usize {
- ((self.to - self.from + self.step - 1) / self.step) as usize
+ (self.to - self.from).div_ceil(self.step) as usize
}
fn get(&self, index: usize) -> Result<Option<Val>> {
@@ -139,7 +139,7 @@
ArrayThunk::Errored(e) => return Err(e.clone()),
ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
ArrayThunk::Waiting => {}
- };
+ }
let ArrayThunk::Waiting =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
@@ -158,15 +158,6 @@
Ok(Some(new_value))
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- if index >= self.len() {
- return None;
- }
- match &self.cached.borrow()[index] {
- ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
- ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting | ArrayThunk::Pending => {}
- };
-
#[derive(Trace)]
struct ExprArrThunk {
expr: ExprArray,
@@ -183,6 +174,15 @@
}
}
+ if index >= self.len() {
+ return None;
+ }
+ match &self.cached.borrow()[index] {
+ ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+ ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+ ArrayThunk::Waiting | ArrayThunk::Pending => {}
+ }
+
Some(Thunk::new(ExprArrThunk {
expr: self.clone(),
index,
@@ -441,7 +441,7 @@
ArrayThunk::Errored(e) => return Err(e.clone()),
ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
ArrayThunk::Waiting => {}
- };
+ }
let ArrayThunk::Waiting =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
@@ -467,15 +467,6 @@
Ok(Some(new_value))
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- if index >= self.len() {
- return None;
- }
- match &self.cached.borrow()[index] {
- ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
- ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting | ArrayThunk::Pending => {}
- };
-
#[derive(Trace)]
struct MappedArrayThunk<const WITH_INDEX: bool> {
arr: MappedArray<WITH_INDEX>,
@@ -489,6 +480,15 @@
}
}
+ if index >= self.len() {
+ return None;
+ }
+ match &self.cached.borrow()[index] {
+ ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+ ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+ ArrayThunk::Waiting | ArrayThunk::Pending => {}
+ }
+
Some(Thunk::new(MappedArrayThunk {
arr: self.clone(),
index,
crates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -21,7 +21,8 @@
// Visits all nodes, trying to find import statements
#[allow(clippy::too_many_lines)]
pub fn find_imports(expr: &Spanned<Expr>, out: &mut FoundImports) {
- fn in_destruct(dest: &Destruct, #[allow(unused_variables)] out: &mut FoundImports) {
+ #[allow(unused_variables, clippy::needless_pass_by_ref_mut)]
+ fn in_destruct(dest: &Destruct, out: &mut FoundImports) {
match dest {
#[cfg(feature = "exp-destruct")]
Destruct::Array {
@@ -295,8 +296,6 @@
let resolved = (s.import_resolver() as &dyn Any)
.downcast_ref::<ResolvedImportResolver>()
.expect("for async imports, import_resolver should be set to ResolvedImportResolver");
-
- let mut resolved_map = resolved.resolved.borrow_mut();
let mut queue = vec![Job::LoadFile {
path: handler.resolve_from_default(path).await?,
@@ -340,14 +339,17 @@
}
}
Job::ResolveImport { from, import } => {
- if let Some((resolved, expression)) =
- resolved_map.get_mut(&(from.clone(), import.path.clone()))
{
- if import.expression && !*expression {
- *expression = true;
- queue.push(Job::ParseFile(resolved.clone()));
+ let mut resolved_map = resolved.resolved.borrow_mut();
+ if let Some((resolved, expression)) =
+ resolved_map.get_mut(&(from.clone(), import.path.clone()))
+ {
+ if import.expression && !*expression {
+ *expression = true;
+ queue.push(Job::ParseFile(resolved.clone()));
+ }
+ continue;
}
- continue;
}
let resolved = handler.resolve_from(&from, &import.path).await?;
queue.push(Job::LoadFile {
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -1,6 +1,7 @@
+use std::{collections::HashMap, hash::BuildHasher};
+
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BindSpec, Destruct};
-use rustc_hash::FxHashMap;
use crate::{
bail,
@@ -10,11 +11,11 @@
#[allow(clippy::too_many_lines)]
#[allow(unused_variables)]
-pub fn destruct(
+pub fn destruct<H: BuildHasher>(
d: &Destruct,
parent: Thunk<Val>,
fctx: Pending<Context>,
- new_bindings: &mut FxHashMap<IStr, Thunk<Val>>,
+ new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
) -> Result<()> {
match d {
Destruct::Full(v) => {
@@ -159,10 +160,10 @@
Ok(())
}
-pub fn evaluate_dest(
+pub fn evaluate_dest<H: BuildHasher>(
d: &BindSpec,
fctx: Pending<Context>,
- new_bindings: &mut FxHashMap<IStr, Thunk<Val>>,
+ new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
) -> Result<()> {
match d {
BindSpec::Field { into, value } => {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,7 FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,8 Spanned,9};10use jrsonnet_types::ValType;11use rustc_hash::FxHashMap;1213use self::destructure::destruct;14use crate::{15 arr::ArrValue,16 bail,17 destructure::evaluate_dest,18 error::{suggest_object_fields, ErrorKind::*},19 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},20 function::{CallLocation, FuncDesc, FuncVal},21 gc::WithCapacityExt as _,22 in_frame,23 typed::Typed,24 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25 with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,26 ResultExt, SupThis, Unbound, Val,27};28pub mod destructure;29pub mod operator;3031// This is the amount of bytes that need to be left on the stack before increasing the size.32// It must be at least as large as the stack required by any code that does not call33// `ensure_sufficient_stack`.34const RED_ZONE: usize = 100 * 1024; // 100k3536// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then37// on. This flag has performance relevant characteristics. Don't set it too high.38const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3940/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations41/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit42/// from this.43///44/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.45#[inline]46pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {47 stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)48}4950pub fn evaluate_trivial(expr: &Spanned<Expr>) -> Option<Val> {51 fn is_trivial(expr: &Spanned<Expr>) -> bool {52 match &**expr {53 Expr::Str(_)54 | Expr::Num(_)55 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,56 Expr::Arr(a) => a.iter().all(is_trivial),57 _ => false,58 }59 }60 Some(match &**expr {61 Expr::Str(s) => Val::string(s.clone()),62 Expr::Num(n) => {63 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64 }65 Expr::Literal(LiteralType::False) => Val::Bool(false),66 Expr::Literal(LiteralType::True) => Val::Bool(true),67 Expr::Literal(LiteralType::Null) => Val::Null,68 Expr::Arr(n) => {69 if n.iter().any(|e| !is_trivial(e)) {70 return None;71 }72 Val::Arr(ArrValue::eager(73 n.iter()74 .map(evaluate_trivial)75 .map(|e| e.expect("checked trivial"))76 .collect(),77 ))78 }79 _ => return None,80 })81}8283pub fn evaluate_method(84 ctx: Context,85 name: IStr,86 params: ExprParams,87 body: Rc<Spanned<Expr>>,88) -> Val {89 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {90 name,91 ctx,92 params,93 body,94 })))95}9697pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {98 Ok(match field_name {99 FieldName::Fixed(n) => Some(n.clone()),100 FieldName::Dyn(expr) => in_frame(101 CallLocation::new(&expr.span()),102 || "evaluating field name".to_string(),103 || {104 let value = evaluate(ctx, expr)?;105 if matches!(value, Val::Null) {106 Ok(None)107 } else {108 Ok(Some(IStr::from_untyped(value)?))109 }110 },111 )?,112 })113}114115pub fn evaluate_comp(116 ctx: Context,117 specs: &[CompSpec],118 callback: &mut impl FnMut(Context) -> Result<()>,119) -> Result<()> {120 match specs.first() {121 None => callback(ctx)?,122 Some(CompSpec::IfSpec(IfSpecData(cond))) => {123 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {124 evaluate_comp(ctx, &specs[1..], callback)?;125 }126 }127 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {128 Val::Arr(list) => {129 for item in list.iter_lazy() {130 let fctx = Pending::new();131 let mut new_bindings = FxHashMap::with_capacity(var.binds_len());132 destruct(var, item, fctx.clone(), &mut new_bindings)?;133 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);134135 evaluate_comp(ctx, &specs[1..], callback)?;136 }137 }138 #[cfg(feature = "exp-object-iteration")]139 Val::Obj(obj) => {140 for field in obj.fields(141 // TODO: Should there be ability to preserve iteration order?142 #[cfg(feature = "exp-preserve-order")]143 false,144 ) {145 let fctx = Pending::new();146 let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());147 let obj = obj.clone();148 let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![149 Thunk::evaluated(Val::string(field.clone())),150 Thunk!(move || obj.get(field).transpose().expect(151 "field exists, as field name was obtained from object.fields()",152 )),153 ])));154 destruct(var, value, fctx.clone(), &mut new_bindings)?;155 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);156157 evaluate_comp(ctx, &specs[1..], callback)?;158 }159 }160 _ => bail!(InComprehensionCanOnlyIterateOverArray),161 },162 }163 Ok(())164}165166trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}167impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}168169fn evaluate_object_locals(170 fctx: Context,171 locals: Rc<Vec<BindSpec>>,172) -> impl CloneableUnbound<Context> {173 #[derive(Trace, Clone)]174 struct UnboundLocals {175 fctx: Context,176 locals: Rc<Vec<BindSpec>>,177 }178 impl Unbound for UnboundLocals {179 type Bound = Context;180181 fn bind(&self, sup_this: SupThis) -> Result<Context> {182 let fctx = Context::new_future();183 let mut new_bindings =184 FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());185 for b in self.locals.iter() {186 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;187 }188189 let ctx = self.fctx.clone();190191 let ctx = ctx192 .extend_bindings_sup_this(new_bindings, sup_this)193 .into_future(fctx);194195 Ok(ctx)196 }197 }198199 UnboundLocals { fctx, locals }200}201202pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(203 builder: &mut ObjValueBuilder,204 ctx: Context,205 uctx: B,206 field: &FieldMember,207) -> Result<()> {208 let name = evaluate_field_name(ctx, &field.name)?;209 let Some(name) = name else {210 return Ok(());211 };212213 match field {214 FieldMember {215 plus,216 params: None,217 visibility,218 value,219 ..220 } => {221 #[derive(Trace)]222 struct UnboundValue<B: Trace> {223 uctx: B,224 value: Rc<Spanned<Expr>>,225 name: IStr,226 }227 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {228 type Bound = Val;229 fn bind(&self, sup_this: SupThis) -> Result<Val> {230 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())231 }232 }233234 builder235 .field(name.clone())236 .with_add(*plus)237 .with_visibility(*visibility)238 .with_location(value.span())239 .bindable(UnboundValue {240 uctx,241 value: value.clone(),242 name,243 })?;244 }245 FieldMember {246 params: Some(params),247 visibility,248 value,249 ..250 } => {251 #[derive(Trace)]252 struct UnboundMethod<B: Trace> {253 uctx: B,254 value: Rc<Spanned<Expr>>,255 params: ExprParams,256 name: IStr,257 }258 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {259 type Bound = Val;260 fn bind(&self, sup_this: SupThis) -> Result<Val> {261 Ok(evaluate_method(262 self.uctx.bind(sup_this)?,263 self.name.clone(),264 self.params.clone(),265 self.value.clone(),266 ))267 }268 }269270 builder271 .field(name.clone())272 .with_visibility(*visibility)273 .with_location(value.span())274 .bindable(UnboundMethod {275 uctx,276 value: value.clone(),277 params: params.clone(),278 name,279 })?;280 }281 }282 Ok(())283}284285#[allow(clippy::too_many_lines)]286pub fn evaluate_member_list_object(ctx: Context, members: &ObjMembers) -> Result<ObjValue> {287 let mut builder = ObjValueBuilder::new();288 let locals = members.locals.clone();289290 // We have single context for all fields, so we can cache binds291 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));292293 for field in &members.fields {294 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?;295 }296297 if !members.asserts.is_empty() {298 #[derive(Trace)]299 struct ObjectAssert<B: Trace> {300 uctx: B,301 asserts: Rc<Vec<AssertStmt>>,302 }303 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {304 fn run(&self, sup_this: SupThis) -> Result<()> {305 let ctx = self.uctx.bind(sup_this)?;306 for assert in &*self.asserts {307 evaluate_assert(ctx.clone(), &assert)?;308 }309 Ok(())310 }311 }312 builder.assert(ObjectAssert {313 uctx: uctx.clone(),314 asserts: members.asserts.clone(),315 });316 }317318 Ok(builder.build())319}320321pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,324 ObjBody::ObjComp(obj) => {325 let mut builder = ObjValueBuilder::new();326 let locals = obj.locals.clone();327 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {328 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());329330 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)331 })?;332333 builder.build()334 }335 })336}337338pub fn evaluate_apply(339 ctx: Context,340 value: &Spanned<Expr>,341 args: &ArgsDesc,342 loc: CallLocation<'_>,343 tailstrict: bool,344) -> Result<Val> {345 let value = evaluate(ctx.clone(), value)?;346 Ok(match value {347 Val::Func(f) => {348 let body = || f.evaluate(ctx, loc, args, tailstrict);349 if tailstrict {350 body()?351 } else {352 in_frame(loc, || format!("function <{}> call", f.name()), body)?353 }354 }355 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),356 })357}358359pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {360 let value = &assertion.0;361 let msg = &assertion.1;362 let assertion_result = in_frame(363 CallLocation::new(&value.span()),364 || "assertion condition".to_owned(),365 || bool::from_untyped(evaluate(ctx.clone(), value)?),366 )?;367 if !assertion_result {368 in_frame(369 CallLocation::new(&value.span()),370 || "assertion failure".to_owned(),371 || {372 if let Some(msg) = msg {373 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));374 }375 bail!(AssertionFailed(Val::Null.to_string()?));376 },377 )?;378 }379 Ok(())380}381382pub fn evaluate_named_param(ctx: Context, expr: &Spanned<Expr>, name: ParamName) -> Result<Val> {383 match name {384 ParamName::Named(name) => evaluate_named(ctx, expr, name),385 ParamName::Unnamed => evaluate(ctx, expr),386 }387}388389pub fn evaluate_named(ctx: Context, expr: &Spanned<Expr>, name: IStr) -> Result<Val> {390 use Expr::*;391 Ok(match &**expr {392 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),393 _ => evaluate(ctx, expr)?,394 })395}396397#[allow(clippy::too_many_lines)]398pub fn evaluate(ctx: Context, expr: &Spanned<Expr>) -> Result<Val> {399 use Expr::*;400401 if let Some(trivial) = evaluate_trivial(expr) {402 return Ok(trivial);403 }404 let loc = expr.span();405 Ok(match &**expr {406 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),407 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),408 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),409 Literal(LiteralType::True) => Val::Bool(true),410 Literal(LiteralType::False) => Val::Bool(false),411 Literal(LiteralType::Null) => Val::Null,412 Str(v) => Val::string(v.clone()),413 Num(v) => Val::try_num(*v)?,414 // I have tried to remove special behavior from super by implementing standalone-super415 // expresion, but looks like this case still needs special treatment.416 //417 // Note that other jsonnet implementations will fail on `if value in (super)` expression,418 // because the standalone super literal is not supported, that is because in other419 // implementations `in super` treated differently from `in smth_else`.420 BinaryOp(bin)421 if matches!(&*bin.rhs, Expr::Literal(LiteralType::Super))422 && bin.op == BinaryOpType::In =>423 {424 let sup_this = ctx.try_sup_this()?;425 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.426 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.427 if !sup_this.has_super() {428 return Ok(Val::Bool(false));429 }430 let field = evaluate(ctx, &bin.lhs)?;431 Val::Bool(sup_this.field_in_super(field.to_string()?))432 }433 BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,434 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,435 Var(name) => in_frame(436 CallLocation::new(&loc),437 || format!("local <{name}> access"),438 || ctx.binding(name.clone())?.evaluate(),439 )?,440 Index { indexable, parts } => ensure_sufficient_stack(|| {441 let mut parts = parts.iter();442 let mut indexable = if matches!(&***indexable, Expr::Literal(LiteralType::Super)) {443 let part = parts.next().expect("at least part should exist");444 // sup_this existence check might also be skipped here for null-coalesce...445 // But I believe this might cause errors.446 let sup_this = ctx.try_sup_this()?;447 if !sup_this.has_super() {448 #[cfg(feature = "exp-null-coaelse")]449 if part.null_coaelse {450 return Ok(Val::Null);451 }452 bail!(NoSuperFound)453 }454 let name = evaluate(ctx.clone(), &part.value)?;455456 let Val::Str(name) = name else {457 bail!(ValueIndexMustBeTypeGot(458 ValType::Obj,459 ValType::Str,460 name.value_type(),461 ))462 };463464 let name = name.into_flat();465 match sup_this466 .get_super(name.clone())467 .with_description_src(&part.value, || format!("field <{name}> access"))?468 {469 Some(v) => v,470 #[cfg(feature = "exp-null-coaelse")]471 None if part.null_coaelse => return Ok(Val::Null),472 None => {473 let suggestions = suggest_object_fields(474 &sup_this.standalone_super().expect("super exists"),475 name.clone(),476 );477478 bail!(NoSuchField(name, suggestions))479 }480 }481 } else {482 evaluate(ctx.clone(), indexable)?483 };484485 for part in parts {486 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {487 (Val::Obj(v), Val::Str(key)) => match v488 .get(key.clone().into_flat())489 .with_description_src(&part.value, || format!("field <{key}> access"))?490 {491 Some(v) => v,492 #[cfg(feature = "exp-null-coaelse")]493 None if part.null_coaelse => return Ok(Val::Null),494 None => {495 let suggestions = suggest_object_fields(&v, key.clone().into_flat());496497 return Err(Error::from(NoSuchField(498 key.clone().into_flat(),499 suggestions,500 )))501 .with_description_src(&part.value, || format!("field <{key}> access"));502 }503 },504 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(505 ValType::Obj,506 ValType::Str,507 n.value_type(),508 )),509 (Val::Arr(v), Val::Num(n)) => {510 let n = n.get();511 if n.fract() > f64::EPSILON {512 bail!(FractionalIndex)513 }514 if n < 0.0 {515 bail!(ArrayBoundsError(n as isize, v.len()));516 }517 v.get(n as usize)?518 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?519 }520 (Val::Arr(_), Val::Str(n)) => {521 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))522 }523 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(524 ValType::Arr,525 ValType::Num,526 n.value_type(),527 )),528529 (Val::Str(s), Val::Num(n)) => Val::Str({530 let n = n.get();531 if n.fract() > f64::EPSILON {532 bail!(FractionalIndex)533 }534 if n < 0.0 {535 bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));536 }537 let v: IStr = s538 .clone()539 .into_flat()540 .chars()541 .skip(n as usize)542 .take(1)543 .collect::<String>()544 .into();545 if v.is_empty() {546 bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))547 }548 StrValue::Flat(v)549 }),550 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(551 ValType::Str,552 ValType::Num,553 n.value_type(),554 )),555 #[cfg(feature = "exp-null-coaelse")]556 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),557 (v, _) => bail!(CantIndexInto(v.value_type())),558 };559 }560 Ok(indexable)561 })?,562 LocalExpr(bindings, returned) => {563 let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =564 FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());565 let fctx = Context::new_future();566 for b in bindings {567 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;568 }569 let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);570 evaluate(ctx, &returned.clone())?571 }572 Arr(items) => {573 if items.is_empty() {574 Val::Arr(ArrValue::empty())575 } else {576 Val::Arr(ArrValue::expr(ctx, items.clone()))577 }578 }579 ArrComp(expr, comp_specs) => {580 let mut out = Vec::new();581 evaluate_comp(ctx, comp_specs, &mut |ctx| {582 let expr = expr.clone();583 out.push(Thunk!(move || evaluate(ctx, &expr)));584 Ok(())585 })?;586 Val::Arr(ArrValue::lazy(out))587 }588 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),589 ObjExtend(a, b) => evaluate_add_op(590 &evaluate(ctx.clone(), a)?,591 &Val::Obj(evaluate_object(ctx, b)?),592 )?,593 Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {594 evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)595 })?,596 Function(params, body) => {597 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())598 }599 AssertExpr(assert) => {600 evaluate_assert(ctx.clone(), &assert.assert)?;601 evaluate(ctx, &assert.rest)?602 }603 ErrorStmt(e) => in_frame(604 CallLocation::new(&loc),605 || "error statement".to_owned(),606 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),607 )?,608 IfElse(if_else) => {609 if in_frame(610 CallLocation::new(&loc),611 || "if condition".to_owned(),612 || bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.0)?),613 )? {614 evaluate(ctx, &if_else.cond_then)?615 } else {616 match &if_else.cond_else {617 Some(v) => evaluate(ctx, v)?,618 None => Val::Null,619 }620 }621 }622 Slice(slice) => {623 fn parse_idx<T: Typed>(624 loc: CallLocation<'_>,625 ctx: Context,626 expr: Option<&Spanned<Expr>>,627 desc: &'static str,628 ) -> Result<Option<T>> {629 if let Some(value) = expr {630 Ok(in_frame(631 loc,632 || format!("slice {desc}"),633 || <Option<T>>::from_untyped(evaluate(ctx, value)?),634 )?)635 } else {636 Ok(None)637 }638 }639640 let indexable = evaluate(ctx.clone(), &slice.value)?;641 let loc = CallLocation::new(&loc);642643 let start = parse_idx(loc, ctx.clone(), slice.slice.start.as_ref(), "start")?;644 let end = parse_idx(loc, ctx.clone(), slice.slice.end.as_ref(), "end")?;645 let step = parse_idx(loc, ctx, slice.slice.step.as_ref(), "step")?;646647 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?648 }649 Import(kind, path) => {650 let Expr::Str(path) = &***path else {651 bail!("computed imports are not supported")652 };653 let tmp = loc.clone().0;654 with_state(|s| {655 let resolved_path = s.resolve_from(tmp.source_path(), path)?;656 Ok(match kind {657 ImportKind::Normal => in_frame(658 CallLocation::new(&loc),659 || format!("import {:?}", path.clone()),660 || s.import_resolved(resolved_path),661 )?,662 ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),663 ImportKind::Bin => {664 Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))665 }666 }) as Result<Val>667 })?668 }669 })670}1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,7 FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,8 Spanned,9};10use jrsonnet_types::ValType;11use rustc_hash::FxHashMap;1213use self::destructure::destruct;14use crate::{15 arr::ArrValue,16 bail,17 destructure::evaluate_dest,18 error::{suggest_object_fields, ErrorKind::*},19 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},20 function::{CallLocation, FuncDesc, FuncVal},21 gc::WithCapacityExt as _,22 in_frame,23 typed::Typed,24 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25 with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,26 ResultExt, SupThis, Unbound, Val,27};28pub mod destructure;29pub mod operator;3031// This is the amount of bytes that need to be left on the stack before increasing the size.32// It must be at least as large as the stack required by any code that does not call33// `ensure_sufficient_stack`.34const RED_ZONE: usize = 100 * 1024; // 100k3536// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then37// on. This flag has performance relevant characteristics. Don't set it too high.38const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3940/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations41/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit42/// from this.43///44/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.45#[inline]46pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {47 stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)48}4950pub fn evaluate_trivial(expr: &Spanned<Expr>) -> Option<Val> {51 fn is_trivial(expr: &Spanned<Expr>) -> bool {52 match &**expr {53 Expr::Str(_)54 | Expr::Num(_)55 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,56 Expr::Arr(a) => a.iter().all(is_trivial),57 _ => false,58 }59 }60 Some(match &**expr {61 Expr::Str(s) => Val::string(s.clone()),62 Expr::Num(n) => {63 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64 }65 Expr::Literal(LiteralType::False) => Val::Bool(false),66 Expr::Literal(LiteralType::True) => Val::Bool(true),67 Expr::Literal(LiteralType::Null) => Val::Null,68 Expr::Arr(n) => {69 if n.iter().any(|e| !is_trivial(e)) {70 return None;71 }72 Val::Arr(ArrValue::eager(73 n.iter()74 .map(evaluate_trivial)75 .map(|e| e.expect("checked trivial"))76 .collect(),77 ))78 }79 _ => return None,80 })81}8283pub fn evaluate_method(84 ctx: Context,85 name: IStr,86 params: ExprParams,87 body: Rc<Spanned<Expr>>,88) -> Val {89 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {90 name,91 ctx,92 params,93 body,94 })))95}9697pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {98 Ok(match field_name {99 FieldName::Fixed(n) => Some(n.clone()),100 FieldName::Dyn(expr) => in_frame(101 CallLocation::new(&expr.span()),102 || "evaluating field name".to_string(),103 || {104 let value = evaluate(ctx, expr)?;105 if matches!(value, Val::Null) {106 Ok(None)107 } else {108 Ok(Some(IStr::from_untyped(value)?))109 }110 },111 )?,112 })113}114115pub fn evaluate_comp(116 ctx: Context,117 specs: &[CompSpec],118 callback: &mut impl FnMut(Context) -> Result<()>,119) -> Result<()> {120 match specs.first() {121 None => callback(ctx)?,122 Some(CompSpec::IfSpec(IfSpecData(cond))) => {123 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {124 evaluate_comp(ctx, &specs[1..], callback)?;125 }126 }127 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {128 Val::Arr(list) => {129 for item in list.iter_lazy() {130 let fctx = Pending::new();131 let mut new_bindings = FxHashMap::with_capacity(var.binds_len());132 destruct(var, item, fctx.clone(), &mut new_bindings)?;133 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);134135 evaluate_comp(ctx, &specs[1..], callback)?;136 }137 }138 #[cfg(feature = "exp-object-iteration")]139 Val::Obj(obj) => {140 for field in obj.fields(141 // TODO: Should there be ability to preserve iteration order?142 #[cfg(feature = "exp-preserve-order")]143 false,144 ) {145 let fctx = Pending::new();146 let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());147 let obj = obj.clone();148 let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![149 Thunk::evaluated(Val::string(field.clone())),150 Thunk!(move || obj.get(field).transpose().expect(151 "field exists, as field name was obtained from object.fields()",152 )),153 ])));154 destruct(var, value, fctx.clone(), &mut new_bindings)?;155 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);156157 evaluate_comp(ctx, &specs[1..], callback)?;158 }159 }160 _ => bail!(InComprehensionCanOnlyIterateOverArray),161 },162 }163 Ok(())164}165166trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}167impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}168169fn evaluate_object_locals(170 fctx: Context,171 locals: Rc<Vec<BindSpec>>,172) -> impl CloneableUnbound<Context> {173 #[derive(Trace, Clone)]174 struct UnboundLocals {175 fctx: Context,176 locals: Rc<Vec<BindSpec>>,177 }178 impl Unbound for UnboundLocals {179 type Bound = Context;180181 fn bind(&self, sup_this: SupThis) -> Result<Context> {182 let fctx = Context::new_future();183 let mut new_bindings =184 FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());185 for b in self.locals.iter() {186 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;187 }188189 let ctx = self.fctx.clone();190191 let ctx = ctx192 .extend_bindings_sup_this(new_bindings, sup_this)193 .into_future(fctx);194195 Ok(ctx)196 }197 }198199 UnboundLocals { fctx, locals }200}201202pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(203 builder: &mut ObjValueBuilder,204 ctx: Context,205 uctx: B,206 field: &FieldMember,207) -> Result<()> {208 let name = evaluate_field_name(ctx, &field.name)?;209 let Some(name) = name else {210 return Ok(());211 };212213 match field {214 FieldMember {215 plus,216 params: None,217 visibility,218 value,219 ..220 } => {221 #[derive(Trace)]222 struct UnboundValue<B: Trace> {223 uctx: B,224 value: Rc<Spanned<Expr>>,225 name: IStr,226 }227 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {228 type Bound = Val;229 fn bind(&self, sup_this: SupThis) -> Result<Val> {230 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())231 }232 }233234 builder235 .field(name.clone())236 .with_add(*plus)237 .with_visibility(*visibility)238 .with_location(value.span())239 .bindable(UnboundValue {240 uctx,241 value: value.clone(),242 name,243 })?;244 }245 FieldMember {246 params: Some(params),247 visibility,248 value,249 ..250 } => {251 #[derive(Trace)]252 struct UnboundMethod<B: Trace> {253 uctx: B,254 value: Rc<Spanned<Expr>>,255 params: ExprParams,256 name: IStr,257 }258 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {259 type Bound = Val;260 fn bind(&self, sup_this: SupThis) -> Result<Val> {261 Ok(evaluate_method(262 self.uctx.bind(sup_this)?,263 self.name.clone(),264 self.params.clone(),265 self.value.clone(),266 ))267 }268 }269270 builder271 .field(name.clone())272 .with_visibility(*visibility)273 .with_location(value.span())274 .bindable(UnboundMethod {275 uctx,276 value: value.clone(),277 params: params.clone(),278 name,279 })?;280 }281 }282 Ok(())283}284285#[allow(clippy::too_many_lines)]286pub fn evaluate_member_list_object(ctx: Context, members: &ObjMembers) -> Result<ObjValue> {287 let mut builder = ObjValueBuilder::new();288 let locals = members.locals.clone();289290 // We have single context for all fields, so we can cache binds291 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));292293 for field in &members.fields {294 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;295 }296297 if !members.asserts.is_empty() {298 #[derive(Trace)]299 struct ObjectAssert<B: Trace> {300 uctx: B,301 asserts: Rc<Vec<AssertStmt>>,302 }303 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {304 fn run(&self, sup_this: SupThis) -> Result<()> {305 let ctx = self.uctx.bind(sup_this)?;306 for assert in &*self.asserts {307 evaluate_assert(ctx.clone(), assert)?;308 }309 Ok(())310 }311 }312 builder.assert(ObjectAssert {313 uctx,314 asserts: members.asserts.clone(),315 });316 }317318 Ok(builder.build())319}320321pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,324 ObjBody::ObjComp(obj) => {325 let mut builder = ObjValueBuilder::new();326 let locals = obj.locals.clone();327 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {328 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());329330 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)331 })?;332333 builder.build()334 }335 })336}337338pub fn evaluate_apply(339 ctx: Context,340 value: &Spanned<Expr>,341 args: &ArgsDesc,342 loc: CallLocation<'_>,343 tailstrict: bool,344) -> Result<Val> {345 let value = evaluate(ctx.clone(), value)?;346 Ok(match value {347 Val::Func(f) => {348 let body = || f.evaluate(ctx, loc, args, tailstrict);349 if tailstrict {350 body()?351 } else {352 in_frame(loc, || format!("function <{}> call", f.name()), body)?353 }354 }355 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),356 })357}358359pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {360 let value = &assertion.0;361 let msg = &assertion.1;362 let assertion_result = in_frame(363 CallLocation::new(&value.span()),364 || "assertion condition".to_owned(),365 || bool::from_untyped(evaluate(ctx.clone(), value)?),366 )?;367 if !assertion_result {368 in_frame(369 CallLocation::new(&value.span()),370 || "assertion failure".to_owned(),371 || {372 if let Some(msg) = msg {373 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));374 }375 bail!(AssertionFailed(Val::Null.to_string()?));376 },377 )?;378 }379 Ok(())380}381382pub fn evaluate_named_param(ctx: Context, expr: &Spanned<Expr>, name: ParamName) -> Result<Val> {383 match name {384 ParamName::Named(name) => evaluate_named(ctx, expr, name),385 ParamName::Unnamed => evaluate(ctx, expr),386 }387}388389pub fn evaluate_named(ctx: Context, expr: &Spanned<Expr>, name: IStr) -> Result<Val> {390 use Expr::*;391 Ok(match &**expr {392 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),393 _ => evaluate(ctx, expr)?,394 })395}396397#[allow(clippy::too_many_lines)]398pub fn evaluate(ctx: Context, expr: &Spanned<Expr>) -> Result<Val> {399 use Expr::*;400401 if let Some(trivial) = evaluate_trivial(expr) {402 return Ok(trivial);403 }404 let loc = expr.span();405 Ok(match &**expr {406 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),407 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),408 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),409 Literal(LiteralType::True) => Val::Bool(true),410 Literal(LiteralType::False) => Val::Bool(false),411 Literal(LiteralType::Null) => Val::Null,412 Str(v) => Val::string(v.clone()),413 Num(v) => Val::try_num(*v)?,414 // I have tried to remove special behavior from super by implementing standalone-super415 // expresion, but looks like this case still needs special treatment.416 //417 // Note that other jsonnet implementations will fail on `if value in (super)` expression,418 // because the standalone super literal is not supported, that is because in other419 // implementations `in super` treated differently from `in smth_else`.420 BinaryOp(bin)421 if matches!(&*bin.rhs, Expr::Literal(LiteralType::Super))422 && bin.op == BinaryOpType::In =>423 {424 let sup_this = ctx.try_sup_this()?;425 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.426 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.427 if !sup_this.has_super() {428 return Ok(Val::Bool(false));429 }430 let field = evaluate(ctx, &bin.lhs)?;431 Val::Bool(sup_this.field_in_super(field.to_string()?))432 }433 BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,434 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,435 Var(name) => in_frame(436 CallLocation::new(&loc),437 || format!("local <{name}> access"),438 || ctx.binding(name.clone())?.evaluate(),439 )?,440 Index { indexable, parts } => ensure_sufficient_stack(|| {441 let mut parts = parts.iter();442 let mut indexable = if matches!(&***indexable, Expr::Literal(LiteralType::Super)) {443 let part = parts.next().expect("at least part should exist");444 // sup_this existence check might also be skipped here for null-coalesce...445 // But I believe this might cause errors.446 let sup_this = ctx.try_sup_this()?;447 if !sup_this.has_super() {448 #[cfg(feature = "exp-null-coaelse")]449 if part.null_coaelse {450 return Ok(Val::Null);451 }452 bail!(NoSuperFound)453 }454 let name = evaluate(ctx.clone(), &part.value)?;455456 let Val::Str(name) = name else {457 bail!(ValueIndexMustBeTypeGot(458 ValType::Obj,459 ValType::Str,460 name.value_type(),461 ))462 };463464 let name = name.into_flat();465 match sup_this466 .get_super(name.clone())467 .with_description_src(&part.value, || format!("field <{name}> access"))?468 {469 Some(v) => v,470 #[cfg(feature = "exp-null-coaelse")]471 None if part.null_coaelse => return Ok(Val::Null),472 None => {473 let suggestions = suggest_object_fields(474 &sup_this.standalone_super().expect("super exists"),475 name.clone(),476 );477478 bail!(NoSuchField(name, suggestions))479 }480 }481 } else {482 evaluate(ctx.clone(), indexable)?483 };484485 for part in parts {486 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {487 (Val::Obj(v), Val::Str(key)) => match v488 .get(key.clone().into_flat())489 .with_description_src(&part.value, || format!("field <{key}> access"))?490 {491 Some(v) => v,492 #[cfg(feature = "exp-null-coaelse")]493 None if part.null_coaelse => return Ok(Val::Null),494 None => {495 let suggestions = suggest_object_fields(&v, key.clone().into_flat());496497 return Err(Error::from(NoSuchField(498 key.clone().into_flat(),499 suggestions,500 )))501 .with_description_src(&part.value, || format!("field <{key}> access"));502 }503 },504 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(505 ValType::Obj,506 ValType::Str,507 n.value_type(),508 )),509 (Val::Arr(v), Val::Num(n)) => {510 let n = n.get();511 if n.fract() > f64::EPSILON {512 bail!(FractionalIndex)513 }514 if n < 0.0 {515 bail!(ArrayBoundsError(n as isize, v.len()));516 }517 v.get(n as usize)?518 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?519 }520 (Val::Arr(_), Val::Str(n)) => {521 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))522 }523 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(524 ValType::Arr,525 ValType::Num,526 n.value_type(),527 )),528529 (Val::Str(s), Val::Num(n)) => Val::Str({530 let n = n.get();531 if n.fract() > f64::EPSILON {532 bail!(FractionalIndex)533 }534 if n < 0.0 {535 bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));536 }537 let v: IStr = s538 .clone()539 .into_flat()540 .chars()541 .skip(n as usize)542 .take(1)543 .collect::<String>()544 .into();545 if v.is_empty() {546 bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))547 }548 StrValue::Flat(v)549 }),550 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(551 ValType::Str,552 ValType::Num,553 n.value_type(),554 )),555 #[cfg(feature = "exp-null-coaelse")]556 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),557 (v, _) => bail!(CantIndexInto(v.value_type())),558 };559 }560 Ok(indexable)561 })?,562 LocalExpr(bindings, returned) => {563 let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =564 FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());565 let fctx = Context::new_future();566 for b in bindings {567 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;568 }569 let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);570 evaluate(ctx, returned)?571 }572 Arr(items) => {573 if items.is_empty() {574 Val::Arr(ArrValue::empty())575 } else {576 Val::Arr(ArrValue::expr(ctx, items.clone()))577 }578 }579 ArrComp(expr, comp_specs) => {580 let mut out = Vec::new();581 evaluate_comp(ctx, comp_specs, &mut |ctx| {582 let expr = expr.clone();583 out.push(Thunk!(move || evaluate(ctx, &expr)));584 Ok(())585 })?;586 Val::Arr(ArrValue::lazy(out))587 }588 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),589 ObjExtend(a, b) => evaluate_add_op(590 &evaluate(ctx.clone(), a)?,591 &Val::Obj(evaluate_object(ctx, b)?),592 )?,593 Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {594 evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)595 })?,596 Function(params, body) => {597 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())598 }599 AssertExpr(assert) => {600 evaluate_assert(ctx.clone(), &assert.assert)?;601 evaluate(ctx, &assert.rest)?602 }603 ErrorStmt(e) => in_frame(604 CallLocation::new(&loc),605 || "error statement".to_owned(),606 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),607 )?,608 IfElse(if_else) => {609 if in_frame(610 CallLocation::new(&loc),611 || "if condition".to_owned(),612 || bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.0)?),613 )? {614 evaluate(ctx, &if_else.cond_then)?615 } else {616 match &if_else.cond_else {617 Some(v) => evaluate(ctx, v)?,618 None => Val::Null,619 }620 }621 }622 Slice(slice) => {623 fn parse_idx<T: Typed>(624 loc: CallLocation<'_>,625 ctx: Context,626 expr: Option<&Spanned<Expr>>,627 desc: &'static str,628 ) -> Result<Option<T>> {629 if let Some(value) = expr {630 Ok(in_frame(631 loc,632 || format!("slice {desc}"),633 || <Option<T>>::from_untyped(evaluate(ctx, value)?),634 )?)635 } else {636 Ok(None)637 }638 }639640 let indexable = evaluate(ctx.clone(), &slice.value)?;641 let loc = CallLocation::new(&loc);642643 let start = parse_idx(loc, ctx.clone(), slice.slice.start.as_ref(), "start")?;644 let end = parse_idx(loc, ctx.clone(), slice.slice.end.as_ref(), "end")?;645 let step = parse_idx(loc, ctx, slice.slice.step.as_ref(), "step")?;646647 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?648 }649 Import(kind, path) => {650 let Expr::Str(path) = &***path else {651 bail!("computed imports are not supported")652 };653 let tmp = loc.clone().0;654 with_state(|s| {655 let resolved_path = s.resolve_from(tmp.source_path(), path)?;656 Ok(match kind {657 ImportKind::Normal => in_frame(658 CallLocation::new(&loc),659 || format!("import {:?}", path.clone()),660 || s.import_resolved(resolved_path),661 )?,662 ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),663 ImportKind::Bin => {664 Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))665 }666 }) as Result<Val>667 })?668 }669 })670}crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -95,9 +95,9 @@
// string format
(Str(_), _) => false,
- (_, Num(b)) => return **b == 0.,
+ (_, Num(b)) => **b == 0.,
#[cfg(feature = "exp-bigint")]
- (_, BigInt(b)) => return **b == num_bigint::BigInt::ZERO,
+ (_, BigInt(b)) => **b == num_bigint::BigInt::ZERO,
// something else
_ => false,
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -239,7 +239,7 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- for (name, _) in self {
+ for name in self.keys() {
handler(name);
}
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,5 +1,3 @@
-use std::mem::replace;
-
use jrsonnet_parser::{
function::{FunctionSignature, ParamName},
ExprParams,
@@ -87,7 +85,7 @@
}
destruct(
- &into,
+ into,
{
let ctx = fctx.clone();
let name = into.name();
@@ -97,7 +95,7 @@
fctx.clone(),
&mut defaults,
)?;
- if !into.name().is_anonymous() {
+ if into.name().is_named() {
filled_named += 1;
} else {
filled_positionals += 1;
@@ -165,7 +163,7 @@
.iter()
.position(|p| p.name() == name)
.ok_or_else(|| UnknownFunctionParameter(name.clone()))?;
- if replace(&mut passed_args[id], Some(arg)).is_some() {
+ if passed_args[id].replace(arg).is_some() {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_args += 1;
@@ -230,7 +228,7 @@
let params = params.clone();
Thunk!(move || Err(FunctionParameterNotBoundInCall(
param_name,
- params.signature.clone()
+ params.signature
)
.into()))
},
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -1,3 +1,8 @@
+#![allow(
+ clippy::implicit_hasher,
+ reason = "those methods exist exactly because with_capacity is only present for default BuildHasher"
+)]
+
/// Macros to help deal with Gc
use jrsonnet_gcmodule::Trace;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
@@ -8,20 +13,20 @@
}
impl<V> WithCapacityExt for FxHashSet<V> {
fn with_capacity(capacity: usize) -> Self {
- Self::with_capacity_and_hasher(capacity, FxBuildHasher::default())
+ Self::with_capacity_and_hasher(capacity, FxBuildHasher)
}
fn new() -> Self {
- Self::with_hasher(FxBuildHasher::default())
+ Self::with_hasher(FxBuildHasher)
}
}
impl<K, V> WithCapacityExt for FxHashMap<K, V> {
fn with_capacity(capacity: usize) -> Self {
- Self::with_capacity_and_hasher(capacity, FxBuildHasher::default())
+ Self::with_capacity_and_hasher(capacity, FxBuildHasher)
}
fn new() -> Self {
- Self::with_hasher(FxBuildHasher::default())
+ Self::with_hasher(FxBuildHasher)
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -367,7 +367,7 @@
let res = evaluate(self.create_default_context(file_name), &parsed);
let mut file_cache = self.file_cache();
- let mut file = file_cache.entry(path.clone());
+ let mut file = file_cache.entry(path);
let Entry::Occupied(file) = &mut file else {
unreachable!("this file was just here")
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -240,7 +240,7 @@
}
ToString if i != 0 => buf.push(' '),
Minify | ToString => {}
- };
+ }
in_description_frame(
|| format!("elem <{i}> manifestification"),
@@ -335,7 +335,7 @@
buf.push('}');
}
Val::Func(_) => bail!("tried to manifest function"),
- };
+ }
Ok(())
}
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -16,7 +16,7 @@
impl LayeredHashMap {
pub fn iter_keys(self, mut handler: impl FnMut(IStr)) {
- for (k, _) in &self.0.current {
+ for k in self.0.current.keys() {
handler(k.clone());
}
if let Some(parent) = self.0.parent.clone() {
@@ -47,11 +47,7 @@
pub fn contains_key(&self, key: &IStr) -> bool {
(self.0).current.contains_key(key)
- || self
- .0
- .parent
- .as_ref()
- .map_or(false, |p| p.contains_key(key))
+ || self.0.parent.as_ref().is_some_and(|p| p.contains_key(key))
}
}
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -1,6 +1,7 @@
use std::{
any::Any,
cell::{Cell, RefCell},
+ clone::Clone,
collections::hash_map::Entry,
fmt::{self, Debug},
hash::{Hash, Hasher},
@@ -272,7 +273,7 @@
impl ObjValue {
pub fn empty() -> Self {
- EMPTY_OBJ.with(|v| v.clone())
+ EMPTY_OBJ.with(Clone::clone)
}
pub fn is_empty(&self) -> bool {
self.0.cores.is_empty() || self.len() == 0
@@ -306,14 +307,13 @@
return Ok(GetFor::NotFound);
}
let v = self.this.get_idx(key, self.sup)?;
- Ok(v.map_or(GetFor::NotFound, |v| GetFor::Final(v)))
+ Ok(v.map_or(GetFor::NotFound, GetFor::Final))
}
fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
- match self.this.field_visibility_idx(field, self.sup) {
- Some(c) => FieldVisibility::Found(c),
- None => FieldVisibility::NotFound,
- }
+ self.this
+ .field_visibility_idx(field, self.sup)
+ .map_or(FieldVisibility::NotFound, FieldVisibility::Found)
}
fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
crates/jrsonnet-evaluator/src/obj/oop.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/oop.rs
+++ b/crates/jrsonnet-evaluator/src/obj/oop.rs
@@ -1,4 +1,4 @@
-use std::cell::Cell;
+use std::cell::{Cell, RefCell};
use std::ops::ControlFlow;
use std::{fmt, mem};
@@ -105,7 +105,7 @@
fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {
if let Some(assertion) = &self.assertion {
- assertion.0.run(sup_this.clone())?;
+ assertion.0.run(sup_this)?;
}
Ok(())
}
@@ -196,7 +196,7 @@
ObjValue(Cc::new(ObjValueInner {
cores: self.sup,
assertions_ran: Cell::new(false),
- value_cache: Default::default(),
+ value_cache: RefCell::default(),
}))
}
}
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -17,6 +17,7 @@
}
}
#[cfg(not(nightly))]
+#[allow(dead_code)]
type NightlyLocalKey<T> = std::thread::LocalKey<T>;
#[cfg(nightly)]
@@ -60,7 +61,7 @@
pub struct StackDepthGuard(PhantomData<()>);
impl Drop for StackDepthGuard {
fn drop(&mut self) {
- STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1))
+ STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1));
}
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -297,6 +297,7 @@
const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
#[inline]
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_integer(
out: &mut String,
neg: bool,
@@ -330,7 +331,7 @@
let pref_len = zero_prefix.len() as u16;
let zp2 = zp
- .saturating_sub(if !prefix_in_padding { pref_len } else { 0 })
+ .saturating_sub(if prefix_in_padding { 0 } else { pref_len })
.max(precision)
.saturating_sub(if prefix_in_padding { pref_len } else { 0 } + digits.len() as u16);
@@ -369,6 +370,7 @@
out, neg, iv, padding, precision, blank, sign, 10, "", false, false,
);
}
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_octal(
out: &mut String,
neg: bool,
@@ -439,8 +441,8 @@
// Note that it can also be equal to 10**prec and we'll need to carry
// over to the wholes. We operate on the absolute numbers, so that we
// don't have trouble with the rounding direction.
- let denominator = 10.0f64.powi(precision as i32);
- let numerator = n.abs() * denominator + 0.5;
+ let denominator = 10.0f64.powi(i32::from(precision));
+ let numerator = n.abs().mul_add(denominator, 0.5);
let whole = (numerator / denominator).floor();
let frac = numerator.floor() % denominator;
@@ -611,7 +613,7 @@
} else {
value.abs().log10().floor()
};
- if exponent < -4.0 || exponent >= fpprec as f64 {
+ if exponent < -4.0 || exponent >= f64::from(fpprec) {
render_float_sci(
&mut tmp_out,
value,
@@ -661,7 +663,7 @@
}
},
ConvTypeV::Percent => tmp_out.push('%'),
- };
+ }
let padding = width.saturating_sub(tmp_out.len() as u16);
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -1,13 +1,14 @@
+use std::{collections::HashMap, hash::BuildHasher};
+
use jrsonnet_interner::IStr;
use jrsonnet_parser::Source;
-use rustc_hash::FxHashMap;
use crate::{
function::{CallLocation, TlaArg},
in_description_frame, with_state, Result, Val,
};
-pub fn apply_tla(args: &FxHashMap<IStr, TlaArg>, val: Val) -> Result<Val> {
+pub fn apply_tla<H: BuildHasher>(args: &HashMap<IStr, TlaArg, H>, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
in_description_frame(
|| "during TLA call".to_owned(),
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -462,7 +462,7 @@
};
if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
return Ok(bytes.0.as_slice().into());
- };
+ }
<Self as Typed>::TYPE.check(&value)?;
// Any::downcast_ref::<ByteArray>(&a);
let mut out = Vec::with_capacity(a.len());
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -65,7 +65,7 @@
MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),
MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
MemoizedClusureThunkInner::Waiting { .. } => (),
- };
+ }
let MemoizedClusureThunkInner::Waiting { env, closure } = replace(
&mut *self.0.borrow_mut(),
MemoizedClusureThunkInner::Pending,
@@ -288,14 +288,11 @@
Self::Str(s) => {
let mut computed_len = None;
let mut get_len = || {
- computed_len.map_or_else(
- || {
- let len = s.chars().count();
- let _ = computed_len.insert(len);
- len
- },
- |len| len,
- )
+ computed_len.unwrap_or_else(|| {
+ let len = s.chars().count();
+ let _ = computed_len.insert(len);
+ len
+ })
};
let mut get_idx = |pos: Option<i32>, default| {
match pos {
@@ -446,7 +443,7 @@
pub const fn get(&self) -> f64 {
self.0
}
- pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {
+ pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {
if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
bail!("numberic value outside of safe integer range for bitwise operation");
}
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -227,9 +227,11 @@
type PoolMap = HashMap<Inner, (), FxBuildHasher>;
thread_local! {
- static POOL: RefCell<PoolMap> = RefCell::new(HashMap::with_capacity_and_hasher(200, FxBuildHasher::default()));
+ static POOL: RefCell<PoolMap> = RefCell::new(HashMap::with_capacity_and_hasher(200, FxBuildHasher));
}
+/// Utils for embedding jrsonnet in non-rust.
+///
/// Jrsonnet golang bindings require that it is possible to move jsonnet
/// VM between OS threads, and this is not possible due to usage of
/// `thread_local`. Instead, there is two methods added, one should be
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -127,6 +127,7 @@
Default(Expr),
}
+#[allow(clippy::large_enum_variant, reason = "this macro is not that hot for it to matter")]
enum ArgInfo {
Normal {
ty: Box<Type>,
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -166,6 +166,10 @@
pub fn len(&self) -> usize {
self.exprs.len()
}
+ pub fn is_empty(&self) -> bool {
+ self.exprs.is_empty()
+ }
+
pub fn binds_len(&self) -> usize {
self.binds_len
}
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -98,9 +98,9 @@
for c in str.chars() {
match func(Either2::A(c.to_string()))? {
Val::Str(o) => write!(out, "{o}").unwrap(),
- Val::Null => continue,
+ Val::Null => {},
_ => bail!("in std.join all items should be strings"),
- };
+ }
}
Ok(IndexableVal::Str(out.into()))
}
@@ -114,9 +114,9 @@
out.push(oe?);
}
}
- Val::Null => continue,
+ Val::Null => {},
_ => bail!("in std.join all items should be arrays"),
- };
+ }
}
Ok(IndexableVal::Arr(out.into()))
}
@@ -205,7 +205,6 @@
out.push(item?);
}
} else if matches!(item, Val::Null) {
- continue;
} else {
bail!("in std.join all items should be arrays");
}
@@ -226,7 +225,6 @@
first = false;
write!(out, "{item}").unwrap();
} else if matches!(item, Val::Null) {
- continue;
} else {
bail!("in std.join all items should be strings");
}
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -46,7 +46,7 @@
};
if arr.is_empty() {
bail!("JSONML value should have tag (array length should be >=1)");
- };
+ }
let tag = String::from_untyped(
arr.get(0)
.description("getting JSONML tag")?
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -90,6 +90,7 @@
RESERVED.iter().any(|k| key.eq_ignore_ascii_case(k))
}
+ #[allow(clippy::if_same_then_else)]
// Check for unsafe characters
if !key
.chars()
@@ -98,7 +99,7 @@
return false;
}
// Check for reserved words
- if is_reserved(key) {
+ else if is_reserved(key) {
return false;
}
// Check for timestamp values. Since spaces and colons are already forbidden,
@@ -107,7 +108,7 @@
// - all characters match [0-9\-]
// - has exactly 2 dashes
// are considered dates.
- if key.chars().all(|v| matches!(v, '0'..='9' | '-')) && count_char(key, '-') == 2 {
+ else if key.chars().all(|v| matches!(v, '0'..='9' | '-')) && count_char(key, '-') == 2 {
return false;
}
// Check for integers. Keys that meet all of the following:
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -172,7 +172,7 @@
let Some(patch) = patch.as_obj() else {
return Ok(patch);
};
- let target = target.as_obj().unwrap_or_else(|| ObjValue::empty());
+ let target = target.as_obj().unwrap_or_else(ObjValue::empty);
let target_fields = target
.fields(
// FIXME: Makes no sense to preserve order for BTreeSet, it would be better to use IndexSet here?
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -21,7 +21,7 @@
let x = keyF(x)?;
while low < high {
- let middle = (high + low) / 2;
+ let middle = usize::midpoint(high, low);
let comp = keyF(arr.get_lazy(middle).expect("in bounds"))?;
match evaluate_compare_op(&comp, &x, BinaryOpType::Lt)? {
Ordering::Less => low = middle + 1,
@@ -66,7 +66,7 @@
bv = b.next();
bk = bv.map(keyF).transpose()?;
}
- };
+ }
}
Ok(ArrValue::lazy(out))
}
@@ -106,7 +106,7 @@
bv = b.next();
bk = bv.map(keyF).transpose()?;
}
- };
+ }
}
while let Some(_ac) = &ak {
// In a, but not in b
@@ -154,7 +154,7 @@
bv = b.next();
bk = bv.clone().map(keyF).transpose()?;
}
- };
+ }
}
// a.len() > b.len()
while let Some(_ac) = &ak {
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -66,7 +66,7 @@
return Err(err);
}
}
- };
+ }
Ok(values)
}
@@ -107,7 +107,7 @@
return Err(err);
}
}
- };
+ }
Ok(vk.into_iter().map(|v| v.0).collect())
}
@@ -204,7 +204,7 @@
}
}
-fn eval_keyf(val: Val, key_f: &Option<FuncVal>) -> Result<Val> {
+fn eval_keyf(val: Val, key_f: Option<&FuncVal>) -> Result<Val> {
if let Some(key_f) = key_f {
key_f.evaluate_simple(&(val,), false)
} else {
@@ -212,13 +212,13 @@
}
}
-fn array_top1(arr: ArrValue, key_f: Option<FuncVal>, ordering: Ordering) -> Result<Val> {
+fn array_top1(arr: ArrValue, key_f: Option<&FuncVal>, ordering: Ordering) -> Result<Val> {
let mut iter = arr.iter();
let mut min = iter.next().expect("not empty")?;
- let mut min_key = eval_keyf(min.clone(), &key_f)?;
+ let mut min_key = eval_keyf(min.clone(), key_f)?;
for item in iter {
let cur = item?;
- let cur_key = eval_keyf(cur.clone(), &key_f)?;
+ let cur_key = eval_keyf(cur.clone(), key_f)?;
if evaluate_compare_op(&cur_key, &min_key, BinaryOpType::Lt)? == ordering {
min = cur;
min_key = cur_key;
@@ -236,7 +236,7 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF, Ordering::Less)
+ array_top1(arr, keyF.as_ref(), Ordering::Less)
}
#[builtin]
pub fn builtin_max_array(
@@ -247,5 +247,5 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF, Ordering::Greater)
+ array_top1(arr, keyF.as_ref(), Ordering::Greater)
}
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -53,7 +53,7 @@
#[builtin]
pub fn builtin_equals_ignore_case(str1: String, str2: String) -> bool {
- str1.to_ascii_lowercase() == str2.to_ascii_lowercase()
+ str1.eq_ignore_ascii_case(&str2)
}
#[builtin]
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -133,7 +133,7 @@
Self::Sum(v) => write_union(f, false, v.iter())?,
Self::SumRef(v) => write_union(f, false, v.iter().copied())?,
Self::Lazy(lazy) => write!(f, "Lazy<{lazy}>")?,
- };
+ }
Ok(())
}
}
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -57,12 +57,13 @@
#[builtin]
fn param_names(fun: FuncVal) -> Vec<String> {
fun.params()
- .into_iter()
+ .iter()
.map(|v| v.name().as_str().unwrap_or("<unnamed>").to_owned())
.collect()
}
#[derive(Trace)]
+#[allow(dead_code)]
pub struct ContextInitializer;
impl ContextInitializerT for ContextInitializer {
fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -23,29 +23,29 @@
// C++ test suite
std_context.add_ext_str("var1".into(), "test".into());
std_context
- .add_ext_code("var2".into(), "{x:1,y:2}")
+ .add_ext_code("var2", "{x:1,y:2}")
.expect("code is valid");
// Golang test suite
std_context
- .add_ext_code("codeVar".into(), "3+3")
+ .add_ext_code("codeVar", "3+3")
.expect("code is valid");
std_context.add_ext_str("stringVar".into(), "2 + 2".into());
std_context
.add_ext_code(
- "selfRecursiveVar".into(),
+ "selfRecursiveVar",
r#"[42, std.extVar("selfRecursiveVar")[0] + 1]"#,
)
.expect("code is valid");
std_context
.add_ext_code(
- "mutuallyRecursiveVar1".into(),
+ "mutuallyRecursiveVar1",
r#"[42, std.extVar("mutuallyRecursiveVar2")[0] + 1]"#,
)
.expect("code is valid");
std_context
.add_ext_code(
- "mutuallyRecursiveVar2".into(),
+ "mutuallyRecursiveVar2",
r#"[42, std.extVar("mutuallyRecursiveVar1")[0] + 1]"#,
)
.expect("code is valid");
@@ -203,9 +203,9 @@
let root = root_tests.join(root_dir);
let root_override = root_tests.join(format!("{root_dir}_golden_override"));
- for entry in fs::read_dir(&root).map_err(|e| io::Error::new(ErrorKind::Other, format!("failed to enumerate cpp_test_suite dir (Note: it needs to be cloned from C++ jsonnet repo for this test): {e}")))? {
+ for entry in fs::read_dir(&root).map_err(|e| io::Error::other(format!("failed to enumerate cpp_test_suite dir (Note: it needs to be cloned from C++ jsonnet repo for this test): {e}")))? {
let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
+ if entry.path().extension().is_none_or(|e| e != "jsonnet") {
continue;
}
@@ -213,7 +213,7 @@
.path()
.file_name()
.and_then(|v| v.to_str())
- .map_or(false, |v| SKIPPED.contains(&v))
+ .is_some_and(|v| SKIPPED.contains(&v))
{
continue;
}
@@ -227,7 +227,7 @@
golden_path2.set_extension("golden");
let golden_override =
- root_override.join(&golden_path.file_name().expect("file has basename"));
+ root_override.join(golden_path.file_name().expect("file has basename"));
// .jsonnet.golden for C++ tests
let mut golden = read_file(&golden_path)?;
@@ -282,7 +282,7 @@
}
}
}
- };
+ }
}
}
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -40,8 +40,8 @@
#[test]
fn golden() {
glob!("../", "golden/*.jsonnet", |path| {
- let result = run(&path);
+ let result = run(path);
- assert_snapshot!(result)
+ assert_snapshot!(result);
});
}
tests/tests/suite.rsdiffbeforeafterboth--- a/tests/tests/suite.rs
+++ b/tests/tests/suite.rs
@@ -32,7 +32,7 @@
file.display(),
trace_format.format(&e).unwrap()
),
- };
+ }
}
#[test]
@@ -42,11 +42,9 @@
for entry in fs::read_dir(&root)? {
let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
- continue;
+ if entry.path().extension().is_some_and(|e| e == "jsonnet") {
+ run(&entry.path());
}
-
- run(&entry.path());
}
Ok(())