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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -20,7 +20,8 @@
(Plus, Num(n)) => Val::Num(*n),
(Minus, Num(n)) => Val::try_num(-n.get())?,
(Not, Bool(v)) => Bool(!v),
- (BitNot, Num(n)) => Val::try_num(!(n.get() as i64) as f64)?,
+ #[expect(clippy::cast_precision_loss, reason = "as spec")]
+ (BitNot, Num(n)) => Val::try_num(!n.truncate_for_bitwise()? as f64)?,
(op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
})
}
@@ -73,7 +74,17 @@
pub fn evaluate_mul_op(a: &Val, b: &Val) -> Result<Val> {
use Val::*;
Ok(match (a, b) {
+ #[expect(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "should not be used with values too large, negative == 0"
+ )]
(Str(s), Num(c)) => Val::string(s.to_string().repeat(c.get() as usize)),
+ #[expect(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "should not be used with values too large"
+ )]
(Num(c), Str(s)) => Val::string(s.to_string().repeat(c.get() as usize)),
(Num(v1), Num(v2)) => Val::try_num(v1.get() * v2.get())?,
@@ -218,13 +229,28 @@
(a, Div, b) => evaluate_div_op(a, b)?,
(a, Mod, b) => evaluate_mod_op(a, b)?,
- (Num(v1), BitAnd, Num(v2)) => {
+ (Num(v1), BitAnd, Num(v2)) =>
+ {
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "values are within safe integer ranges"
+ )]
Val::try_num((v1.truncate_for_bitwise()? & v2.truncate_for_bitwise()?) as f64)?
}
- (Num(v1), BitOr, Num(v2)) => {
+ (Num(v1), BitOr, Num(v2)) =>
+ {
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "values are within safe integer ranges"
+ )]
Val::try_num((v1.truncate_for_bitwise()? | v2.truncate_for_bitwise()?) as f64)?
}
- (Num(v1), BitXor, Num(v2)) => {
+ (Num(v1), BitXor, Num(v2)) =>
+ {
+ #[expect(
+ clippy::cast_precision_loss,
+ reason = "values are within safe integer ranges"
+ )]
Val::try_num((v1.truncate_for_bitwise()? ^ v2.truncate_for_bitwise()?) as f64)?
}
(Num(v1), Lhs, Num(v2)) => {
@@ -234,16 +260,28 @@
let base = v1.truncate_for_bitwise()?;
let exp = v2.truncate_for_bitwise()? % 64;
+ #[expect(clippy::cast_sign_loss, reason = "exp is positive")]
if exp >= 1 && base >= (1i64 << (63 - exp as u32)) {
bail!("left shift would overflow")
}
+ #[expect(
+ clippy::cast_precision_loss,
+ clippy::cast_sign_loss,
+ reason = "checked as original impl"
+ )]
Val::try_num(base.wrapping_shl(exp as u32) as f64)?
}
(Num(v1), Rhs, Num(v2)) => {
if v2.get() < 0.0 {
bail!("shift by negative exponent")
}
+ #[expect(
+ clippy::cast_sign_loss,
+ clippy::cast_possible_truncation,
+ reason = "checked as original impl"
+ )]
let exp = ((v2.get() as i64) & 63) as u32;
+ #[expect(clippy::cast_precision_loss, reason = "checked as upstream impl")]
Val::try_num(v1.truncate_for_bitwise()?.wrapping_shr(exp) as f64)?
}
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.rsdiffbeforeafterboth1use std::{2 alloc::{self, Layout},3 borrow::Borrow,4 cell::UnsafeCell,5 cmp,6 hash::{Hash, Hasher},7 mem,8 ptr::{self, NonNull},9 slice, str,10};1112const UTF8_MASK: u32 = 1 << 31;13const REFCNT_MASK: u32 = !UTF8_MASK;1415#[repr(C)]16struct InnerHeader {17 size: u32,18 // MSB is checked utf8 flag, rest - refcnt19 utf8_refcnt: u32,20}21impl InnerHeader {22 const fn new(size: u32, is_utf8: bool) -> Self {23 Self {24 size,25 utf8_refcnt: 1 | (if is_utf8 { UTF8_MASK } else { 0 }),26 }27 }2829 const fn refcnt(&self) -> u32 {30 self.utf8_refcnt & REFCNT_MASK31 }32 const fn is_utf8(&self) -> bool {33 self.utf8_refcnt & UTF8_MASK != 034 }3536 fn set_refcnt(&mut self, cnt: u32) {37 assert_eq!(cnt & UTF8_MASK, 0);38 // Reset all bits expect last39 self.utf8_refcnt &= UTF8_MASK;40 // Store refcnt41 self.utf8_refcnt |= cnt;42 }43 fn set_is_utf8(&mut self) {44 self.utf8_refcnt |= UTF8_MASK;45 }46}4748/// Similar to Rc<[u8]>, but stores all data (refcnt, size) inline, instead of being DST49pub struct Inner(UnsafeCell<NonNull<InnerHeader>>);50impl Inner {51 /// # Safety52 /// `is_utf8` should only be set if data is really checked to be utf853 /// # Panics54 /// If data is larger than 4GB55 // we allocate with correct alignment56 #[allow(clippy::cast_ptr_alignment)]57 unsafe fn new_raw(bytes: &[u8], is_utf8: bool) -> Self {58 // SAFETY:59 // - layout has non-zero size, and correct align60 // - data is written right after allocation61 // - new allocation can't overlap with passed slice62 unsafe {63 let data: *mut InnerHeader = alloc::alloc(Layout::from_size_align_unchecked(64 mem::size_of::<InnerHeader>() + bytes.len(),65 mem::align_of::<InnerHeader>(),66 ))67 .cast();68 assert!(!data.is_null());69 *data = InnerHeader::new(bytes.len().try_into().expect("bytes > 4GB"), is_utf8);70 ptr::copy_nonoverlapping(bytes.as_ptr(), data.offset(1).cast::<u8>(), bytes.len());71 Self(UnsafeCell::new(NonNull::new_unchecked(data)))72 }73 }74 pub fn new_bytes(bytes: &[u8]) -> Self {75 // SAFETY: is_utf8 is not set76 unsafe { Self::new_raw(bytes, false) }77 }78 #[allow(dead_code)]79 pub fn new_str(str: &str) -> Self {80 // SAFETY: strings always utf881 unsafe { Self::new_raw(str.as_bytes(), true) }82 }8384 // `slice::from_raw_parts` is not yet stabilized85 #[allow(clippy::missing_const_for_fn)]86 pub fn as_slice(&self) -> &[u8] {87 let header = Self::header(self);88 // SAFETY: data is not null, and it is correctly initialized89 let size = unsafe { (*header).size };90 // SAFETY: bytes after data is allocated to be exactly data.size in length91 unsafe {92 slice::from_raw_parts(93 (*self.0.get()).as_ptr().offset(1).cast::<u8>(),94 size as usize,95 )96 }97 }9899 /// # Safety100 /// Data should be checked to be utf8 via [`check_utf8`] first101 pub unsafe fn as_str_unchecked(&self) -> &str {102 // SAFETY: data is checked103 unsafe { str::from_utf8_unchecked(self.as_slice()) }104 }105106 /// Check data to be utf-8107 ///108 /// Positive results are cached109 pub fn check_utf8(this: &Self) -> bool {110 let header = Self::header_mut(this);111 // SAFETY: header is initialized112 if unsafe { (*header).is_utf8() } {113 return true;114 }115116 if str::from_utf8(this.as_slice()).is_ok() {117 // SAFETY: header is initialized118 unsafe { (*header).set_is_utf8() };119 true120 } else {121 false122 }123 }124125 /// Marks data as utf-8126 ///127 /// # Safety128 /// data should be really utf-8129 pub unsafe fn assume_utf8(this: &Self) {130 let header = Self::header_mut(this);131 // SAFETY: header is correct132 unsafe { (*header).set_is_utf8() }133 }134135 fn header(this: &Self) -> *const InnerHeader {136 // Safety: in `new`, we allocate with correct alignment137 unsafe { (*this.0.get()).as_ptr() }138 }139 fn header_mut(this: &Self) -> *mut InnerHeader {140 // Safety: in `new`, we allocate with correct alignment141 unsafe { (*this.0.get()).as_ptr() }142 }143144 fn clone(this: &Self) -> Self {145 let header = Self::header_mut(this);146 // SAFETY: header is initialized147 unsafe {148 let refcnt = (*header).refcnt() + 1;149 (*header).set_refcnt(refcnt);150 Self(UnsafeCell::new(*this.0.get()))151 }152 }153154 pub fn ptr_eq(a: &Self, b: &Self) -> bool {155 Self::as_ptr(a) == Self::as_ptr(b)156 }157 pub fn as_ptr(this: &Self) -> *const u8 {158 // SAFETY: data is initialized159 unsafe { (*this.0.get()).as_ptr().offset(1).cast() }160 }161162 pub fn strong_count(this: &Self) -> u32 {163 let header = Self::header(this);164 // SAFETY: header is initialized165 unsafe { (*header).refcnt() }166 }167}168169impl Clone for Inner {170 fn clone(&self) -> Self {171 Self::clone(self)172 }173}174175impl Drop for Inner {176 fn drop(&mut self) {177 #[cold]178 #[inline(never)]179 fn dealloc(val: &Inner) {180 let header = Inner::header_mut(val);181 // Safety: Data is valid yet182 let size = unsafe { (*header).size as usize };183 // SAFETY: size is correct, layout is valid, data will not be used after this, as refcn == 0184 unsafe {185 alloc::dealloc(186 header.cast(),187 Layout::from_size_align_unchecked(188 mem::size_of::<InnerHeader>() + size,189 mem::align_of::<InnerHeader>(),190 ),191 );192 }193 }194 let header = Self::header_mut(self);195 // SAFETY: header is initialized196 let refcnt = unsafe {197 let refcnt = (*header).refcnt() - 1;198 (*header).set_refcnt(refcnt);199 refcnt200 };201 if refcnt == 0 {202 dealloc(self);203 }204 }205}206207impl PartialEq for Inner {208 fn eq(&self, other: &Self) -> bool {209 Self::as_ptr(self) == Self::as_ptr(other) || self.as_slice().eq(other.as_slice())210 }211}212impl Hash for Inner {213 fn hash<H: Hasher>(&self, state: &mut H) {214 self.as_slice().hash(state);215 }216}217impl Eq for Inner {}218impl PartialOrd for Inner {219 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {220 Some(self.cmp(other))221 }222}223impl Ord for Inner {224 fn cmp(&self, other: &Self) -> cmp::Ordering {225 self.as_slice().cmp(other.as_slice())226 }227}228229impl Borrow<[u8]> for Inner {230 fn borrow(&self) -> &[u8] {231 self.as_slice()232 }233}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
];