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.rsdiffbeforeafterboth1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8 ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,9 arr::{ArrValue, BytesArray},10 bail,11 function::FuncVal,12 typed::CheckType,13 val::{IndexableVal, NumValue, StrValue, ThunkMapper},14};1516#[doc(hidden)]17pub mod __typed_macro_prelude {18 pub use ::jrsonnet_evaluator::{19 IStr, ObjValue, ObjValueBuilder, State, Val,20 error::{ErrorKind, Result as JrResult},21 typed::{22 CheckType, ComplexValType, FromUntyped, IntoUntyped, ParseTypedObj, SerializeTypedObj,23 Typed,24 },25 };26}27pub use jrsonnet_macros::{FromUntyped, IntoUntyped, Typed};2829#[derive(Trace)]30struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);31impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>32where33 K: Typed + FromUntyped + Trace,34{35 type Output = K;3637 fn map(self, from: Val) -> Result<Self::Output> {38 K::from_untyped(from)39 }40}41impl<K: Trace> Default for ThunkFromUntyped<K> {42 fn default() -> Self {43 Self(PhantomData)44 }45}46#[derive(Trace)]47struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);48impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>49where50 K: Typed + Trace + IntoUntyped,51{52 type Output = Val;5354 fn map(self, from: K) -> Result<Self::Output> {55 K::into_untyped(from)56 }57}58impl<K: Trace> Default for ThunkIntoUntyped<K> {59 fn default() -> Self {60 Self(PhantomData)61 }62}6364#[diagnostic::on_unimplemented(65 note = "don't implement `ParseTypedObj` directly, it is automatically provided by `FromUntyped` derive"66)]67pub trait ParseTypedObj: Typed {68 fn parse(obj: &ObjValue) -> Result<Self>;69}7071#[diagnostic::on_unimplemented(72 note = "don't implement `SerializeTypedObj` directly, it is automatically provided by `IntoUntyped` derive"73)]74pub trait SerializeTypedObj: Typed {75 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;76 fn into_object(self) -> Result<ObjValue> {77 let mut builder = ObjValueBuilder::new();78 self.serialize(&mut builder)?;79 Ok(builder.build())80 }81}8283pub trait Typed: Sized {84 const TYPE: &'static ComplexValType;85}86pub trait IntoUntyped: Typed {87 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`88 fn provides_lazy() -> bool {89 false90 }91 fn into_untyped(typed: Self) -> Result<Val>;92 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {93 Thunk::from(Self::into_untyped(typed))94 }95}96pub trait IntoUntypedResult: Typed {97 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result98 /// This method returns identity in impl Typed for Result, and should not be overriden99 #[doc(hidden)]100 fn into_untyped_result(typed: Self) -> Result<Val>;101}102impl<T> IntoUntypedResult for T103where104 T: IntoUntyped,105{106 fn into_untyped_result(typed: Self) -> Result<Val> {107 T::into_untyped(typed)108 }109}110111pub trait FromUntyped: Typed {112 fn from_untyped(untyped: Val) -> Result<Self>;113 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {114 Self::from_untyped(lazy.evaluate()?)115 }116117 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible118 fn wants_lazy() -> bool {119 false120 }121}122123impl<T> Typed for Thunk<T>124where125 T: Typed + Trace + Clone,126{127 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);128}129130impl IntoUntyped for Thunk<Val> {131 fn into_untyped(typed: Self) -> Result<Val> {132 typed.evaluate()133 }134 fn provides_lazy() -> bool {135 true136 }137138 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {139 inner140 }141}142143impl<T> FromUntyped for Thunk<T>144where145 T: Typed + FromUntyped + Trace + Clone,146{147 fn from_untyped(untyped: Val) -> Result<Self> {148 Self::from_lazy_untyped(Thunk::evaluated(untyped))149 }150151 fn wants_lazy() -> bool {152 true153 }154155 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {156 Ok(inner.map(<ThunkFromUntyped<T>>::default()))157 }158}159160#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]161pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;162#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]163pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;164165macro_rules! impl_int {166 ($($ty:ty)*) => {$(167 impl Typed for $ty {168 const TYPE: &'static ComplexValType =169 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));170 }171 impl FromUntyped for $ty {172 fn from_untyped(value: Val) -> Result<Self> {173 <Self as Typed>::TYPE.check(&value)?;174 match value {175 Val::Num(n) => {176 let n = n.get();177 #[allow(clippy::float_cmp)]178 if n.trunc() != n {179 bail!(180 "cannot convert number with fractional part to {}",181 stringify!($ty)182 )183 }184 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation, reason = "checked by TYPE")]185 Ok(n as Self)186 }187 _ => unreachable!(),188 }189 }190 }191 impl IntoUntyped for $ty {192 fn into_untyped(value: Self) -> Result<Val> {193 Ok(Val::Num(value.into()))194 }195 }196 )*};197}198199impl_int!(i8 u8 i16 u16 i32 u32);200201macro_rules! impl_bounded_int {202 ($($name:ident = $ty:ty)*) => {$(203 #[derive(Clone, Copy)]204 #[allow(clippy::cast_possible_truncation, reason = "overflow is api misuse")]205 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);206 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {207 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {208 if value >= MIN && value <= MAX {209 Some(Self(value))210 } else {211 None212 }213 }214 pub const fn value(self) -> $ty {215 self.0216 }217 }218 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {219 type Target = $ty;220 fn deref(&self) -> &Self::Target {221 &self.0222 }223 }224225 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {226 #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss, reason = "overflow is api misuse")]227 const TYPE: &'static ComplexValType =228 &ComplexValType::BoundedNumber(229 Some(MIN as f64),230 Some(MAX as f64),231 );232 }233234 impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {235 fn from_untyped(value: Val) -> Result<Self> {236 <Self as Typed>::TYPE.check(&value)?;237 match value {238 Val::Num(n) => {239 let n = n.get();240 #[allow(clippy::float_cmp)]241 if n.trunc() != n {242 bail!(243 "cannot convert number with fractional part to {}",244 stringify!($ty)245 )246 }247 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "overflow is api misuse, the range is checked by TYPE")]248 Ok(Self(n as $ty))249 }250 _ => unreachable!(),251 }252 }253 }254255 impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {256 #[allow(clippy::cast_lossless)]257 fn into_untyped(value: Self) -> Result<Val> {258 Ok(Val::try_num(value.0)?)259 }260 }261 )*};262}263264impl_bounded_int!(265 BoundedI8 = i8266 BoundedI16 = i16267 BoundedI32 = i32268 BoundedI64 = i64269 BoundedUsize = usize270);271272impl Typed for f64 {273 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);274}275impl IntoUntyped for f64 {276 fn into_untyped(value: Self) -> Result<Val> {277 Ok(Val::try_num(value)?)278 }279}280impl FromUntyped for f64 {281 fn from_untyped(value: Val) -> Result<Self> {282 <Self as Typed>::TYPE.check(&value)?;283 match value {284 Val::Num(n) => Ok(n.get()),285 _ => unreachable!(),286 }287 }288}289290pub struct PositiveF64(pub f64);291impl Typed for PositiveF64 {292 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);293}294impl IntoUntyped for PositiveF64 {295 fn into_untyped(value: Self) -> Result<Val> {296 Ok(Val::try_num(value.0)?)297 }298}299impl FromUntyped for PositiveF64 {300 fn from_untyped(value: Val) -> Result<Self> {301 <Self as Typed>::TYPE.check(&value)?;302 match value {303 Val::Num(n) => Ok(Self(n.get())),304 _ => unreachable!(),305 }306 }307}308impl Typed for usize {309 const TYPE: &'static ComplexValType =310 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));311}312impl IntoUntyped for usize {313 fn into_untyped(value: Self) -> Result<Val> {314 Ok(Val::try_num(value)?)315 }316}317impl FromUntyped for usize {318 fn from_untyped(value: Val) -> Result<Self> {319 <Self as Typed>::TYPE.check(&value)?;320 match value {321 Val::Num(n) => {322 let n = n.get();323 #[allow(clippy::float_cmp)]324 if n.trunc() != n {325 bail!("cannot convert number with fractional part to usize")326 }327 #[allow(328 clippy::cast_possible_truncation,329 clippy::cast_sign_loss,330 reason = "the range is checked by TYPE"331 )]332 Ok(n as Self)333 }334 _ => unreachable!(),335 }336 }337}338339impl Typed for IStr {340 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);341}342impl IntoUntyped for IStr {343 fn into_untyped(value: Self) -> Result<Val> {344 Ok(Val::string(value))345 }346}347impl FromUntyped for IStr {348 fn from_untyped(value: Val) -> Result<Self> {349 <Self as Typed>::TYPE.check(&value)?;350 match value {351 Val::Str(s) => Ok(s.into_flat()),352 _ => unreachable!(),353 }354 }355}356357impl Typed for String {358 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);359}360impl IntoUntyped for String {361 fn into_untyped(value: Self) -> Result<Val> {362 Ok(Val::string(value))363 }364}365impl FromUntyped for String {366 fn from_untyped(value: Val) -> Result<Self> {367 <Self as Typed>::TYPE.check(&value)?;368 match value {369 Val::Str(s) => Ok(s.to_string()),370 _ => unreachable!(),371 }372 }373}374375impl Typed for StrValue {376 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);377}378impl IntoUntyped for StrValue {379 fn into_untyped(value: Self) -> Result<Val> {380 Ok(Val::Str(value))381 }382}383impl FromUntyped for StrValue {384 fn from_untyped(value: Val) -> Result<Self> {385 <Self as Typed>::TYPE.check(&value)?;386 match value {387 Val::Str(s) => Ok(s),388 _ => unreachable!(),389 }390 }391}392393impl Typed for char {394 const TYPE: &'static ComplexValType = &ComplexValType::Char;395}396impl IntoUntyped for char {397 fn into_untyped(value: Self) -> Result<Val> {398 Ok(Val::string(value))399 }400}401impl FromUntyped for char {402 fn from_untyped(value: Val) -> Result<Self> {403 <Self as Typed>::TYPE.check(&value)?;404 match value {405 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),406 _ => unreachable!(),407 }408 }409}410411// TODO: View into vec using ArrayLike?412impl<T> Typed for Vec<T>413where414 T: Typed,415{416 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);417}418impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {419 fn into_untyped(value: Self) -> Result<Val> {420 Ok(Val::Arr(421 value422 .into_iter()423 .map(T::into_untyped)424 .collect::<Result<ArrValue>>()?,425 ))426 }427}428impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {429 fn from_untyped(value: Val) -> Result<Self> {430 let Val::Arr(a) = value else {431 <Self as Typed>::TYPE.check(&value)?;432 unreachable!("typecheck should fail")433 };434 a.iter()435 .enumerate()436 .map(|(i, r)| {437 r.and_then(|t| {438 T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))439 })440 })441 .collect::<Result<Self>>()442 }443}444445// TODO: View into BTreeMap using ObjectCore?446impl<K, V> Typed for BTreeMap<K, V>447where448 K: Typed + Ord,449 V: Typed,450{451 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);452}453impl<K, V> IntoUntyped for BTreeMap<K, V>454where455 K: Typed + Ord + IntoUntyped,456 V: Typed + IntoUntyped,457{458 fn into_untyped(typed: Self) -> Result<Val> {459 let mut out = ObjValueBuilder::with_capacity(typed.len());460 for (k, v) in typed {461 let Some(key) = K::into_untyped(k)?.as_str() else {462 bail!("map key should serialize to string");463 };464 let value = V::into_untyped(v)?;465 out.field(key).value(value);466 }467 Ok(Val::Obj(out.build()))468 }469}470impl<K, V> FromUntyped for BTreeMap<K, V>471where472 K: FromUntyped + Ord,473 V: FromUntyped,474{475 fn from_untyped(value: Val) -> Result<Self> {476 Self::TYPE.check(&value)?;477 let obj = value.as_obj().expect("typecheck should fail");478479 let mut out = Self::new();480 if V::wants_lazy() {481 for key in obj.fields_ex(482 false,483 #[cfg(feature = "exp-preserve-order")]484 false,485 ) {486 let value = obj.get_lazy(key.clone()).expect("field exists");487 let value = V::from_lazy_untyped(value)?;488 let key = K::from_untyped(Val::Str(key.into()))?;489 let _ = out.insert(key, value);490 }491 } else {492 for (key, value) in obj.iter(493 #[cfg(feature = "exp-preserve-order")]494 false,495 ) {496 let key = K::from_untyped(Val::Str(key.into()))?;497 let value = V::from_untyped(value?)?;498 let _ = out.insert(key, value);499 }500 }501 Ok(out)502 }503}504505impl Typed for Val {506 const TYPE: &'static ComplexValType = &ComplexValType::Any;507}508impl IntoUntyped for Val {509 fn into_untyped(typed: Self) -> Result<Val> {510 Ok(typed)511 }512}513impl FromUntyped for Val {514 fn from_untyped(untyped: Val) -> Result<Self> {515 Ok(untyped)516 }517}518519#[doc(hidden)]520impl<T> Typed for Result<T>521where522 T: Typed,523{524 const TYPE: &'static ComplexValType = &ComplexValType::Any;525}526impl<T: IntoUntyped> IntoUntypedResult for Result<T> {527 fn into_untyped_result(typed: Self) -> Result<Val> {528 typed.map(T::into_untyped)?529 }530}531532/// Specialization533impl Typed for IBytes {534 const TYPE: &'static ComplexValType =535 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));536}537impl IntoUntyped for IBytes {538 fn into_untyped(value: Self) -> Result<Val> {539 Ok(Val::Arr(ArrValue::bytes(value)))540 }541}542impl FromUntyped for IBytes {543 fn from_untyped(value: Val) -> Result<Self> {544 let Val::Arr(a) = &value else {545 <Self as Typed>::TYPE.check(&value)?;546 unreachable!()547 };548 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {549 return Ok(bytes.0.as_slice().into());550 }551 <Self as Typed>::TYPE.check(&value)?;552 // Any::downcast_ref::<ByteArray>(&a);553 let mut out = Vec::with_capacity(a.len());554 for e in a.iter() {555 let r = e?;556 out.push(u8::from_untyped(r)?);557 }558 Ok(out.as_slice().into())559 }560}561562pub struct M1;563impl Typed for M1 {564 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));565}566impl IntoUntyped for M1 {567 fn into_untyped(_: Self) -> Result<Val> {568 Ok(Val::Num(NumValue::new(-1.0).expect("finite")))569 }570}571impl FromUntyped for M1 {572 fn from_untyped(value: Val) -> Result<Self> {573 <Self as Typed>::TYPE.check(&value)?;574 Ok(Self)575 }576}577578macro_rules! decl_either {579 ($($name: ident, $($id: ident)*);*) => {$(580 #[derive(Clone)]581 pub enum $name<$($id),*> {582 $($id($id)),*583 }584 impl<$($id),*> Typed for $name<$($id),*>585 where586 $($id: Typed,)*587 {588 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);589 }590 impl<$($id),*> IntoUntyped for $name<$($id),*>591 where592 $($id: Typed + IntoUntyped,)*593 {594 fn into_untyped(value: Self) -> Result<Val> {595 match value {$(596 $name::$id(v) => $id::into_untyped(v)597 ),*}598 }599 }600601 impl<$($id),*> FromUntyped for $name<$($id),*>602 where603 $($id: Typed + FromUntyped,)*604 {605 fn from_untyped(value: Val) -> Result<Self> {606 $(607 if $id::TYPE.check(&value).is_ok() {608 $id::from_untyped(value).map(Self::$id)609 } else610 )* {611 <Self as Typed>::TYPE.check(&value)?;612 unreachable!()613 }614 }615 }616 )*}617}618decl_either!(619 Either1, A;620 Either2, A B;621 Either3, A B C;622 Either4, A B C D;623 Either5, A B C D E;624 Either6, A B C D E F;625 Either7, A B C D E F G626);627#[macro_export]628macro_rules! Either {629 ($a:ty) => {$crate::typed::Either1<$a>};630 ($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};631 ($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};632 ($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};633 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};634 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};635 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};636}637pub use Either;638639pub type MyType = Either![u32, f64, String];640641impl Typed for ArrValue {642 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);643}644impl IntoUntyped for ArrValue {645 fn into_untyped(value: Self) -> Result<Val> {646 Ok(Val::Arr(value))647 }648}649impl FromUntyped for ArrValue {650 fn from_untyped(value: Val) -> Result<Self> {651 <Self as Typed>::TYPE.check(&value)?;652 match value {653 Val::Arr(a) => Ok(a),654 _ => unreachable!(),655 }656 }657}658659impl Typed for FuncVal {660 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);661}662impl IntoUntyped for FuncVal {663 fn into_untyped(value: Self) -> Result<Val> {664 Ok(Val::Func(value))665 }666}667impl FromUntyped for FuncVal {668 fn from_untyped(value: Val) -> Result<Self> {669 <Self as Typed>::TYPE.check(&value)?;670 match value {671 Val::Func(a) => Ok(a),672 _ => unreachable!(),673 }674 }675}676677impl Typed for ObjValue {678 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);679}680impl IntoUntyped for ObjValue {681 fn into_untyped(value: Self) -> Result<Val> {682 Ok(Val::Obj(value))683 }684}685impl FromUntyped for ObjValue {686 fn from_untyped(value: Val) -> Result<Self> {687 <Self as Typed>::TYPE.check(&value)?;688 match value {689 Val::Obj(a) => Ok(a),690 _ => unreachable!(),691 }692 }693}694695impl Typed for bool {696 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);697}698impl IntoUntyped for bool {699 fn into_untyped(value: Self) -> Result<Val> {700 Ok(Val::Bool(value))701 }702}703impl FromUntyped for bool {704 fn from_untyped(value: Val) -> Result<Self> {705 <Self as Typed>::TYPE.check(&value)?;706 match value {707 Val::Bool(a) => Ok(a),708 _ => unreachable!(),709 }710 }711}712713impl Typed for IndexableVal {714 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[715 &ComplexValType::Simple(ValType::Arr),716 &ComplexValType::Simple(ValType::Str),717 ]);718}719impl IntoUntyped for IndexableVal {720 fn into_untyped(value: Self) -> Result<Val> {721 match value {722 Self::Str(s) => Ok(Val::string(s)),723 Self::Arr(a) => Ok(Val::Arr(a)),724 }725 }726}727impl FromUntyped for IndexableVal {728 fn from_untyped(value: Val) -> Result<Self> {729 <Self as Typed>::TYPE.check(&value)?;730 value.into_indexable()731 }732}733734pub struct Null;735impl Typed for Null {736 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);737}738impl IntoUntyped for Null {739 fn into_untyped(_: Self) -> Result<Val> {740 Ok(Val::Null)741 }742}743impl FromUntyped for Null {744 fn from_untyped(value: Val) -> Result<Self> {745 <Self as Typed>::TYPE.check(&value)?;746 Ok(Self)747 }748}749750impl<T> Typed for Option<T>751where752 T: Typed,753{754 const TYPE: &'static ComplexValType =755 &ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);756}757impl<T> IntoUntyped for Option<T>758where759 T: Typed + IntoUntyped,760{761 fn into_untyped(typed: Self) -> Result<Val> {762 typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))763 }764}765impl<T> FromUntyped for Option<T>766where767 T: Typed + FromUntyped,768{769 fn from_untyped(untyped: Val) -> Result<Self> {770 if matches!(untyped, Val::Null) {771 Ok(None)772 } else {773 T::from_untyped(untyped).map(Some)774 }775 }776}777778impl Typed for NumValue {779 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);780}781impl IntoUntyped for NumValue {782 fn into_untyped(typed: Self) -> Result<Val> {783 Ok(Val::Num(typed))784 }785}786impl FromUntyped for NumValue {787 fn from_untyped(untyped: Val) -> Result<Self> {788 Self::TYPE.check(&untyped)?;789 match untyped {790 Val::Num(v) => Ok(v),791 _ => unreachable!(),792 }793 }794}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
];