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.rsdiffbeforeafterboth1use std::{2 any::Any,3 fmt::{self},4 num::NonZeroU32,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, cc_dyn};9use jrsonnet_interner::IBytes;10use jrsonnet_ir::Expr;1112use crate::{Context, Result, Thunk, Val, function::NativeFn, typed::IntoUntyped};1314mod spec;15pub use spec::{ArrayLike, *};1617cc_dyn!(18 #[doc = "Represents a Jsonnet array value."]19 #[derive(Clone)]20 ArrValue,21 ArrayLike,22 pub fn new() {...}23);24impl fmt::Debug for ArrValue {25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26 self.0.fmt(f)27 }28}2930pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}31impl<I, T> ArrayLikeIter<T> for I where32 I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator33{34}3536impl ArrValue {37 pub fn empty() -> Self {38 Self::new(RangeArray::empty())39 }4041 pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {42 Self::new(ExprArray::new(ctx, exprs))43 }4445 pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {46 Self::new(LazyArray(thunks))47 }4849 pub fn eager(values: Vec<Val>) -> Self {50 Self::new(EagerArray(values))51 }5253 pub fn repeated(data: Self, repeats: usize) -> Option<Self> {54 Some(Self::new(RepeatedArray::new(data, repeats)?))55 }5657 pub fn bytes(bytes: IBytes) -> Self {58 Self::new(BytesArray(bytes))59 }60 pub fn chars(chars: impl Iterator<Item = char>) -> Self {61 Self::new(CharArray(chars.collect()))62 }6364 #[must_use]65 pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {66 Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))67 }6869 #[must_use]70 pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {71 Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))72 }7374 pub fn filter(self, filter: NativeFn!((Thunk<Val>) -> bool)) -> Result<Self> {75 // TODO: ArrValue::Picked(inner, indexes) for large arrays76 'eager: {77 let mut out = Vec::new();78 for i in self.iter() {79 let Ok(i) = i else {80 break 'eager;81 };82 if filter.call(IntoUntyped::into_lazy_untyped(i.clone()))? {83 out.push(i);84 }85 }86 return Ok(Self::eager(out));87 };8889 let mut out = Vec::new();90 for i in self.iter_lazy() {91 if filter.call(i.clone())? {92 out.push(i);93 }94 }95 Ok(Self::lazy(out))96 }9798 pub fn extended(a: Self, b: Self) -> Self {99 // TODO: benchmark for an optimal value, currently just a arbitrary choice100 const ARR_EXTEND_THRESHOLD: usize = 1000;101102 if a.is_empty() {103 b104 } else if b.is_empty() {105 a106 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {107 Self::new(ExtendedArray::new(a, b))108 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {109 let mut out = Vec::with_capacity(a.len() + b.len());110 out.extend(a);111 out.extend(b);112 Self::eager(out)113 } else {114 let mut out = Vec::with_capacity(a.len() + b.len());115 out.extend(a.iter_lazy());116 out.extend(b.iter_lazy());117 Self::lazy(out)118 }119 }120121 pub fn range_exclusive(a: i32, b: i32) -> Self {122 Self::new(RangeArray::new_exclusive(a, b))123 }124 pub fn range_inclusive(a: i32, b: i32) -> Self {125 Self::new(RangeArray::new_inclusive(a, b))126 }127128 #[must_use]129 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {130 let get_idx = |pos: Option<i32>, len: usize, default| match pos {131 Some(v) if v < 0 => len.saturating_sub((-v) as usize),132 Some(v) => (v as usize).min(len),133 None => default,134 };135 let index = get_idx(index, self.len(), 0);136 let end = get_idx(end, self.len(), self.len());137 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));138139 if index >= end {140 return Self::empty();141 }142143 Self::new(SliceArray {144 inner: self,145 from: index as u32,146 to: end as u32,147 step: step.get(),148 })149 }150151 /// Array length.152 pub fn len(&self) -> usize {153 self.0.len()154 }155156 /// Is array contains no elements?157 pub fn is_empty(&self) -> bool {158 self.0.is_empty()159 }160161 /// Get array element by index, evaluating it, if it is lazy.162 ///163 /// Returns `None` on out-of-bounds condition.164 pub fn get(&self, index: usize) -> Result<Option<Val>> {165 self.0.get(index)166 }167168 /// Returns None if get is either non cheap, or out of bounds169 /// Note that non-cheap access includes errorable values170 ///171 /// Prefer it to `get_lazy`, but use `get` when you can.172 fn get_cheap(&self, index: usize) -> Option<Val> {173 self.0.get_cheap(index)174 }175176 /// Get array element by index, without evaluation.177 ///178 /// Returns `None` on out-of-bounds condition.179 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {180 self.0.get_lazy(index)181 }182183 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {184 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))185 }186187 /// Iterate over elements, returning lazy values.188 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {189 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))190 }191192 /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.193 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {194 if self.is_cheap() {195 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))196 } else {197 None198 }199 }200201 /// Return a reversed view on current array.202 #[must_use]203 pub fn reversed(self) -> Self {204 Self::new(ReverseArray(self))205 }206207 pub fn ptr_eq(a: &Self, b: &Self) -> bool {208 Cc::ptr_eq(&a.0, &b.0)209 }210211 /// Is this vec supports `.get_cheap()?`212 pub fn is_cheap(&self) -> bool {213 self.0.is_cheap()214 }215216 pub fn as_any(&self) -> &dyn Any {217 &self.0218 }219}220impl From<Vec<Val>> for ArrValue {221 fn from(value: Vec<Val>) -> Self {222 Self::eager(value)223 }224}225impl From<Vec<Thunk<Val>>> for ArrValue {226 fn from(value: Vec<Thunk<Val>>) -> Self {227 Self::lazy(value)228 }229}230impl FromIterator<Val> for ArrValue {231 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {232 Self::eager(iter.into_iter().collect())233 }234}235impl ArrayLike for ArrValue {236 fn len(&self) -> usize {237 self.0.len()238 }239240 fn get(&self, index: usize) -> Result<Option<Val>> {241 self.0.get(index)242 }243244 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {245 self.0.get_lazy(index)246 }247248 fn get_cheap(&self, index: usize) -> Option<Val> {249 self.0.get_cheap(index)250 }251252 fn is_cheap(&self) -> bool {253 self.0.is_cheap()254 }255}1use std::{2 any::Any,3 fmt::{self},4 num::NonZeroU32,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, cc_dyn};9use jrsonnet_interner::IBytes;10use jrsonnet_ir::Expr;1112use crate::{Context, Result, Thunk, Val, function::NativeFn, typed::IntoUntyped};1314mod spec;15pub use spec::{ArrayLike, *};1617cc_dyn!(18 #[doc = "Represents a Jsonnet array value."]19 #[derive(Clone)]20 ArrValue,21 ArrayLike,22 pub fn new() {...}23);24impl fmt::Debug for ArrValue {25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26 self.0.fmt(f)27 }28}2930pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}31impl<I, T> ArrayLikeIter<T> for I where32 I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator33{34}3536impl ArrValue {37 pub fn empty() -> Self {38 Self::new(RangeArray::empty())39 }4041 pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {42 Self::new(ExprArray::new(ctx, exprs))43 }4445 pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {46 Self::new(LazyArray(thunks))47 }4849 pub fn eager(values: Vec<Val>) -> Self {50 Self::new(EagerArray(values))51 }5253 pub fn repeated(data: Self, repeats: usize) -> Option<Self> {54 Some(Self::new(RepeatedArray::new(data, repeats)?))55 }5657 pub fn bytes(bytes: IBytes) -> Self {58 Self::new(BytesArray(bytes))59 }60 pub fn chars(chars: impl Iterator<Item = char>) -> Self {61 Self::new(CharArray(chars.collect()))62 }6364 #[must_use]65 pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {66 Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))67 }6869 #[must_use]70 pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {71 Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))72 }7374 pub fn filter(self, filter: NativeFn!((Thunk<Val>) -> bool)) -> Result<Self> {75 // TODO: ArrValue::Picked(inner, indexes) for large arrays76 'eager: {77 let mut out = Vec::new();78 for i in self.iter() {79 let Ok(i) = i else {80 break 'eager;81 };82 if filter.call(IntoUntyped::into_lazy_untyped(i.clone()))? {83 out.push(i);84 }85 }86 return Ok(Self::eager(out));87 };8889 let mut out = Vec::new();90 for i in self.iter_lazy() {91 if filter.call(i.clone())? {92 out.push(i);93 }94 }95 Ok(Self::lazy(out))96 }9798 pub fn extended(a: Self, b: Self) -> Self {99 // TODO: benchmark for an optimal value, currently just a arbitrary choice100 const ARR_EXTEND_THRESHOLD: usize = 1000;101102 if a.is_empty() {103 b104 } else if b.is_empty() {105 a106 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {107 Self::new(ExtendedArray::new(a, b))108 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {109 let mut out = Vec::with_capacity(a.len() + b.len());110 out.extend(a);111 out.extend(b);112 Self::eager(out)113 } else {114 let mut out = Vec::with_capacity(a.len() + b.len());115 out.extend(a.iter_lazy());116 out.extend(b.iter_lazy());117 Self::lazy(out)118 }119 }120121 pub fn range_exclusive(a: i32, b: i32) -> Self {122 Self::new(RangeArray::new_exclusive(a, b))123 }124 pub fn range_inclusive(a: i32, b: i32) -> Self {125 Self::new(RangeArray::new_inclusive(a, b))126 }127128 #[must_use]129 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {130 let get_idx = |pos: Option<i32>, len: usize, default| match pos {131 #[expect(132 clippy::cast_sign_loss,133 reason = "abs value is used, len is limited to u31"134 )]135 Some(v) if v < 0 => len.saturating_sub((-v) as usize),136 #[expect(clippy::cast_sign_loss, reason = "abs value is used")]137 Some(v) => (v as usize).min(len),138 None => default,139 };140 let index = get_idx(index, self.len(), 0);141 let end = get_idx(end, self.len(), self.len());142 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));143144 if index >= end {145 return Self::empty();146 }147148 Self::new(SliceArray {149 inner: self,150 #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]151 from: index as u32,152 #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]153 to: end as u32,154 step: step.get(),155 })156 }157158 /// Array length.159 pub fn len(&self) -> usize {160 self.0.len()161 }162163 /// Is array contains no elements?164 pub fn is_empty(&self) -> bool {165 self.0.is_empty()166 }167168 /// Get array element by index, evaluating it, if it is lazy.169 ///170 /// Returns `None` on out-of-bounds condition.171 pub fn get(&self, index: usize) -> Result<Option<Val>> {172 self.0.get(index)173 }174175 /// Returns None if get is either non cheap, or out of bounds176 /// Note that non-cheap access includes errorable values177 ///178 /// Prefer it to `get_lazy`, but use `get` when you can.179 fn get_cheap(&self, index: usize) -> Option<Val> {180 self.0.get_cheap(index)181 }182183 /// Get array element by index, without evaluation.184 ///185 /// Returns `None` on out-of-bounds condition.186 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {187 self.0.get_lazy(index)188 }189190 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {191 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))192 }193194 /// Iterate over elements, returning lazy values.195 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {196 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))197 }198199 /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.200 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {201 if self.is_cheap() {202 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))203 } else {204 None205 }206 }207208 /// Return a reversed view on current array.209 #[must_use]210 pub fn reversed(self) -> Self {211 Self::new(ReverseArray(self))212 }213214 pub fn ptr_eq(a: &Self, b: &Self) -> bool {215 Cc::ptr_eq(&a.0, &b.0)216 }217218 /// Is this vec supports `.get_cheap()?`219 pub fn is_cheap(&self) -> bool {220 self.0.is_cheap()221 }222223 pub fn as_any(&self) -> &dyn Any {224 &self.0225 }226}227impl From<Vec<Val>> for ArrValue {228 fn from(value: Vec<Val>) -> Self {229 Self::eager(value)230 }231}232impl From<Vec<Thunk<Val>>> for ArrValue {233 fn from(value: Vec<Thunk<Val>>) -> Self {234 Self::lazy(value)235 }236}237impl FromIterator<Val> for ArrValue {238 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {239 Self::eager(iter.into_iter().collect())240 }241}242impl ArrayLike for ArrValue {243 fn len(&self) -> usize {244 self.0.len()245 }246247 fn get(&self, index: usize) -> Result<Option<Val>> {248 self.0.get(index)249 }250251 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {252 self.0.get_lazy(index)253 }254255 fn get_cheap(&self, index: usize) -> Option<Val> {256 self.0.get_cheap(index)257 }258259 fn is_cheap(&self) -> bool {260 self.0.is_cheap()261 }262}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.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
];