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.rsdiffbeforeafterboth1use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_ir::Expr;67use super::ArrValue;8use crate::{9 Context, Error, ObjValue, Result, Thunk, Val,10 error::ErrorKind::InfiniteRecursionDetected,11 evaluate,12 function::NativeFn,13 typed::{IntoUntyped, Typed},14 val::ThunkValue,15};1617pub trait ArrayLike: Any + Trace + Debug {18 fn len(&self) -> usize;19 fn is_empty(&self) -> bool {20 self.len() == 021 }22 fn get(&self, index: usize) -> Result<Option<Val>>;23 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;24 fn get_cheap(&self, index: usize) -> Option<Val>;2526 fn is_cheap(&self) -> bool;27}2829#[derive(Debug, Trace)]30pub struct SliceArray {31 pub(crate) inner: ArrValue,32 pub(crate) from: u32,33 pub(crate) to: u32,34 pub(crate) step: u32,35}3637impl SliceArray {38 fn map_idx(&self, index: usize) -> usize {39 self.from as usize + self.step as usize * index40 }41}42impl ArrayLike for SliceArray {43 fn len(&self) -> usize {44 (self.to - self.from).div_ceil(self.step) as usize45 }4647 fn get(&self, index: usize) -> Result<Option<Val>> {48 self.inner.get(self.map_idx(index))49 }5051 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {52 self.inner.get_lazy(self.map_idx(index))53 }5455 fn get_cheap(&self, index: usize) -> Option<Val> {56 self.inner.get_cheap(self.map_idx(index))57 }58 fn is_cheap(&self) -> bool {59 self.inner.is_cheap()60 }61}6263#[derive(Trace, Debug)]64pub struct CharArray(pub Vec<char>);65impl ArrayLike for CharArray {66 fn len(&self) -> usize {67 self.0.len()68 }6970 fn get(&self, index: usize) -> Result<Option<Val>> {71 Ok(self.get_cheap(index))72 }7374 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {75 self.get_cheap(index).map(Thunk::evaluated)76 }7778 fn get_cheap(&self, index: usize) -> Option<Val> {79 self.0.get(index).map(|v| Val::string(*v))80 }81 fn is_cheap(&self) -> bool {82 true83 }84}8586#[derive(Trace, Debug)]87pub struct BytesArray(pub IBytes);88impl ArrayLike for BytesArray {89 fn len(&self) -> usize {90 self.0.len()91 }9293 fn get(&self, index: usize) -> Result<Option<Val>> {94 Ok(self.get_cheap(index))95 }9697 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {98 self.get_cheap(index).map(Thunk::evaluated)99 }100101 fn get_cheap(&self, index: usize) -> Option<Val> {102 self.0.get(index).map(|v| Val::Num((*v).into()))103 }104 fn is_cheap(&self) -> bool {105 true106 }107}108109#[derive(Debug, Trace, Clone)]110enum ArrayThunk {111 Computed(Val),112 Errored(Error),113 Waiting,114 Pending,115}116117#[derive(Debug, Trace, Clone)]118pub struct ExprArray {119 ctx: Context,120 src: Rc<Vec<Expr>>,121 cached: Cc<RefCell<Vec<ArrayThunk>>>,122}123impl ExprArray {124 pub fn new(ctx: Context, src: Rc<Vec<Expr>>) -> Self {125 Self {126 ctx,127 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),128 src,129 }130 }131}132impl ArrayLike for ExprArray {133 fn len(&self) -> usize {134 self.cached.borrow().len()135 }136 fn get(&self, index: usize) -> Result<Option<Val>> {137 if index >= self.len() {138 return Ok(None);139 }140 match &self.cached.borrow()[index] {141 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),142 ArrayThunk::Errored(e) => return Err(e.clone()),143 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),144 ArrayThunk::Waiting => {}145 }146147 let ArrayThunk::Waiting =148 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)149 else {150 unreachable!()151 };152153 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {154 Ok(v) => v,155 Err(e) => {156 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());157 return Err(e);158 }159 };160 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());161 Ok(Some(new_value))162 }163 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {164 #[derive(Trace)]165 struct ExprArrThunk {166 expr: ExprArray,167 index: usize,168 }169 impl ThunkValue for ExprArrThunk {170 type Output = Val;171172 fn get(&self) -> Result<Self::Output> {173 self.expr174 .get(self.index)175 .transpose()176 .expect("index checked")177 }178 }179180 if index >= self.len() {181 return None;182 }183 match &self.cached.borrow()[index] {184 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),185 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),186 ArrayThunk::Waiting | ArrayThunk::Pending => {}187 }188189 Some(Thunk::new(ExprArrThunk {190 expr: self.clone(),191 index,192 }))193 }194 fn get_cheap(&self, _index: usize) -> Option<Val> {195 None196 }197 fn is_cheap(&self) -> bool {198 false199 }200}201202#[derive(Trace, Debug)]203pub struct ExtendedArray {204 pub a: ArrValue,205 pub b: ArrValue,206 split: usize,207 len: usize,208}209impl ExtendedArray {210 pub fn new(a: ArrValue, b: ArrValue) -> Self {211 let a_len = a.len();212 let b_len = b.len();213 Self {214 a,215 b,216 split: a_len,217 len: a_len.checked_add(b_len).expect("too large array value"),218 }219 }220}221222struct WithExactSize<I>(I, usize);223impl<I, T> Iterator for WithExactSize<I>224where225 I: Iterator<Item = T>,226{227 type Item = T;228229 fn next(&mut self) -> Option<Self::Item> {230 self.0.next()231 }232 fn nth(&mut self, n: usize) -> Option<Self::Item> {233 self.0.nth(n)234 }235 fn size_hint(&self) -> (usize, Option<usize>) {236 (self.1, Some(self.1))237 }238}239impl<I> DoubleEndedIterator for WithExactSize<I>240where241 I: DoubleEndedIterator,242{243 fn next_back(&mut self) -> Option<Self::Item> {244 self.0.next_back()245 }246 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {247 self.0.nth_back(n)248 }249}250impl<I> ExactSizeIterator for WithExactSize<I>251where252 I: Iterator,253{254 fn len(&self) -> usize {255 self.1256 }257}258impl ArrayLike for ExtendedArray {259 fn get(&self, index: usize) -> Result<Option<Val>> {260 if self.split > index {261 self.a.get(index)262 } else {263 self.b.get(index - self.split)264 }265 }266 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {267 if self.split > index {268 self.a.get_lazy(index)269 } else {270 self.b.get_lazy(index - self.split)271 }272 }273274 fn len(&self) -> usize {275 self.len276 }277278 fn get_cheap(&self, index: usize) -> Option<Val> {279 if self.split > index {280 self.a.get_cheap(index)281 } else {282 self.b.get_cheap(index - self.split)283 }284 }285 fn is_cheap(&self) -> bool {286 self.a.is_cheap() && self.b.is_cheap()287 }288}289290#[derive(Trace, Debug)]291pub struct LazyArray(pub Vec<Thunk<Val>>);292impl ArrayLike for LazyArray {293 fn len(&self) -> usize {294 self.0.len()295 }296 fn get(&self, index: usize) -> Result<Option<Val>> {297 let Some(v) = self.0.get(index) else {298 return Ok(None);299 };300 v.evaluate().map(Some)301 }302 fn get_cheap(&self, _index: usize) -> Option<Val> {303 None304 }305 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {306 self.0.get(index).cloned()307 }308 fn is_cheap(&self) -> bool {309 false310 }311}312313#[derive(Trace, Debug)]314pub struct EagerArray(pub Vec<Val>);315impl ArrayLike for EagerArray {316 fn len(&self) -> usize {317 self.0.len()318 }319320 fn get(&self, index: usize) -> Result<Option<Val>> {321 Ok(self.0.get(index).cloned())322 }323324 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {325 self.0.get(index).cloned().map(Thunk::evaluated)326 }327328 fn get_cheap(&self, index: usize) -> Option<Val> {329 self.0.get(index).cloned()330 }331 fn is_cheap(&self) -> bool {332 true333 }334}335336/// Inclusive range type337#[derive(Debug, Trace, PartialEq, Eq)]338pub struct RangeArray {339 start: i32,340 end: i32,341}342impl RangeArray {343 pub fn empty() -> Self {344 Self::new_exclusive(0, 0)345 }346 pub fn new_exclusive(start: i32, end: i32) -> Self {347 end.checked_sub(1)348 .map_or_else(Self::empty, |end| Self { start, end })349 }350 pub fn new_inclusive(start: i32, end: i32) -> Self {351 Self { start, end }352 }353 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {354 WithExactSize(355 self.start..=self.end,356 (self.end as usize)357 .wrapping_sub(self.start as usize)358 .wrapping_add(1),359 )360 }361}362363impl ArrayLike for RangeArray {364 fn len(&self) -> usize {365 self.range().len()366 }367 fn is_empty(&self) -> bool {368 self.range().len() == 0369 }370371 fn get(&self, index: usize) -> Result<Option<Val>> {372 Ok(self.get_cheap(index))373 }374375 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {376 self.get_cheap(index).map(Thunk::evaluated)377 }378379 fn get_cheap(&self, index: usize) -> Option<Val> {380 self.range().nth(index).map(|i| Val::Num(i.into()))381 }382 fn is_cheap(&self) -> bool {383 true384 }385}386387#[derive(Debug, Trace)]388pub struct ReverseArray(pub ArrValue);389impl ArrayLike for ReverseArray {390 fn len(&self) -> usize {391 self.0.len()392 }393394 fn get(&self, index: usize) -> Result<Option<Val>> {395 self.0.get(self.0.len() - index - 1)396 }397398 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {399 self.0.get_lazy(self.0.len() - index - 1)400 }401402 fn get_cheap(&self, index: usize) -> Option<Val> {403 self.0.get_cheap(self.0.len() - index - 1)404 }405 fn is_cheap(&self) -> bool {406 self.0.is_cheap()407 }408}409410#[derive(Trace, Clone, Debug)]411pub enum ArrayMapper {412 Plain(NativeFn!((Val) -> Val)),413 WithIndex(NativeFn!((u32, Val) -> Val)),414}415416#[derive(Trace, Debug, Clone)]417pub struct MappedArray {418 inner: ArrValue,419 cached: Cc<RefCell<Vec<ArrayThunk>>>,420 mapper: ArrayMapper,421}422impl MappedArray {423 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {424 let len = inner.len();425 Self {426 inner,427 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),428 mapper,429 }430 }431 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {432 match &self.mapper {433 ArrayMapper::Plain(f) => f.call(value),434 ArrayMapper::WithIndex(f) => f.call(index as u32, value),435 }436 }437}438impl ArrayLike for MappedArray {439 fn len(&self) -> usize {440 self.cached.borrow().len()441 }442443 fn get(&self, index: usize) -> Result<Option<Val>> {444 if index >= self.len() {445 return Ok(None);446 }447 match &self.cached.borrow()[index] {448 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),449 ArrayThunk::Errored(e) => return Err(e.clone()),450 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),451 ArrayThunk::Waiting => {}452 }453454 let ArrayThunk::Waiting =455 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)456 else {457 unreachable!()458 };459460 let val = self461 .inner462 .get(index)463 .transpose()464 .expect("index checked")465 .and_then(|r| self.evaluate(index, r));466467 let new_value = match val {468 Ok(v) => v,469 Err(e) => {470 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());471 return Err(e);472 }473 };474 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());475 Ok(Some(new_value))476 }477 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {478 #[derive(Trace)]479 struct MappedArrayThunk {480 arr: MappedArray,481 index: usize,482 }483 impl ThunkValue for MappedArrayThunk {484 type Output = Val;485486 fn get(&self) -> Result<Self::Output> {487 self.arr.get(self.index).transpose().expect("index checked")488 }489 }490491 if index >= self.len() {492 return None;493 }494 match &self.cached.borrow()[index] {495 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),496 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),497 ArrayThunk::Waiting | ArrayThunk::Pending => {}498 }499500 Some(Thunk::new(MappedArrayThunk {501 arr: self.clone(),502 index,503 }))504 }505506 fn get_cheap(&self, _index: usize) -> Option<Val> {507 None508 }509 fn is_cheap(&self) -> bool {510 false511 }512}513514#[derive(Trace, Debug)]515pub struct RepeatedArray {516 data: ArrValue,517 repeats: usize,518 total_len: usize,519}520impl RepeatedArray {521 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {522 let total_len = data.len().checked_mul(repeats)?;523 Some(Self {524 data,525 repeats,526 total_len,527 })528 }529}530531impl ArrayLike for RepeatedArray {532 fn len(&self) -> usize {533 self.total_len534 }535536 fn get(&self, index: usize) -> Result<Option<Val>> {537 if index > self.total_len {538 return Ok(None);539 }540 self.data.get(index % self.data.len())541 }542543 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {544 if index > self.total_len {545 return None;546 }547 self.data.get_lazy(index % self.data.len())548 }549550 fn get_cheap(&self, index: usize) -> Option<Val> {551 if index > self.total_len {552 return None;553 }554 self.data.get_cheap(index % self.data.len())555 }556 fn is_cheap(&self) -> bool {557 self.data.is_cheap()558 }559}560561#[derive(Trace, Debug)]562pub struct PickObjectValues {563 obj: ObjValue,564 keys: Vec<IStr>,565}566567impl PickObjectValues {568 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {569 Self { obj, keys }570 }571}572573impl ArrayLike for PickObjectValues {574 fn len(&self) -> usize {575 self.keys.len()576 }577578 fn get(&self, index: usize) -> Result<Option<Val>> {579 let Some(key) = self.keys.get(index) else {580 return Ok(None);581 };582 Ok(Some(self.obj.get_or_bail(key.clone())?))583 }584585 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {586 let key = self.keys.get(index)?;587 Some(self.obj.get_lazy_or_bail(key.clone()))588 }589590 fn get_cheap(&self, _index: usize) -> Option<Val> {591 None592 }593594 fn is_cheap(&self) -> bool {595 false596 }597}598599#[derive(Trace, Debug)]600pub struct PickObjectKeyValues {601 obj: ObjValue,602 keys: Vec<IStr>,603}604605impl PickObjectKeyValues {606 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {607 Self { obj, keys }608 }609}610611#[derive(Typed, IntoUntyped)]612pub struct KeyValue {613 key: IStr,614 value: Thunk<Val>,615}616617impl ArrayLike for PickObjectKeyValues {618 fn len(&self) -> usize {619 self.keys.len()620 }621622 fn get(&self, index: usize) -> Result<Option<Val>> {623 let Some(key) = self.keys.get(index) else {624 return Ok(None);625 };626 Ok(Some(627 KeyValue::into_untyped(KeyValue {628 key: key.clone(),629 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),630 })631 .expect("convertible"),632 ))633 }634635 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {636 let key = self.keys.get(index)?;637 // Nothing can fail in the key part, yet value is still638 // lazy-evaluated639 Some(Thunk::evaluated(640 KeyValue::into_untyped(KeyValue {641 key: key.clone(),642 value: self.obj.get_lazy_or_bail(key.clone()),643 })644 .expect("convertible"),645 ))646 }647648 fn get_cheap(&self, _index: usize) -> Option<Val> {649 None650 }651652 fn is_cheap(&self) -> bool {653 false654 }655}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.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
];