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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -291,7 +291,7 @@
let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));
for field in &members.fields {
- evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?;
+ evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;
}
if !members.asserts.is_empty() {
@@ -304,13 +304,13 @@
fn run(&self, sup_this: SupThis) -> Result<()> {
let ctx = self.uctx.bind(sup_this)?;
for assert in &*self.asserts {
- evaluate_assert(ctx.clone(), &assert)?;
+ evaluate_assert(ctx.clone(), assert)?;
}
Ok(())
}
}
builder.assert(ObjectAssert {
- uctx: uctx.clone(),
+ uctx,
asserts: members.asserts.clone(),
});
}
@@ -567,7 +567,7 @@
evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
}
let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
- evaluate(ctx, &returned.clone())?
+ evaluate(ctx, returned)?
}
Arr(items) => {
if items.is_empty() {
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.rsdiffbeforeafterboth1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9 arr::{ArrValue, BytesArray},10 bail,11 function::{native::NativeDesc, FuncDesc, FuncVal},12 typed::CheckType,13 val::{IndexableVal, NumValue, StrValue, ThunkMapper},14 ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,15};1617#[derive(Trace)]18struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for FromUntyped<K>20where21 K: Typed + Trace,22{23 type Output = K;2425 fn map(self, from: Val) -> Result<Self::Output> {26 K::from_untyped(from)27 }28}29impl<K: Trace> Default for FromUntyped<K> {30 fn default() -> Self {31 Self(PhantomData)32 }33}3435pub trait TypedObj: Typed {36 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;37 fn parse(obj: &ObjValue) -> Result<Self>;38 fn into_object(self) -> Result<ObjValue> {39 let mut builder = ObjValueBuilder::new();40 self.serialize(&mut builder)?;41 Ok(builder.build())42 }43}4445pub trait Typed: Sized {46 const TYPE: &'static ComplexValType;47 fn into_untyped(typed: Self) -> Result<Val>;48 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {49 Thunk::from(Self::into_untyped(typed))50 }51 fn from_untyped(untyped: Val) -> Result<Self>;52 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {53 Self::from_untyped(lazy.evaluate()?)54 }5556 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`57 fn provides_lazy() -> bool {58 false59 }6061 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible62 fn wants_lazy() -> bool {63 false64 }6566 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result67 /// This method returns identity in impl Typed for Result, and should not be overriden68 #[doc(hidden)]69 fn into_result(typed: Self) -> Result<Val> {70 let value = Self::into_untyped(typed)?;71 Ok(value)72 }73}7475impl<T> Typed for Thunk<T>76where77 T: Typed + Trace + Clone,78{79 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8081 fn into_untyped(typed: Self) -> Result<Val> {82 T::into_untyped(typed.evaluate()?)83 }8485 fn from_untyped(untyped: Val) -> Result<Self> {86 Self::from_lazy_untyped(Thunk::evaluated(untyped))87 }8889 fn provides_lazy() -> bool {90 true91 }9293 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {94 #[derive(Trace)]95 struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);96 impl<K> ThunkMapper<K> for IntoUntyped<K>97 where98 K: Typed + Trace,99 {100 type Output = Val;101102 fn map(self, from: K) -> Result<Self::Output> {103 K::into_untyped(from)104 }105 }106 impl<K: Trace> Default for IntoUntyped<K> {107 fn default() -> Self {108 Self(PhantomData)109 }110 }111 inner.map(<IntoUntyped<T>>::default())112 }113114 fn wants_lazy() -> bool {115 true116 }117118 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {119 Ok(inner.map(<FromUntyped<T>>::default()))120 }121}122123pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;124pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;125126macro_rules! impl_int {127 ($($ty:ty)*) => {$(128 impl Typed for $ty {129 const TYPE: &'static ComplexValType =130 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));131 fn from_untyped(value: Val) -> Result<Self> {132 <Self as Typed>::TYPE.check(&value)?;133 match value {134 Val::Num(n) => {135 let n = n.get();136 #[allow(clippy::float_cmp)]137 if n.trunc() != n {138 bail!(139 "cannot convert number with fractional part to {}",140 stringify!($ty)141 )142 }143 Ok(n as Self)144 }145 _ => unreachable!(),146 }147 }148 fn into_untyped(value: Self) -> Result<Val> {149 Ok(Val::Num(value.into()))150 }151 }152 )*};153}154155impl_int!(i8 u8 i16 u16 i32 u32);156157macro_rules! impl_bounded_int {158 ($($name:ident = $ty:ty)*) => {$(159 #[derive(Clone, Copy)]160 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);161 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {162 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {163 if value >= MIN && value <= MAX {164 Some(Self(value))165 } else {166 None167 }168 }169 pub const fn value(self) -> $ty {170 self.0171 }172 }173 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {174 type Target = $ty;175 fn deref(&self) -> &Self::Target {176 &self.0177 }178 }179180 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {181 const TYPE: &'static ComplexValType =182 &ComplexValType::BoundedNumber(183 Some(MIN as f64),184 Some(MAX as f64),185 );186187 fn from_untyped(value: Val) -> Result<Self> {188 <Self as Typed>::TYPE.check(&value)?;189 match value {190 Val::Num(n) => {191 let n = n.get();192 #[allow(clippy::float_cmp)]193 if n.trunc() != n {194 bail!(195 "cannot convert number with fractional part to {}",196 stringify!($ty)197 )198 }199 Ok(Self(n as $ty))200 }201 _ => unreachable!(),202 }203 }204205 #[allow(clippy::cast_lossless)]206 fn into_untyped(value: Self) -> Result<Val> {207 Ok(Val::try_num(value.0)?)208 }209 }210 )*};211}212213impl_bounded_int!(214 BoundedI8 = i8215 BoundedI16 = i16216 BoundedI32 = i32217 BoundedI64 = i64218 BoundedUsize = usize219);220221impl Typed for f64 {222 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);223224 fn into_untyped(value: Self) -> Result<Val> {225 Ok(Val::try_num(value)?)226 }227228 fn from_untyped(value: Val) -> Result<Self> {229 <Self as Typed>::TYPE.check(&value)?;230 match value {231 Val::Num(n) => Ok(n.get()),232 _ => unreachable!(),233 }234 }235}236237pub struct PositiveF64(pub f64);238impl Typed for PositiveF64 {239 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);240241 fn into_untyped(value: Self) -> Result<Val> {242 Ok(Val::try_num(value.0)?)243 }244245 fn from_untyped(value: Val) -> Result<Self> {246 <Self as Typed>::TYPE.check(&value)?;247 match value {248 Val::Num(n) => Ok(Self(n.get())),249 _ => unreachable!(),250 }251 }252}253impl Typed for usize {254 const TYPE: &'static ComplexValType =255 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));256257 fn into_untyped(value: Self) -> Result<Val> {258 Ok(Val::try_num(value)?)259 }260261 fn from_untyped(value: Val) -> Result<Self> {262 <Self as Typed>::TYPE.check(&value)?;263 match value {264 Val::Num(n) => {265 let n = n.get();266 #[allow(clippy::float_cmp)]267 if n.trunc() != n {268 bail!("cannot convert number with fractional part to usize")269 }270 Ok(n as Self)271 }272 _ => unreachable!(),273 }274 }275}276277impl Typed for IStr {278 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);279280 fn into_untyped(value: Self) -> Result<Val> {281 Ok(Val::string(value))282 }283284 fn from_untyped(value: Val) -> Result<Self> {285 <Self as Typed>::TYPE.check(&value)?;286 match value {287 Val::Str(s) => Ok(s.into_flat()),288 _ => unreachable!(),289 }290 }291}292293impl Typed for String {294 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);295296 fn into_untyped(value: Self) -> Result<Val> {297 Ok(Val::string(value))298 }299300 fn from_untyped(value: Val) -> Result<Self> {301 <Self as Typed>::TYPE.check(&value)?;302 match value {303 Val::Str(s) => Ok(s.to_string()),304 _ => unreachable!(),305 }306 }307}308309impl Typed for StrValue {310 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);311312 fn into_untyped(value: Self) -> Result<Val> {313 Ok(Val::Str(value))314 }315316 fn from_untyped(value: Val) -> Result<Self> {317 <Self as Typed>::TYPE.check(&value)?;318 match value {319 Val::Str(s) => Ok(s),320 _ => unreachable!(),321 }322 }323}324325impl Typed for char {326 const TYPE: &'static ComplexValType = &ComplexValType::Char;327328 fn into_untyped(value: Self) -> Result<Val> {329 Ok(Val::string(value))330 }331332 fn from_untyped(value: Val) -> Result<Self> {333 <Self as Typed>::TYPE.check(&value)?;334 match value {335 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),336 _ => unreachable!(),337 }338 }339}340341impl<T> Typed for Vec<T>342where343 T: Typed,344{345 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);346347 fn into_untyped(value: Self) -> Result<Val> {348 Ok(Val::Arr(349 value350 .into_iter()351 .map(T::into_untyped)352 .collect::<Result<ArrValue>>()?,353 ))354 }355356 fn from_untyped(value: Val) -> Result<Self> {357 let Val::Arr(a) = value else {358 <Self as Typed>::TYPE.check(&value)?;359 unreachable!("typecheck should fail")360 };361 a.iter()362 .enumerate()363 .map(|(i, r)| {364 r.and_then(|t| {365 T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))366 })367 })368 .collect::<Result<Self>>()369 }370}371372impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {373 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);374375 fn into_untyped(typed: Self) -> Result<Val> {376 let mut out = ObjValueBuilder::with_capacity(typed.len());377 for (k, v) in typed {378 let Some(key) = K::into_untyped(k)?.as_str() else {379 bail!("map key should serialize to string");380 };381 let value = V::into_untyped(v)?;382 out.field(key).value(value);383 }384 Ok(Val::Obj(out.build()))385 }386387 fn from_untyped(value: Val) -> Result<Self> {388 Self::TYPE.check(&value)?;389 let obj = value.as_obj().expect("typecheck should fail");390391 let mut out = Self::new();392 if V::wants_lazy() {393 for key in obj.fields_ex(394 false,395 #[cfg(feature = "exp-preserve-order")]396 false,397 ) {398 let value = obj.get_lazy(key.clone()).expect("field exists");399 let value = V::from_lazy_untyped(value)?;400 let key = K::from_untyped(Val::Str(key.into()))?;401 let _ = out.insert(key, value);402 }403 } else {404 for (key, value) in obj.iter(405 #[cfg(feature = "exp-preserve-order")]406 false,407 ) {408 let key = K::from_untyped(Val::Str(key.into()))?;409 let value = V::from_untyped(value?)?;410 let _ = out.insert(key, value);411 }412 }413 Ok(out)414 }415}416417impl Typed for Val {418 const TYPE: &'static ComplexValType = &ComplexValType::Any;419420 fn into_untyped(typed: Self) -> Result<Val> {421 Ok(typed)422 }423 fn from_untyped(untyped: Val) -> Result<Self> {424 Ok(untyped)425 }426}427428// Hack429#[doc(hidden)]430impl<T> Typed for Result<T>431where432 T: Typed,433{434 const TYPE: &'static ComplexValType = &ComplexValType::Any;435436 fn into_untyped(_typed: Self) -> Result<Val> {437 panic!("do not use this conversion")438 }439440 fn from_untyped(_untyped: Val) -> Result<Self> {441 panic!("do not use this conversion")442 }443444 fn into_result(typed: Self) -> Result<Val> {445 typed.map(T::into_untyped)?446 }447}448449/// Specialization450impl Typed for IBytes {451 const TYPE: &'static ComplexValType =452 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));453454 fn into_untyped(value: Self) -> Result<Val> {455 Ok(Val::Arr(ArrValue::bytes(value)))456 }457458 fn from_untyped(value: Val) -> Result<Self> {459 let Val::Arr(a) = &value else {460 <Self as Typed>::TYPE.check(&value)?;461 unreachable!()462 };463 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {464 return Ok(bytes.0.as_slice().into());465 }466 <Self as Typed>::TYPE.check(&value)?;467 // Any::downcast_ref::<ByteArray>(&a);468 let mut out = Vec::with_capacity(a.len());469 for e in a.iter() {470 let r = e?;471 out.push(u8::from_untyped(r)?);472 }473 Ok(out.as_slice().into())474 }475}476477pub struct M1;478impl Typed for M1 {479 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));480481 fn into_untyped(_: Self) -> Result<Val> {482 Ok(Val::Num(NumValue::new(-1.0).expect("finite")))483 }484485 fn from_untyped(value: Val) -> Result<Self> {486 <Self as Typed>::TYPE.check(&value)?;487 Ok(Self)488 }489}490491macro_rules! decl_either {492 ($($name: ident, $($id: ident)*);*) => {$(493 #[derive(Clone)]494 pub enum $name<$($id),*> {495 $($id($id)),*496 }497 impl<$($id),*> Typed for $name<$($id),*>498 where499 $($id: Typed,)*500 {501 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);502503 fn into_untyped(value: Self) -> Result<Val> {504 match value {$(505 $name::$id(v) => $id::into_untyped(v)506 ),*}507 }508509 fn from_untyped(value: Val) -> Result<Self> {510 $(511 if $id::TYPE.check(&value).is_ok() {512 $id::from_untyped(value).map(Self::$id)513 } else514 )* {515 <Self as Typed>::TYPE.check(&value)?;516 unreachable!()517 }518 }519 }520 )*}521}522decl_either!(523 Either1, A;524 Either2, A B;525 Either3, A B C;526 Either4, A B C D;527 Either5, A B C D E;528 Either6, A B C D E F;529 Either7, A B C D E F G530);531#[macro_export]532macro_rules! Either {533 ($a:ty) => {$crate::typed::Either1<$a>};534 ($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};535 ($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};536 ($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};537 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};538 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};539 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};540}541pub use Either;542543pub type MyType = Either![u32, f64, String];544545impl Typed for ArrValue {546 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);547548 fn into_untyped(value: Self) -> Result<Val> {549 Ok(Val::Arr(value))550 }551552 fn from_untyped(value: Val) -> Result<Self> {553 <Self as Typed>::TYPE.check(&value)?;554 match value {555 Val::Arr(a) => Ok(a),556 _ => unreachable!(),557 }558 }559}560561impl Typed for FuncVal {562 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);563564 fn into_untyped(value: Self) -> Result<Val> {565 Ok(Val::Func(value))566 }567568 fn from_untyped(value: Val) -> Result<Self> {569 <Self as Typed>::TYPE.check(&value)?;570 match value {571 Val::Func(a) => Ok(a),572 _ => unreachable!(),573 }574 }575}576577impl Typed for Cc<FuncDesc> {578 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);579580 fn into_untyped(value: Self) -> Result<Val> {581 Ok(Val::Func(FuncVal::Normal(value)))582 }583584 fn from_untyped(value: Val) -> Result<Self> {585 <Self as Typed>::TYPE.check(&value)?;586 match value {587 Val::Func(FuncVal::Normal(desc)) => Ok(desc),588 Val::Func(_) => bail!("expected normal function, not builtin"),589 _ => unreachable!(),590 }591 }592}593594impl Typed for ObjValue {595 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);596597 fn into_untyped(value: Self) -> Result<Val> {598 Ok(Val::Obj(value))599 }600601 fn from_untyped(value: Val) -> Result<Self> {602 <Self as Typed>::TYPE.check(&value)?;603 match value {604 Val::Obj(a) => Ok(a),605 _ => unreachable!(),606 }607 }608}609610impl Typed for bool {611 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);612613 fn into_untyped(value: Self) -> Result<Val> {614 Ok(Val::Bool(value))615 }616617 fn from_untyped(value: Val) -> Result<Self> {618 <Self as Typed>::TYPE.check(&value)?;619 match value {620 Val::Bool(a) => Ok(a),621 _ => unreachable!(),622 }623 }624}625impl Typed for IndexableVal {626 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[627 &ComplexValType::Simple(ValType::Arr),628 &ComplexValType::Simple(ValType::Str),629 ]);630631 fn into_untyped(value: Self) -> Result<Val> {632 match value {633 Self::Str(s) => Ok(Val::string(s)),634 Self::Arr(a) => Ok(Val::Arr(a)),635 }636 }637638 fn from_untyped(value: Val) -> Result<Self> {639 <Self as Typed>::TYPE.check(&value)?;640 value.into_indexable()641 }642}643644pub struct Null;645impl Typed for Null {646 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);647648 fn into_untyped(_: Self) -> Result<Val> {649 Ok(Val::Null)650 }651652 fn from_untyped(value: Val) -> Result<Self> {653 <Self as Typed>::TYPE.check(&value)?;654 Ok(Self)655 }656}657658impl<T> Typed for Option<T>659where660 T: Typed,661{662 const TYPE: &'static ComplexValType =663 &ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);664665 fn into_untyped(typed: Self) -> Result<Val> {666 typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))667 }668669 fn from_untyped(untyped: Val) -> Result<Self> {670 if matches!(untyped, Val::Null) {671 Ok(None)672 } else {673 T::from_untyped(untyped).map(Some)674 }675 }676}677678pub struct NativeFn<D: NativeDesc>(D::Value);679impl<D: NativeDesc> Deref for NativeFn<D> {680 type Target = D::Value;681682 fn deref(&self) -> &Self::Target {683 &self.0684 }685}686impl<D: NativeDesc> Typed for NativeFn<D> {687 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);688689 fn into_untyped(_typed: Self) -> Result<Val> {690 bail!("can only convert functions from jsonnet to native")691 }692693 fn from_untyped(untyped: Val) -> Result<Self> {694 Ok(Self(695 untyped696 .as_func()697 .expect("shape is checked")698 .into_native::<D>(),699 ))700 }701}702703impl Typed for NumValue {704 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);705706 fn into_untyped(typed: Self) -> Result<Val> {707 Ok(Val::Num(typed))708 }709710 fn from_untyped(untyped: Val) -> Result<Self> {711 Self::TYPE.check(&untyped)?;712 match untyped {713 Val::Num(v) => Ok(v),714 _ => unreachable!(),715 }716 }717}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(())