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.rsdiffbeforeafterboth1#[cfg(feature = "explaining-traces")]2use std::cell::RefCell;3use std::{4 any::Any,5 path::{Path, PathBuf},6};78use jrsonnet_gcmodule::Trace;9use jrsonnet_ir::CodeLocation;10#[cfg(feature = "explaining-traces")]11use jrsonnet_ir::Span;1213use crate::{Error, error::ErrorKind};1415/// The way paths should be displayed16#[derive(Clone, Trace)]17pub enum PathResolver {18 /// Only filename19 FileName,20 /// Absolute path21 Absolute,22 /// Path relative to base directory23 Relative(PathBuf),24}2526impl PathResolver {27 /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure28 pub fn new_cwd_fallback() -> Self {29 std::env::current_dir().map_or(Self::Absolute, Self::Relative)30 }31 pub fn resolve(&self, from: &Path) -> String {32 match self {33 Self::FileName => from34 .file_name()35 .expect("file name exists")36 .to_string_lossy()37 .into_owned(),38 Self::Absolute => from.to_string_lossy().into_owned(),39 Self::Relative(base) => {40 if from.is_relative() {41 return from.to_string_lossy().into_owned();42 }43 pathdiff::diff_paths(from, base)44 .expect("base is absolute")45 .to_string_lossy()46 .into_owned()47 }48 }49 }50}5152/// Implements pretty-printing of traces53#[allow(clippy::module_name_repetitions)]54pub trait TraceFormat: Trace {55 fn write_trace(56 &self,57 out: &mut dyn std::fmt::Write,58 error: &Error,59 ) -> Result<(), std::fmt::Error>;60 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {61 let mut out = String::new();62 self.write_trace(&mut out, error)?;63 Ok(out)64 }65 fn as_any(&self) -> &dyn Any;66 fn as_any_mut(&mut self) -> &mut dyn Any;67}6869fn print_code_location(70 out: &mut impl std::fmt::Write,71 start: &CodeLocation,72 end: &CodeLocation,73) -> Result<(), std::fmt::Error> {74 if start.line == end.line {75 if start.column == end.column {76 write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;77 } else {78 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;79 }80 } else {81 write!(82 out,83 "{}:{}-{}:{}",84 start.line,85 end.column.saturating_sub(1),86 start.line,87 end.column88 )?;89 }90 Ok(())91}9293/// vanilla-like jsonnet formatting94#[derive(Trace)]95pub struct CompactFormat {96 pub resolver: PathResolver,97 pub max_trace: usize,98 pub padding: usize,99}100impl Default for CompactFormat {101 fn default() -> Self {102 Self {103 resolver: PathResolver::Absolute,104 max_trace: 20,105 padding: 4,106 }107 }108}109110impl TraceFormat for CompactFormat {111 fn write_trace(112 &self,113 out: &mut dyn std::fmt::Write,114 error: &Error,115 ) -> Result<(), std::fmt::Error> {116 write!(out, "{}", error.error())?;117 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {118 use std::fmt::Write;119120 writeln!(out)?;121 let mut n = path.source_path().path().map_or_else(122 || path.source_path().to_string(),123 |r| self.resolver.resolve(r),124 );125 let mut offset = error.location.0 as usize;126 let is_eof = if offset >= path.code().len() {127 offset = path.code().len().saturating_sub(1);128 true129 } else {130 false131 };132 let mut location = path133 .map_source_locations(&[offset as u32])134 .into_iter()135 .next()136 .unwrap();137 if is_eof {138 location.column += 1;139 }140141 write!(n, ":").unwrap();142 print_code_location(&mut n, &location, &location).unwrap();143 write!(out, "{:<p$}{n}", "", p = self.padding)?;144 }145 let file_names = error146 .trace()147 .0148 .iter()149 .map(|el| &el.location)150 .map(|location| {151 use std::fmt::Write;152 #[allow(clippy::option_if_let_else)]153 if let Some(location) = location {154 let mut resolved_path = match location.0.source_path().path() {155 Some(r) => self.resolver.resolve(r),156 None => location.0.source_path().to_string(),157 };158 // TODO: Process all trace elements first159 let location = location.0.map_source_locations(&[location.1, location.2]);160 write!(resolved_path, ":").unwrap();161 print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();162 write!(resolved_path, ":").unwrap();163 Some(resolved_path)164 } else {165 None166 }167 })168 .collect::<Vec<_>>();169 let align = file_names170 .iter()171 .flatten()172 .map(String::len)173 .max()174 .unwrap_or(0);175 for (el, file) in error.trace().0.iter().zip(file_names) {176 writeln!(out)?;177 if let Some(file) = file {178 write!(179 out,180 "{:<p$}{:<w$} {}",181 "",182 file,183 el.desc,184 p = self.padding,185 w = align186 )?;187 } else {188 write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;189 }190 }191 Ok(())192 }193194 fn as_any(&self) -> &dyn Any {195 self196 }197198 fn as_any_mut(&mut self) -> &mut dyn Any {199 self200 }201}202203#[derive(Trace)]204pub struct JsFormat {205 pub max_trace: usize,206}207impl TraceFormat for JsFormat {208 fn write_trace(209 &self,210 out: &mut dyn std::fmt::Write,211 error: &Error,212 ) -> Result<(), std::fmt::Error> {213 write!(out, "{}", error.error())?;214 for item in &error.trace().0 {215 writeln!(out)?;216 let desc = &item.desc;217 if let Some(source) = &item.location {218 let start_end = source.0.map_source_locations(&[source.1, source.2]);219 let resolved_path = source.0.source_path().path().map_or_else(220 || source.0.source_path().to_string(),221 |r| r.display().to_string(),222 );223224 write!(225 out,226 " at {} ({}:{}:{})",227 desc, resolved_path, start_end[0].line, start_end[0].column,228 )?;229 } else {230 write!(out, " during {desc}")?;231 }232 }233 Ok(())234 }235236 fn as_any(&self) -> &dyn Any {237 self238 }239240 fn as_any_mut(&mut self) -> &mut dyn Any {241 self242 }243}244245#[cfg(feature = "explaining-traces")]246#[derive(Trace)]247pub struct HiDocFormat {248 pub resolver: PathResolver,249 pub max_trace: usize,250}251#[cfg(feature = "explaining-traces")]252impl TraceFormat for HiDocFormat {253 fn write_trace(254 &self,255 out: &mut dyn std::fmt::Write,256 error: &Error,257 ) -> Result<(), std::fmt::Error> {258 struct ResetData {259 loc: Span,260 }261 use hi_doc::{Formatting, SnippetBuilder, Text, source_to_ansi};262263 write!(out, "{}", error.error())?;264 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {265 writeln!(out)?;266 let mut offset = error.location;267 // To inclusive range268 if offset.1 > offset.0 {269 offset.1 -= 1;270 }271 let mut builder = SnippetBuilder::new(path.code());272 builder273 .error(Text::fragment("syntax error", Formatting::default()))274 .range(offset.0 as usize..=offset.1 as usize)275 .build();276 let source = builder.build();277 let ansi = source_to_ansi(&source);278 write!(out, "{ansi}")?;279 }280 let trace = &error.trace();281 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);282 let mut last_location: Option<Span> = None;283 let mut flush_builder = |data: Option<ResetData>| {284 use std::fmt::Write;285 let mut out = String::new();286 let location_changed = if let Some(ResetData { loc }) = &data {287 if last_location.as_ref().map(|l| l.0.code()) != Some(loc.0.code()) {288 true289 } else if let (Some(last), new) = (&last_location, loc) {290 // Reverse condition if traceback291 last.1 > new.1 || last.2 > new.2292 } else {293 false294 }295 } else {296 true297 };298 if location_changed {299 if let Some(builder) = snippet_builder.borrow_mut().take() {300 let rendered = builder.build();301 let ansi = source_to_ansi(&rendered);302 if let Some(loc) = &last_location {303 let _ = writeln!(out, "...at {}", loc.0.source_path());304 }305 let _ = write!(out, "{}", ansi.trim_end());306 }307 last_location = None;308309 if let Some(ResetData { loc }) = data {310 *snippet_builder.borrow_mut() = Some(SnippetBuilder::new(loc.0.code()));311 last_location = Some(loc);312 }313 }314 if out.is_empty() {315 return None;316 }317 Some(out)318 };319 for item in &trace.0 {320 let desc = &item.desc;321 if let Some(source) = &item.location {322 if let Some(flushed) = flush_builder(Some(ResetData {323 loc: source.clone(),324 })) {325 writeln!(out)?;326 write!(out, "{flushed}")?;327 }328 let mut builder = snippet_builder.borrow_mut();329 let builder = builder.as_mut().unwrap();330 builder331 .note(Text::fragment(desc, Formatting::default()))332 .range(source.1 as usize..=(source.2 as usize - 1).max(source.1 as usize))333 .build();334 } else {335 if let Some(flushed) = flush_builder(None) {336 writeln!(out)?;337 write!(out, "{flushed}")?;338 }339 writeln!(out)?;340 write!(out, " {desc}")?;341 }342 }343344 if let Some(flushed) = flush_builder(None) {345 writeln!(out)?;346 write!(out, "{flushed}")?;347 }348 Ok(())349 }350351 fn as_any(&self) -> &dyn Any {352 self353 }354355 fn as_any_mut(&mut self) -> &mut dyn Any {356 self357 }358}1#[cfg(feature = "explaining-traces")]2use std::cell::RefCell;3use std::{4 any::Any,5 path::{Path, PathBuf},6};78use jrsonnet_gcmodule::Trace;9use jrsonnet_ir::CodeLocation;10#[cfg(feature = "explaining-traces")]11use jrsonnet_ir::Span;1213use crate::{Error, error::ErrorKind};1415/// The way paths should be displayed16#[derive(Clone, Trace)]17pub enum PathResolver {18 /// Only filename19 FileName,20 /// Absolute path21 Absolute,22 /// Path relative to base directory23 Relative(PathBuf),24}2526impl PathResolver {27 /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure28 pub fn new_cwd_fallback() -> Self {29 std::env::current_dir().map_or(Self::Absolute, Self::Relative)30 }31 pub fn resolve(&self, from: &Path) -> String {32 match self {33 Self::FileName => from34 .file_name()35 .expect("file name exists")36 .to_string_lossy()37 .into_owned(),38 Self::Absolute => from.to_string_lossy().into_owned(),39 Self::Relative(base) => {40 if from.is_relative() {41 return from.to_string_lossy().into_owned();42 }43 pathdiff::diff_paths(from, base)44 .expect("base is absolute")45 .to_string_lossy()46 .into_owned()47 }48 }49 }50}5152/// Implements pretty-printing of traces53#[allow(clippy::module_name_repetitions)]54pub trait TraceFormat: Trace {55 fn write_trace(56 &self,57 out: &mut dyn std::fmt::Write,58 error: &Error,59 ) -> Result<(), std::fmt::Error>;60 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {61 let mut out = String::new();62 self.write_trace(&mut out, error)?;63 Ok(out)64 }65 fn as_any(&self) -> &dyn Any;66 fn as_any_mut(&mut self) -> &mut dyn Any;67}6869fn print_code_location(70 out: &mut impl std::fmt::Write,71 start: &CodeLocation,72 end: &CodeLocation,73) -> Result<(), std::fmt::Error> {74 if start.line == end.line {75 if start.column == end.column {76 write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;77 } else {78 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;79 }80 } else {81 write!(82 out,83 "{}:{}-{}:{}",84 start.line,85 end.column.saturating_sub(1),86 start.line,87 end.column88 )?;89 }90 Ok(())91}9293/// vanilla-like jsonnet formatting94#[derive(Trace)]95pub struct CompactFormat {96 pub resolver: PathResolver,97 pub max_trace: usize,98 pub padding: usize,99}100impl Default for CompactFormat {101 fn default() -> Self {102 Self {103 resolver: PathResolver::Absolute,104 max_trace: 20,105 padding: 4,106 }107 }108}109110impl TraceFormat for CompactFormat {111 fn write_trace(112 &self,113 out: &mut dyn std::fmt::Write,114 error: &Error,115 ) -> Result<(), std::fmt::Error> {116 write!(out, "{}", error.error())?;117 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {118 use std::fmt::Write;119120 writeln!(out)?;121 let mut n = path.source_path().path().map_or_else(122 || path.source_path().to_string(),123 |r| self.resolver.resolve(r),124 );125 let mut offset = error.location.0 as usize;126 let is_eof = if offset >= path.code().len() {127 offset = path.code().len().saturating_sub(1);128 true129 } else {130 false131 };132 #[expect(clippy::cast_possible_truncation, reason = "code is limited by 4gb")]133 let mut location = path134 .map_source_locations(&[offset as u32])135 .into_iter()136 .next()137 .unwrap();138 if is_eof {139 location.column += 1;140 }141142 write!(n, ":").unwrap();143 print_code_location(&mut n, &location, &location).unwrap();144 write!(out, "{:<p$}{n}", "", p = self.padding)?;145 }146 let file_names = error147 .trace()148 .0149 .iter()150 .map(|el| &el.location)151 .map(|location| {152 use std::fmt::Write;153 #[allow(clippy::option_if_let_else)]154 if let Some(location) = location {155 let mut resolved_path = match location.0.source_path().path() {156 Some(r) => self.resolver.resolve(r),157 None => location.0.source_path().to_string(),158 };159 // TODO: Process all trace elements first160 let location = location.0.map_source_locations(&[location.1, location.2]);161 write!(resolved_path, ":").unwrap();162 print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();163 write!(resolved_path, ":").unwrap();164 Some(resolved_path)165 } else {166 None167 }168 })169 .collect::<Vec<_>>();170 let align = file_names171 .iter()172 .flatten()173 .map(String::len)174 .max()175 .unwrap_or(0);176 for (el, file) in error.trace().0.iter().zip(file_names) {177 writeln!(out)?;178 if let Some(file) = file {179 write!(180 out,181 "{:<p$}{:<w$} {}",182 "",183 file,184 el.desc,185 p = self.padding,186 w = align187 )?;188 } else {189 write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;190 }191 }192 Ok(())193 }194195 fn as_any(&self) -> &dyn Any {196 self197 }198199 fn as_any_mut(&mut self) -> &mut dyn Any {200 self201 }202}203204#[derive(Trace)]205pub struct JsFormat {206 pub max_trace: usize,207}208impl TraceFormat for JsFormat {209 fn write_trace(210 &self,211 out: &mut dyn std::fmt::Write,212 error: &Error,213 ) -> Result<(), std::fmt::Error> {214 write!(out, "{}", error.error())?;215 for item in &error.trace().0 {216 writeln!(out)?;217 let desc = &item.desc;218 if let Some(source) = &item.location {219 let start_end = source.0.map_source_locations(&[source.1, source.2]);220 let resolved_path = source.0.source_path().path().map_or_else(221 || source.0.source_path().to_string(),222 |r| r.display().to_string(),223 );224225 write!(226 out,227 " at {} ({}:{}:{})",228 desc, resolved_path, start_end[0].line, start_end[0].column,229 )?;230 } else {231 write!(out, " during {desc}")?;232 }233 }234 Ok(())235 }236237 fn as_any(&self) -> &dyn Any {238 self239 }240241 fn as_any_mut(&mut self) -> &mut dyn Any {242 self243 }244}245246#[cfg(feature = "explaining-traces")]247#[derive(Trace)]248pub struct HiDocFormat {249 pub resolver: PathResolver,250 pub max_trace: usize,251}252#[cfg(feature = "explaining-traces")]253impl TraceFormat for HiDocFormat {254 fn write_trace(255 &self,256 out: &mut dyn std::fmt::Write,257 error: &Error,258 ) -> Result<(), std::fmt::Error> {259 struct ResetData {260 loc: Span,261 }262 use hi_doc::{Formatting, SnippetBuilder, Text, source_to_ansi};263264 write!(out, "{}", error.error())?;265 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {266 writeln!(out)?;267 let mut offset = error.location;268 // To inclusive range269 if offset.1 > offset.0 {270 offset.1 -= 1;271 }272 let mut builder = SnippetBuilder::new(path.code());273 builder274 .error(Text::fragment("syntax error", Formatting::default()))275 .range(offset.0 as usize..=offset.1 as usize)276 .build();277 let source = builder.build();278 let ansi = source_to_ansi(&source);279 write!(out, "{ansi}")?;280 }281 let trace = &error.trace();282 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);283 let mut last_location: Option<Span> = None;284 let mut flush_builder = |data: Option<ResetData>| {285 use std::fmt::Write;286 let mut out = String::new();287 let location_changed = if let Some(ResetData { loc }) = &data {288 if last_location.as_ref().map(|l| l.0.code()) != Some(loc.0.code()) {289 true290 } else if let (Some(last), new) = (&last_location, loc) {291 // Reverse condition if traceback292 last.1 > new.1 || last.2 > new.2293 } else {294 false295 }296 } else {297 true298 };299 if location_changed {300 if let Some(builder) = snippet_builder.borrow_mut().take() {301 let rendered = builder.build();302 let ansi = source_to_ansi(&rendered);303 if let Some(loc) = &last_location {304 let _ = writeln!(out, "...at {}", loc.0.source_path());305 }306 let _ = write!(out, "{}", ansi.trim_end());307 }308 last_location = None;309310 if let Some(ResetData { loc }) = data {311 *snippet_builder.borrow_mut() = Some(SnippetBuilder::new(loc.0.code()));312 last_location = Some(loc);313 }314 }315 if out.is_empty() {316 return None;317 }318 Some(out)319 };320 for item in &trace.0 {321 let desc = &item.desc;322 if let Some(source) = &item.location {323 if let Some(flushed) = flush_builder(Some(ResetData {324 loc: source.clone(),325 })) {326 writeln!(out)?;327 write!(out, "{flushed}")?;328 }329 let mut builder = snippet_builder.borrow_mut();330 let builder = builder.as_mut().unwrap();331 builder332 .note(Text::fragment(desc, Formatting::default()))333 .range(source.1 as usize..=(source.2 as usize - 1).max(source.1 as usize))334 .build();335 } else {336 if let Some(flushed) = flush_builder(None) {337 writeln!(out)?;338 write!(out, "{flushed}")?;339 }340 writeln!(out)?;341 write!(out, " {desc}")?;342 }343 }344345 if let Some(flushed) = flush_builder(None) {346 writeln!(out)?;347 write!(out, "{flushed}")?;348 }349 Ok(())350 }351352 fn as_any(&self) -> &dyn Any {353 self354 }355356 fn as_any_mut(&mut self) -> &mut dyn Any {357 self358 }359}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
];