difftreelog
refactor reenable clippy integer cast checks
in: master
17 files changed
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -122,11 +122,6 @@
wildcard_imports = "allow"
enum_glob_use = "allow"
module_name_repetitions = "allow"
-# TODO: fix individual issues, however this works as intended almost everywhere
-cast_precision_loss = "allow"
-cast_possible_wrap = "allow"
-cast_possible_truncation = "allow"
-cast_sign_loss = "allow"
# False positives
# https://github.com/rust-lang/rust-clippy/issues/6902
use_self = "allow"
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -128,7 +128,12 @@
#[must_use]
pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {
let get_idx = |pos: Option<i32>, len: usize, default| match pos {
+ #[expect(
+ clippy::cast_sign_loss,
+ reason = "abs value is used, len is limited to u31"
+ )]
Some(v) if v < 0 => len.saturating_sub((-v) as usize),
+ #[expect(clippy::cast_sign_loss, reason = "abs value is used")]
Some(v) => (v as usize).min(len),
None => default,
};
@@ -142,7 +147,9 @@
Self::new(SliceArray {
inner: self,
+ #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
from: index as u32,
+ #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
to: end as u32,
step: step.get(),
})
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -350,22 +350,26 @@
pub fn new_inclusive(start: i32, end: i32) -> Self {
Self { start, end }
}
+ #[expect(
+ clippy::cast_sign_loss,
+ reason = "the math is valid with wrapping, sign loss works as intended"
+ )]
+ fn size(&self) -> usize {
+ (self.end as usize)
+ .wrapping_sub(self.start as usize)
+ .wrapping_add(1)
+ }
fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {
- WithExactSize(
- self.start..=self.end,
- (self.end as usize)
- .wrapping_sub(self.start as usize)
- .wrapping_add(1),
- )
+ WithExactSize(self.start..=self.end, self.size())
}
}
impl ArrayLike for RangeArray {
fn len(&self) -> usize {
- self.range().len()
+ self.size()
}
fn is_empty(&self) -> bool {
- self.range().len() == 0
+ self.size() == 0
}
fn get(&self, index: usize) -> Result<Option<Val>> {
@@ -431,6 +435,10 @@
fn evaluate(&self, index: usize, value: Val) -> Result<Val> {
match &self.mapper {
ArrayMapper::Plain(f) => f.call(value),
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "array len is limited to u31"
+ )]
ArrayMapper::WithIndex(f) => f.call(index as u32, value),
}
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -548,8 +548,18 @@
bail!(FractionalIndex)
}
if n < 0.0 {
- bail!(ArrayBoundsError(n as isize, v.len()));
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "it would be truncated anyway"
+ )]
+ let n = n as isize;
+ bail!(ArrayBoundsError(n, v.len()));
}
+ #[expect(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "n is checked postive"
+ )]
v.get(n as usize)?
.ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?
}
@@ -568,18 +578,29 @@
bail!(FractionalIndex)
}
if n < 0.0 {
- bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "it would be truncated anyway"
+ )]
+ let n = n as isize;
+ bail!(ArrayBoundsError(n, s.into_flat().chars().count()));
}
+ #[expect(
+ clippy::cast_sign_loss,
+ clippy::cast_possible_truncation,
+ reason = "n is positive, overflow will truncate as expected"
+ )]
+ let n = n as usize;
let v: IStr = s
.clone()
.into_flat()
.chars()
- .skip(n as usize)
+ .skip(n)
.take(1)
.collect::<String>()
.into();
if v.is_empty() {
- bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))
+ bail!(StringBoundsError(n, s.into_flat().chars().count()))
}
StrValue::Flat(v)
}),
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth1use std::cmp::Ordering;23use jrsonnet_ir::{BinaryOpType, Expr, UnaryOpType};45use crate::{6 Context, Result, Val,7 arr::ArrValue,8 bail,9 error::ErrorKind::*,10 evaluate,11 stdlib::std_format,12 typed::IntoUntyped as _,13 val::{StrValue, equals},14};1516pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {17 use UnaryOpType::*;18 use Val::*;19 Ok(match (op, b) {20 (Plus, Num(n)) => Val::Num(*n),21 (Minus, Num(n)) => Val::try_num(-n.get())?,22 (Not, Bool(v)) => Bool(!v),23 (BitNot, Num(n)) => Val::try_num(!(n.get() as i64) as f64)?,24 (op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),25 })26}2728pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {29 use Val::*;30 Ok(match (a, b) {31 (Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),3233 (Num(a), Str(b)) => Val::string(format!("{a}{b}")),34 (Str(a), Num(b)) => Val::string(format!("{a}{b}")),3536 (Str(a), o) | (o, Str(a)) if a.is_empty() => Val::string(o.clone().to_string()?),37 (Str(a), o) => Val::string(format!("{a}{}", o.clone().to_string()?)),38 (o, Str(a)) => Val::string(format!("{}{a}", o.clone().to_string()?)),3940 (Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),41 (Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),4243 (Num(v1), Num(v2)) => Val::try_num(v1.get() + v2.get())?,4445 #[cfg(feature = "exp-bigint")]46 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a + &**b)),4748 _ => bail!(BinaryOperatorDoesNotOperateOnValues(49 BinaryOpType::Add,50 a.value_type(),51 b.value_type(),52 )),53 })54}5556pub fn evaluate_sub_op(a: &Val, b: &Val) -> Result<Val> {57 use Val::*;58 Ok(match (a, b) {59 (Num(v1), Num(v2)) => Val::try_num(v1.get() - v2.get())?,6061 #[cfg(feature = "exp-bigint")]62 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a - &**b)),6364 // TODO: Support objects and arrays65 _ => bail!(BinaryOperatorDoesNotOperateOnValues(66 BinaryOpType::Sub,67 a.value_type(),68 b.value_type(),69 )),70 })71}7273pub fn evaluate_mul_op(a: &Val, b: &Val) -> Result<Val> {74 use Val::*;75 Ok(match (a, b) {76 (Str(s), Num(c)) => Val::string(s.to_string().repeat(c.get() as usize)),77 (Num(c), Str(s)) => Val::string(s.to_string().repeat(c.get() as usize)),7879 (Num(v1), Num(v2)) => Val::try_num(v1.get() * v2.get())?,8081 #[cfg(feature = "exp-bigint")]82 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a * &**b)),8384 _ => bail!(BinaryOperatorDoesNotOperateOnValues(85 BinaryOpType::Mul,86 a.value_type(),87 b.value_type(),88 )),89 })90}9192fn is_attempt_to_divide_by_zero(a: &Val, b: &Val) -> bool {93 use Val::*;94 match (a, b) {95 // string format96 (Str(_), _) => false,9798 (_, Num(b)) => **b == 0.,99 #[cfg(feature = "exp-bigint")]100 (_, BigInt(b)) => **b == num_bigint::BigInt::ZERO,101102 // something else103 _ => false,104 }105}106107pub fn evaluate_div_op(a: &Val, b: &Val) -> Result<Val> {108 use Val::*;109110 if is_attempt_to_divide_by_zero(a, b) {111 bail!(DivisionByZero);112 }113114 Ok(match (a, b) {115 (Num(a), Num(b)) => Val::try_num(a.get() / b.get())?,116 #[cfg(feature = "exp-bigint")]117 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a / &**b)),118 (a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(119 BinaryOpType::Div,120 a.value_type(),121 b.value_type()122 )),123 })124}125126pub fn evaluate_mod_op(a: &Val, b: &Val) -> Result<Val> {127 use Val::*;128129 if is_attempt_to_divide_by_zero(a, b) {130 bail!(DivisionByZero);131 }132133 Ok(match (a, b) {134 (Num(a), Num(b)) => Val::try_num(a.get() % b.get())?,135 #[cfg(feature = "exp-bigint")]136 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a % &**b)),137 (Str(str), vals) => {138 String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)?139 }140 (a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(141 BinaryOpType::Mod,142 a.value_type(),143 b.value_type()144 )),145 })146}147148pub fn evaluate_binary_op_special(149 ctx: Context,150 a: &Expr,151 op: BinaryOpType,152 b: &Expr,153) -> Result<Val> {154 use BinaryOpType::*;155 use Val::*;156 Ok(match (evaluate(ctx.clone(), a)?, op, b) {157 (Bool(true), Or, _o) => Val::Bool(true),158 (Bool(false), And, _o) => Val::Bool(false),159 #[cfg(feature = "exp-null-coaelse")]160 (Null, NullCoaelse, eb) => evaluate(ctx, eb)?,161 #[cfg(feature = "exp-null-coaelse")]162 (a, NullCoaelse, _o) => a,163 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(ctx, eb)?)?,164 })165}166167pub fn evaluate_compare_op(a: &Val, b: &Val, op: BinaryOpType) -> Result<Ordering> {168 use Val::*;169 Ok(match (a, b) {170 (Str(a), Str(b)) => a.cmp(b),171172 (Num(a), Num(b)) => a.cmp(b),173174 #[cfg(feature = "exp-bigint")]175 (BigInt(a), BigInt(b)) => a.cmp(b),176177 (Arr(a), Arr(b)) => {178 let ai = a.iter();179 let bi = b.iter();180181 for (a, b) in ai.zip(bi) {182 let ord = evaluate_compare_op(&a?, &b?, op)?;183 if !ord.is_eq() {184 return Ok(ord);185 }186 }187 a.len().cmp(&b.len())188 }189 (_, _) => bail!(BinaryOperatorDoesNotOperateOnValues(190 op,191 a.value_type(),192 b.value_type()193 )),194 })195}196197pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {198 use BinaryOpType::*;199 use Val::*;200 Ok(match (a, op, b) {201 (a, Eq, b) => Bool(equals(a, b)?),202 (a, Neq, b) => Bool(!equals(a, b)?),203204 (a, Lt, b) => Bool(evaluate_compare_op(a, b, Lt)?.is_lt()),205 (a, Gt, b) => Bool(evaluate_compare_op(a, b, Gt)?.is_gt()),206 (a, Lte, b) => Bool(evaluate_compare_op(a, b, Lte)?.is_le()),207 (a, Gte, b) => Bool(evaluate_compare_op(a, b, Gte)?.is_ge()),208209 (Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),210211 // Bool X Bool212 (Bool(a), And, Bool(b)) => Bool(*a && *b),213 (Bool(a), Or, Bool(b)) => Bool(*a || *b),214215 (a, Add, b) => evaluate_add_op(a, b)?,216 (a, Sub, b) => evaluate_sub_op(a, b)?,217 (a, Mul, b) => evaluate_mul_op(a, b)?,218 (a, Div, b) => evaluate_div_op(a, b)?,219 (a, Mod, b) => evaluate_mod_op(a, b)?,220221 (Num(v1), BitAnd, Num(v2)) => {222 Val::try_num((v1.truncate_for_bitwise()? & v2.truncate_for_bitwise()?) as f64)?223 }224 (Num(v1), BitOr, Num(v2)) => {225 Val::try_num((v1.truncate_for_bitwise()? | v2.truncate_for_bitwise()?) as f64)?226 }227 (Num(v1), BitXor, Num(v2)) => {228 Val::try_num((v1.truncate_for_bitwise()? ^ v2.truncate_for_bitwise()?) as f64)?229 }230 (Num(v1), Lhs, Num(v2)) => {231 if v2.get() < 0.0 {232 bail!("shift by negative exponent")233 }234 let base = v1.truncate_for_bitwise()?;235 let exp = v2.truncate_for_bitwise()? % 64;236237 if exp >= 1 && base >= (1i64 << (63 - exp as u32)) {238 bail!("left shift would overflow")239 }240 Val::try_num(base.wrapping_shl(exp as u32) as f64)?241 }242 (Num(v1), Rhs, Num(v2)) => {243 if v2.get() < 0.0 {244 bail!("shift by negative exponent")245 }246 let exp = ((v2.get() as i64) & 63) as u32;247 Val::try_num(v1.truncate_for_bitwise()?.wrapping_shr(exp) as f64)?248 }249250 // Bigint X Bigint251 _ => bail!(BinaryOperatorDoesNotOperateOnValues(252 op,253 a.value_type(),254 b.value_type(),255 )),256 })257}1use std::cmp::Ordering;23use jrsonnet_ir::{BinaryOpType, Expr, UnaryOpType};45use crate::{6 Context, Result, Val,7 arr::ArrValue,8 bail,9 error::ErrorKind::*,10 evaluate,11 stdlib::std_format,12 typed::IntoUntyped as _,13 val::{StrValue, equals},14};1516pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {17 use UnaryOpType::*;18 use Val::*;19 Ok(match (op, b) {20 (Plus, Num(n)) => Val::Num(*n),21 (Minus, Num(n)) => Val::try_num(-n.get())?,22 (Not, Bool(v)) => Bool(!v),23 #[expect(clippy::cast_precision_loss, reason = "as spec")]24 (BitNot, Num(n)) => Val::try_num(!n.truncate_for_bitwise()? as f64)?,25 (op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),26 })27}2829pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {30 use Val::*;31 Ok(match (a, b) {32 (Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),3334 (Num(a), Str(b)) => Val::string(format!("{a}{b}")),35 (Str(a), Num(b)) => Val::string(format!("{a}{b}")),3637 (Str(a), o) | (o, Str(a)) if a.is_empty() => Val::string(o.clone().to_string()?),38 (Str(a), o) => Val::string(format!("{a}{}", o.clone().to_string()?)),39 (o, Str(a)) => Val::string(format!("{}{a}", o.clone().to_string()?)),4041 (Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),42 (Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),4344 (Num(v1), Num(v2)) => Val::try_num(v1.get() + v2.get())?,4546 #[cfg(feature = "exp-bigint")]47 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a + &**b)),4849 _ => bail!(BinaryOperatorDoesNotOperateOnValues(50 BinaryOpType::Add,51 a.value_type(),52 b.value_type(),53 )),54 })55}5657pub fn evaluate_sub_op(a: &Val, b: &Val) -> Result<Val> {58 use Val::*;59 Ok(match (a, b) {60 (Num(v1), Num(v2)) => Val::try_num(v1.get() - v2.get())?,6162 #[cfg(feature = "exp-bigint")]63 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a - &**b)),6465 // TODO: Support objects and arrays66 _ => bail!(BinaryOperatorDoesNotOperateOnValues(67 BinaryOpType::Sub,68 a.value_type(),69 b.value_type(),70 )),71 })72}7374pub fn evaluate_mul_op(a: &Val, b: &Val) -> Result<Val> {75 use Val::*;76 Ok(match (a, b) {77 #[expect(78 clippy::cast_possible_truncation,79 clippy::cast_sign_loss,80 reason = "should not be used with values too large, negative == 0"81 )]82 (Str(s), Num(c)) => Val::string(s.to_string().repeat(c.get() as usize)),83 #[expect(84 clippy::cast_possible_truncation,85 clippy::cast_sign_loss,86 reason = "should not be used with values too large"87 )]88 (Num(c), Str(s)) => Val::string(s.to_string().repeat(c.get() as usize)),8990 (Num(v1), Num(v2)) => Val::try_num(v1.get() * v2.get())?,9192 #[cfg(feature = "exp-bigint")]93 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a * &**b)),9495 _ => bail!(BinaryOperatorDoesNotOperateOnValues(96 BinaryOpType::Mul,97 a.value_type(),98 b.value_type(),99 )),100 })101}102103fn is_attempt_to_divide_by_zero(a: &Val, b: &Val) -> bool {104 use Val::*;105 match (a, b) {106 // string format107 (Str(_), _) => false,108109 (_, Num(b)) => **b == 0.,110 #[cfg(feature = "exp-bigint")]111 (_, BigInt(b)) => **b == num_bigint::BigInt::ZERO,112113 // something else114 _ => false,115 }116}117118pub fn evaluate_div_op(a: &Val, b: &Val) -> Result<Val> {119 use Val::*;120121 if is_attempt_to_divide_by_zero(a, b) {122 bail!(DivisionByZero);123 }124125 Ok(match (a, b) {126 (Num(a), Num(b)) => Val::try_num(a.get() / b.get())?,127 #[cfg(feature = "exp-bigint")]128 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a / &**b)),129 (a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(130 BinaryOpType::Div,131 a.value_type(),132 b.value_type()133 )),134 })135}136137pub fn evaluate_mod_op(a: &Val, b: &Val) -> Result<Val> {138 use Val::*;139140 if is_attempt_to_divide_by_zero(a, b) {141 bail!(DivisionByZero);142 }143144 Ok(match (a, b) {145 (Num(a), Num(b)) => Val::try_num(a.get() % b.get())?,146 #[cfg(feature = "exp-bigint")]147 (BigInt(a), BigInt(b)) => BigInt(Box::new(&**a % &**b)),148 (Str(str), vals) => {149 String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)?150 }151 (a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(152 BinaryOpType::Mod,153 a.value_type(),154 b.value_type()155 )),156 })157}158159pub fn evaluate_binary_op_special(160 ctx: Context,161 a: &Expr,162 op: BinaryOpType,163 b: &Expr,164) -> Result<Val> {165 use BinaryOpType::*;166 use Val::*;167 Ok(match (evaluate(ctx.clone(), a)?, op, b) {168 (Bool(true), Or, _o) => Val::Bool(true),169 (Bool(false), And, _o) => Val::Bool(false),170 #[cfg(feature = "exp-null-coaelse")]171 (Null, NullCoaelse, eb) => evaluate(ctx, eb)?,172 #[cfg(feature = "exp-null-coaelse")]173 (a, NullCoaelse, _o) => a,174 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(ctx, eb)?)?,175 })176}177178pub fn evaluate_compare_op(a: &Val, b: &Val, op: BinaryOpType) -> Result<Ordering> {179 use Val::*;180 Ok(match (a, b) {181 (Str(a), Str(b)) => a.cmp(b),182183 (Num(a), Num(b)) => a.cmp(b),184185 #[cfg(feature = "exp-bigint")]186 (BigInt(a), BigInt(b)) => a.cmp(b),187188 (Arr(a), Arr(b)) => {189 let ai = a.iter();190 let bi = b.iter();191192 for (a, b) in ai.zip(bi) {193 let ord = evaluate_compare_op(&a?, &b?, op)?;194 if !ord.is_eq() {195 return Ok(ord);196 }197 }198 a.len().cmp(&b.len())199 }200 (_, _) => bail!(BinaryOperatorDoesNotOperateOnValues(201 op,202 a.value_type(),203 b.value_type()204 )),205 })206}207208pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {209 use BinaryOpType::*;210 use Val::*;211 Ok(match (a, op, b) {212 (a, Eq, b) => Bool(equals(a, b)?),213 (a, Neq, b) => Bool(!equals(a, b)?),214215 (a, Lt, b) => Bool(evaluate_compare_op(a, b, Lt)?.is_lt()),216 (a, Gt, b) => Bool(evaluate_compare_op(a, b, Gt)?.is_gt()),217 (a, Lte, b) => Bool(evaluate_compare_op(a, b, Lte)?.is_le()),218 (a, Gte, b) => Bool(evaluate_compare_op(a, b, Gte)?.is_ge()),219220 (Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),221222 // Bool X Bool223 (Bool(a), And, Bool(b)) => Bool(*a && *b),224 (Bool(a), Or, Bool(b)) => Bool(*a || *b),225226 (a, Add, b) => evaluate_add_op(a, b)?,227 (a, Sub, b) => evaluate_sub_op(a, b)?,228 (a, Mul, b) => evaluate_mul_op(a, b)?,229 (a, Div, b) => evaluate_div_op(a, b)?,230 (a, Mod, b) => evaluate_mod_op(a, b)?,231232 (Num(v1), BitAnd, Num(v2)) =>233 {234 #[expect(235 clippy::cast_precision_loss,236 reason = "values are within safe integer ranges"237 )]238 Val::try_num((v1.truncate_for_bitwise()? & v2.truncate_for_bitwise()?) as f64)?239 }240 (Num(v1), BitOr, Num(v2)) =>241 {242 #[expect(243 clippy::cast_precision_loss,244 reason = "values are within safe integer ranges"245 )]246 Val::try_num((v1.truncate_for_bitwise()? | v2.truncate_for_bitwise()?) as f64)?247 }248 (Num(v1), BitXor, Num(v2)) =>249 {250 #[expect(251 clippy::cast_precision_loss,252 reason = "values are within safe integer ranges"253 )]254 Val::try_num((v1.truncate_for_bitwise()? ^ v2.truncate_for_bitwise()?) as f64)?255 }256 (Num(v1), Lhs, Num(v2)) => {257 if v2.get() < 0.0 {258 bail!("shift by negative exponent")259 }260 let base = v1.truncate_for_bitwise()?;261 let exp = v2.truncate_for_bitwise()? % 64;262263 #[expect(clippy::cast_sign_loss, reason = "exp is positive")]264 if exp >= 1 && base >= (1i64 << (63 - exp as u32)) {265 bail!("left shift would overflow")266 }267 #[expect(268 clippy::cast_precision_loss,269 clippy::cast_sign_loss,270 reason = "checked as original impl"271 )]272 Val::try_num(base.wrapping_shl(exp as u32) as f64)?273 }274 (Num(v1), Rhs, Num(v2)) => {275 if v2.get() < 0.0 {276 bail!("shift by negative exponent")277 }278 #[expect(279 clippy::cast_sign_loss,280 clippy::cast_possible_truncation,281 reason = "checked as original impl"282 )]283 let exp = ((v2.get() as i64) & 63) as u32;284 #[expect(clippy::cast_precision_loss, reason = "checked as upstream impl")]285 Val::try_num(v1.truncate_for_bitwise()?.wrapping_shr(exp) as f64)?286 }287288 // Bigint X Bigint289 _ => bail!(BinaryOperatorDoesNotOperateOnValues(290 op,291 a.value_type(),292 b.value_type(),293 )),294 })295}crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -69,12 +69,20 @@
where
E: de::Error,
{
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "this is how it works with stdlib functions"
+ )]
Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "this is how it works with stdlib functions"
+ )]
Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
}
@@ -161,6 +169,10 @@
Self::Num(n) => {
let n = n.get();
if n.fract() == 0.0 {
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "no correct implementation is possible here; expected"
+ )]
let n = n as i64;
serializer.serialize_i64(n)
} else {
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -792,6 +792,8 @@
key,
})
}
+
+ #[allow(dead_code, reason = "used in object ...rest destructuring")]
pub(crate) fn as_standalone(&self) -> StandaloneSuperCore {
StandaloneSuperCore {
sup: CoreIdx {
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -1,5 +1,10 @@
//! faster std.format impl
#![allow(clippy::too_many_arguments)]
+#![expect(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "many safe integer casts, behavior on overflow is not specified"
+)]
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -129,6 +129,7 @@
} else {
false
};
+ #[expect(clippy::cast_possible_truncation, reason = "code is limited by 4gb")]
let mut location = path
.map_source_locations(&[offset as u32])
.into_iter()
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -157,7 +157,9 @@
}
}
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;
macro_rules! impl_int {
@@ -179,6 +181,7 @@
stringify!($ty)
)
}
+ #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation, reason = "checked by TYPE")]
Ok(n as Self)
}
_ => unreachable!(),
@@ -198,6 +201,7 @@
macro_rules! impl_bounded_int {
($($name:ident = $ty:ty)*) => {$(
#[derive(Clone, Copy)]
+ #[allow(clippy::cast_possible_truncation, reason = "overflow is api misuse")]
pub struct $name<const MIN: $ty, const MAX: $ty>($ty);
impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {
pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {
@@ -219,6 +223,7 @@
}
impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {
+ #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss, reason = "overflow is api misuse")]
const TYPE: &'static ComplexValType =
&ComplexValType::BoundedNumber(
Some(MIN as f64),
@@ -239,6 +244,7 @@
stringify!($ty)
)
}
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "overflow is api misuse, the range is checked by TYPE")]
Ok(Self(n as $ty))
}
_ => unreachable!(),
@@ -318,6 +324,11 @@
if n.trunc() != n {
bail!("cannot convert number with fractional part to usize")
}
+ #[allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "the range is checked by TYPE"
+ )]
Ok(n as Self)
}
_ => unreachable!(),
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -295,8 +295,10 @@
};
let mut get_idx = |pos: Option<i32>, default| {
match pos {
- Some(v) if v < 0 => get_len().saturating_sub((-v) as usize),
+ #[expect(clippy::cast_sign_loss, reason = "abs value is used")]
+ Some(v) if v < 0 => get_len().saturating_sub((-v as isize) as usize),
// No need to clamp, as iterator interface is used
+ #[expect(clippy::cast_sign_loss, reason = "abs value is used")]
Some(v) => v as usize,
None => default,
}
@@ -322,6 +324,10 @@
Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(
index,
end,
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "overflow will result with skip too large which would be equivalent"
+ )]
step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),
))),
}
@@ -446,6 +452,7 @@
if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
bail!("numberic value outside of safe integer range for bitwise operation");
}
+ #[expect(clippy::cast_possible_truncation, reason = "intended")]
Ok(self.0 as i64)
}
}
@@ -520,6 +527,7 @@
type Error = ConvertNumValueError;
#[inline]
fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
+ #[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]
let value = value as f64;
if value < MIN_SAFE_INTEGER {
return Err(ConvertNumValueError::Underflow)
crates/jrsonnet-interner/src/inner.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/inner.rs
+++ b/crates/jrsonnet-interner/src/inner.rs
@@ -67,7 +67,7 @@
.cast();
assert!(!data.is_null());
*data = InnerHeader::new(bytes.len().try_into().expect("bytes > 4GB"), is_utf8);
- ptr::copy_nonoverlapping(bytes.as_ptr(), data.offset(1).cast::<u8>(), bytes.len());
+ ptr::copy_nonoverlapping(bytes.as_ptr(), data.add(1).cast::<u8>(), bytes.len());
Self(UnsafeCell::new(NonNull::new_unchecked(data)))
}
}
@@ -89,10 +89,7 @@
let size = unsafe { (*header).size };
// SAFETY: bytes after data is allocated to be exactly data.size in length
unsafe {
- slice::from_raw_parts(
- (*self.0.get()).as_ptr().offset(1).cast::<u8>(),
- size as usize,
- )
+ slice::from_raw_parts((*self.0.get()).as_ptr().add(1).cast::<u8>(), size as usize)
}
}
@@ -156,7 +153,7 @@
}
pub fn as_ptr(this: &Self) -> *const u8 {
// SAFETY: data is initialized
- unsafe { (*this.0.get()).as_ptr().offset(1).cast() }
+ unsafe { (*this.0.get()).as_ptr().add(1).cast() }
}
pub fn strong_count(this: &Self) -> u32 {
crates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -638,6 +638,7 @@
}
}
+#[allow(clippy::too_many_lines)]
fn expr_basic(p: &mut Parser<'_>) -> Result<Expr> {
if let Some(lit) = literal(p) {
return Ok(Expr::Literal(lit));
@@ -764,7 +765,6 @@
}
SyntaxKind::IDENT => {
- let text = p.text();
let n = spanned(p, |p| {
let s: IStr = p.text().into();
p.eat_any();
@@ -1005,8 +1005,9 @@
}
pub fn string_to_expr(s: IStr, settings: &ParserSettings) -> Spanned<Expr> {
- let len = s.len();
- Spanned::new(Expr::Str(s), Span(settings.source.clone(), 0, len as u32))
+ let len = u32::try_from(s.len()).expect("code size is limited by 4gb");
+
+ Spanned::new(Expr::Str(s), Span(settings.source.clone(), 0, len))
}
#[cfg(test)]
crates/jrsonnet-lexer/src/lex.rsdiffbeforeafterboth--- a/crates/jrsonnet-lexer/src/lex.rs
+++ b/crates/jrsonnet-lexer/src/lex.rs
@@ -60,7 +60,10 @@
range: {
let Range { start, end } = self.inner.span();
- Span(start as u32, end as u32)
+ Span(
+ u32::try_from(start).expect("code size is limited by 4gb"),
+ u32::try_from(end).expect("code size is limited by 4gb"),
+ )
},
})
}
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -17,7 +17,11 @@
}
#[builtin]
-pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {
+pub fn builtin_make_array(
+ // Can't use usize because range_exclusive is over i32
+ sz: BoundedI32<0, { i32::MAX }>,
+ func: FuncVal,
+) -> Result<ArrValue> {
if *sz == 0 {
return Ok(ArrValue::empty());
}
@@ -25,6 +29,7 @@
// TODO: Different mapped array impl avoiding allocating unnecessary vals
|| Ok(ArrValue::range_exclusive(0, *sz).map(FromUntyped::from_untyped(Val::Func(func))?)),
|trivial| {
+ #[expect(clippy::cast_sign_loss, reason = "sz is bounded to be larger than 0")]
let mut out = Vec::with_capacity(*sz as usize);
for _ in 0..*sz {
out.push(trivial.clone());
@@ -363,6 +368,10 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "array sizes are bounded to i32 len"
+ )]
Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)
}
@@ -378,6 +387,11 @@
pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {
for (index, item) in arr.iter().enumerate() {
if equals(&item?, &elem)? {
+ #[expect(
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ reason = "array sizes are bounded to i32 len"
+ )]
return builtin_remove_at(arr.clone(), index as i32);
}
}
crates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/math.rs
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -120,6 +120,7 @@
let lg = s.abs().log2();
let x = (lg - lg.floor() - 1.0).exp2();
let exp = lg.floor() + 1.0;
+ #[expect(clippy::cast_possible_truncation, reason = "exponent can fit in i16")]
(s.signum() * x, exp as i16)
}
}
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -66,6 +66,7 @@
"clippy"
"rustc"
"rust-src"
+ "rust-analyzer"
])
rustfmt
];