Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3d3d2be
Add lint to suggest as_chunks over chunks_exact with constant
rommeld Nov 1, 2025
4a4c955
Fix pass value instead of reference
rommeld Nov 1, 2025
d332ec5
Switched to symbols instead of using strings
rommeld Nov 1, 2025
610acda
Added suggestions and changes from review
rommeld Nov 4, 2025
632e37b
Updated CHANGELOG.md via
rommeld Nov 4, 2025
bc1d010
Reduced error message verbosity
rommeld Nov 4, 2025
1d99b91
Added check for types that can be adjusted as slices
rommeld Nov 4, 2025
2731771
Moved Rust version check and removed
rommeld Nov 4, 2025
7082eef
Added lint suggestion
rommeld Nov 7, 2025
dc9fa9d
Reduced highlighting to method call for better understanding
rommeld Nov 7, 2025
afaf92b
Moved method to lints which handle methods whose receivers and argume…
rommeld Nov 7, 2025
dfd8065
Changed suggestion to return iterator instead of tuple
rommeld Nov 7, 2025
3cfa99a
Moved version check after cheaper checks is slice and constant evalua…
rommeld Nov 7, 2025
94181ab
Changed suggestion to just consider method call
rommeld Nov 7, 2025
370d0ae
Changed linting suggestion span_lint_and_then to span_lint_and_sugg
rommeld Nov 8, 2025
24798af
Added skipping multi-line test from cargo dev fmt
rommeld Nov 8, 2025
5e05b1d
Improved lint by only suggesting fix when method not stored in variable
rommeld Nov 8, 2025
ae2cb12
Fixed missing curly brakets
rommeld Nov 8, 2025
43a7a72
Deleted comment from lint declaration
rommeld Nov 8, 2025
64aae82
Moved unfixable tests to separate file because ui_test otherwise woul…
rommeld Nov 8, 2025
83e0039
Swapped plain with so help function is visually attached to method
rommeld Nov 8, 2025
1e276d7
Fixed wrongly replaced comment in lint declaration
rommeld Nov 8, 2025
c50ccf8
Fixed one last typo in the lint declaration comment
rommeld Nov 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6252,6 +6252,7 @@ Released 2018-09-13
[`chars_last_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_last_cmp
[`chars_next_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_next_cmp
[`checked_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions
[`chunks_exact_with_const_size`]: https://rust-lang.github.io/rust-clippy/master/index.html#chunks_exact_with_const_size
[`clear_with_drain`]: https://rust-lang.github.io/rust-clippy/master/index.html#clear_with_drain
[`clone_double_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_double_ref
[`clone_on_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_copy
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[
crate::methods::CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS_INFO,
crate::methods::CHARS_LAST_CMP_INFO,
crate::methods::CHARS_NEXT_CMP_INFO,
crate::methods::CHUNKS_EXACT_WITH_CONST_SIZE_INFO,
crate::methods::CLEAR_WITH_DRAIN_INFO,
crate::methods::CLONED_INSTEAD_OF_COPIED_INFO,
crate::methods::CLONE_ON_COPY_INFO,
Expand Down
58 changes: 58 additions & 0 deletions clippy_lints/src/methods/chunks_exact_with_const_size.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::sym;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_span::{Span, Symbol};

use super::CHUNKS_EXACT_WITH_CONST_SIZE;

pub(super) fn check(
cx: &LateContext<'_>,
recv: &Expr<'_>,
arg: &Expr<'_>,
call_span: Span,
method_name: Symbol,
msrv: Msrv,
) {
// Check if receiver is slice-like
if !cx.typeck_results().expr_ty_adjusted(recv).peel_refs().is_slice() {
return;
}

// Check if argument is a constant
let constant_eval = ConstEvalCtxt::new(cx);
if let Some(Constant::Int(_)) = constant_eval.eval(arg) {
// Check for Rust version - only check after we know we would emit a lint
if !msrv.meets(cx, msrvs::AS_CHUNKS) {
return;
}

// Determine the suggested method name
let suggestion_method = if method_name == sym::chunks_exact_mut {
"as_chunks_mut"
} else {
"as_chunks"
};

// Build the suggestion with proper applicability tracking
let mut applicability = Applicability::MachineApplicable;
let arg_str = snippet_with_applicability(cx, arg.span, "_", &mut applicability);

// Suggestion replaces just "chunks_exact(N)" with "as_chunks::<N>().0.iter()"
let suggestion = format!("{suggestion_method}::<{arg_str}>().0.iter()");

span_lint_and_sugg(
cx,
CHUNKS_EXACT_WITH_CONST_SIZE,
call_span,
format!("using `{method_name}` with a constant chunk size"),
"consider using `as_chunks` instead",
suggestion,
applicability,
);
}
Copy link
Contributor

@ada4a ada4a Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As Lintcheck shows in #16002 (comment), here's one bigger remaining1 problem: chunks_exact(_mut) (I'll use the immutable version from here on, for brevity) returns ChunksExact, and apart from being an iterator, that struct also has a remainder method, which returns, well, the remainder. But since we replace the whole chunks_exact call with as_chunks().0.iter(), we lose access to that remainder.

In theory, we could make the lint a lot smarter, so that when it sees that the chunk_exact is stored into a variable, and is then used both as an iterator and to get the remainder, we adjust both calls correctly. So this example from Lintcheck:

let chunk_iter = bytes.chunks_exact(CHUNK_SIZE);
let remainder_chunk = chunk_iter.remainder();
for chunk in chunk_iter {
    /* ... */
}

would be turned into something like this:

let chunk_iter = bytes.as_chunks::<CHUNK_SIZE>();
let remainder_chunk = chunk_iter.1;
for chunk in chunk_iter.0.iter() {
    /* ... */
}

But that'd be pretty complicated, so I suggest we do the following instead:

  1. If we see that the call to .chunks_exact is stored into a variable,
  2. don't offer a suggestion (as it might not be correct)
  3. but instead give a help message, something like:
    let chunk_iter = bytes.chunks_exact(CHUNK_SIZE);
                           ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.as_chunks::<CHUNK_SIZE>() instead`

(1) can be done as follows:

if let Node::LetStmt(_) = cx.tcx.parent_hir_node(expr.hir_id) {
    /* only leave a help message, not a suggestion */
}

Here's how that would probably look in your code:

Suggestion

Suggested change
// Suggestion replaces just "chunks_exact(N)" with "as_chunks::<N>().0.iter()"
let suggestion = format!("{suggestion_method}::<{arg_str}>().0.iter()");
span_lint_and_sugg(
cx,
CHUNKS_EXACT_WITH_CONST_SIZE,
call_span,
format!("using `{method_name}` with a constant chunk size"),
"consider using `as_chunks` instead",
suggestion,
applicability,
);
}
let as_chunks = format_args!("{suggestion_method}::<{arg_str}>()");
span_lint_and_then(
cx,
CHUNKS_EXACT_WITH_CONST_SIZE,
call_span,
format!("using `{method_name}` with a constant chunk size"),
|diag| {
if let Node::LetStmt(_) = cx.tcx.parent_hir_node(expr.hir_id) {
// The `ChunksExact(Mut)` struct is stored for later -- this likely means that the user intends to not only use it as an iterator,
// but also access the remainder using `(into_)remainder`. For now, just give a help message in this case.
// TODO: give a suggestion that replaces this:
// ```
// let chunk_iter = bytes.chunks_exact(CHUNK_SIZE);
// let remainder_chunk = chunk_iter.remainder();
// for chunk in chunk_iter {
// /* ... */
// }
// ```
// with this:
// ```
// let chunk_iter = bytes.as_chunks::<CHUNK_SIZE>();
// let remainder_chunk = chunk_iter.1;
// for chunk in chunk_iter.0.iter() {
// /* ... */
// }
// ```
diag.span_help(
call_span,
format!("consider using `{as_chunks}` instead"),
);
} else {
diag.span_suggestion(
call_span,
"consider using `as_chunks` instead",
// Suggestion replaces just "chunks_exact(N)" with "as_chunks::<N>().0.iter()"
format!("{as_chunks}.0.iter()"),
applicability,
);
}
}
);
}

Footnotes

  1. foreshadowing :P

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might get that totally wrong but isn't that in opposition to your comment above? Because I think it is useful to have the suggestion the possibility to access to the tuple.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I wouldn't want to suggest that in here is that, again, I think that if the user stores the ChunksExact in a variable, then they probably want to access the remainder -- and suggesting .0.iter() would go against that. If they do want to use the variable just as an iterator, they can of course add .0.iter() themselves, but that scenario would be rather rare I think.

In general, the return type of as_chunks is pretty self-explanatory imo -- it's a tuple, and a quick glance at the API docs tells you what each half stands for, so I imagine the user will be able to figure that out...

But if we do want to be extra helpful, we could emit an additional note: given the example code from above, it could look like this:

note: you can access the chunks using `chunk_iter.0.iter()`, and the remainder using `chunk_iter.1`

To do that, you'll need to:

  1. extract the pat from LetStmt
  2. pat is an arbitrary pattern, since the left-hand side of a let-statement could in theory be an arbitrary pattern (e.g. destructuring), but we can assume it's just PatKind::Binding. Therefore, match on that and extract ident -- the identifier (=name) of the variable
  3. construct the note message, and emit it using diag.span_note (after emitting the help message)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done!:)

Oh, but there's a caveat I forgot about and you no doubt noticed – since in one of the test cases we now only give a help message and not a suggestion, ui_test (the UI test library we're using) will fail, as even after applying all the suggestions, the test file still raises warnings, precisely because help-only cases haven't actually changed.

Because of this, such test cases are placed into a separate file, usually called <lint_name>_unfixable.rs (there's also this //@no-rustfix thing you'll often see in such files, but you don't need to worry about that for now)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was wondering why the tests were failing. Luckily, I do not get frustrated that easily might have taken me a couple of attempts before I would have noticed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 64aae82

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Btw, could you please add the comment from the suggestion (of some version of it, as you please) to your code? Having a TODO will let an interested contributor pick it up in the future

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to use your comment as it is more helpful and provides transparency next possible steps.

}
31 changes: 31 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod chars_last_cmp;
mod chars_last_cmp_with_unwrap;
mod chars_next_cmp;
mod chars_next_cmp_with_unwrap;
mod chunks_exact_with_const_size;
mod clear_with_drain;
mod clone_on_copy;
mod clone_on_ref_ptr;
Expand Down Expand Up @@ -2087,6 +2088,32 @@ declare_clippy_lint! {
"replace `.bytes().nth()` with `.as_bytes().get()`"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `chunks_exact` or `chunks_exact_mut` with a constant chunk size.
///
/// ### Why is this bad?
/// `as_chunks` provides better ergonomics and type safety by returning arrays instead of slices.
/// It was stabilized in Rust 1.88.
///
/// ### Example
/// ```no_run
/// let slice = [1, 2, 3, 4, 5, 6];
/// let mut it = slice.chunks_exact(2);
/// for chunk in it {}
/// ```
/// Use instead:
/// ```no_run
/// let slice = [1, 2, 3, 4, 5, 6];
/// let (chunks, remainder) = slice.as_chunks::<2>();
/// for chunk in chunks {}
/// ```
#[clippy::version = "1.93.0"]
pub CHUNKS_EXACT_WITH_CONST_SIZE,
style,
"using `chunks_exact` with constant when `as_chunks` is more ergonomic"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
Expand Down Expand Up @@ -4787,6 +4814,7 @@ impl_lint_pass!(Methods => [
ITER_NTH,
ITER_NTH_ZERO,
BYTES_NTH,
CHUNKS_EXACT_WITH_CONST_SIZE,
ITER_SKIP_NEXT,
GET_UNWRAP,
GET_LAST_WITH_LEN,
Expand Down Expand Up @@ -5043,6 +5071,9 @@ impl Methods {
_ => {},
}
},
(name @ (sym::chunks_exact | sym::chunks_exact_mut), [arg]) => {
chunks_exact_with_const_size::check(cx, recv, arg, call_span, name, self.msrv);
},
(sym::and_then, [arg]) => {
let biom_option_linted = bind_instead_of_map::check_and_then_some(cx, expr, recv, arg);
let biom_result_linted = bind_instead_of_map::check_and_then_ok(cx, expr, recv, arg);
Expand Down
2 changes: 1 addition & 1 deletion clippy_utils/src/msrvs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ macro_rules! msrv_aliases {

// names may refer to stabilized feature flags or library items
msrv_aliases! {
1,88,0 { LET_CHAINS }
1,88,0 { LET_CHAINS, AS_CHUNKS }
1,87,0 { OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF, INTEGER_SIGN_CAST }
1,85,0 { UINT_FLOAT_MIDPOINT, CONST_SIZE_OF_VAL }
1,84,0 { CONST_OPTION_AS_SLICE, MANUAL_DANGLING_PTR }
Expand Down
2 changes: 2 additions & 0 deletions clippy_utils/src/sym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ generate! {
checked_pow,
checked_rem_euclid,
checked_sub,
chunks_exact,
chunks_exact_mut,
clamp,
clippy_utils,
clone_into,
Expand Down
34 changes: 34 additions & 0 deletions tests/ui/chunks_exact_with_const_size.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![warn(clippy::chunks_exact_with_const_size)]
#![allow(unused)]
#![allow(clippy::iter_cloned_collect)]

fn main() {
let slice = [1, 2, 3, 4, 5, 6, 7, 8];

// Should trigger lint - literal constant
let result = slice.as_chunks::<4>().0.iter();
//~^ chunks_exact_with_const_size

// Should trigger lint - const value
const CHUNK_SIZE: usize = 4;
let result = slice.as_chunks::<CHUNK_SIZE>().0.iter();
//~^ chunks_exact_with_const_size

// Should NOT trigger - runtime value
let size = 4;
let mut it = slice.chunks_exact(size);
for chunk in it {}

// Should trigger lint - simple iteration
let result = slice.as_chunks::<3>().0.iter();
//~^ chunks_exact_with_const_size

// Should trigger - mutable variant
let mut arr = [1, 2, 3, 4, 5, 6, 7, 8];
let result = arr.as_chunks_mut::<4>().0.iter();
//~^ chunks_exact_with_const_size

// Should trigger - multiline expression
let result = slice.iter().copied().collect::<Vec<_>>().as_chunks::<2>().0.iter();
//~^ chunks_exact_with_const_size
}
34 changes: 34 additions & 0 deletions tests/ui/chunks_exact_with_const_size.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![warn(clippy::chunks_exact_with_const_size)]
#![allow(unused)]
#![allow(clippy::iter_cloned_collect)]

fn main() {
let slice = [1, 2, 3, 4, 5, 6, 7, 8];

// Should trigger lint - literal constant
let result = slice.chunks_exact(4);
//~^ chunks_exact_with_const_size

// Should trigger lint - const value
const CHUNK_SIZE: usize = 4;
let result = slice.chunks_exact(CHUNK_SIZE);
//~^ chunks_exact_with_const_size

// Should NOT trigger - runtime value
let size = 4;
let mut it = slice.chunks_exact(size);
for chunk in it {}

// Should trigger lint - simple iteration
let result = slice.chunks_exact(3);
//~^ chunks_exact_with_const_size

// Should trigger - mutable variant
let mut arr = [1, 2, 3, 4, 5, 6, 7, 8];
let result = arr.chunks_exact_mut(4);
//~^ chunks_exact_with_const_size

// Should trigger - multiline expression
let result = slice.iter().copied().collect::<Vec<_>>().chunks_exact(2);
//~^ chunks_exact_with_const_size
}
35 changes: 35 additions & 0 deletions tests/ui/chunks_exact_with_const_size.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
error: using `chunks_exact` with a constant chunk size
--> tests/ui/chunks_exact_with_const_size.rs:9:24
|
LL | let result = slice.chunks_exact(4);
| ^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<4>().0.iter()`
|
= note: `-D clippy::chunks-exact-with-const-size` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::chunks_exact_with_const_size)]`

error: using `chunks_exact` with a constant chunk size
--> tests/ui/chunks_exact_with_const_size.rs:14:24
|
LL | let result = slice.chunks_exact(CHUNK_SIZE);
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<CHUNK_SIZE>().0.iter()`

error: using `chunks_exact` with a constant chunk size
--> tests/ui/chunks_exact_with_const_size.rs:23:24
|
LL | let result = slice.chunks_exact(3);
| ^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<3>().0.iter()`

error: using `chunks_exact_mut` with a constant chunk size
--> tests/ui/chunks_exact_with_const_size.rs:28:22
|
LL | let result = arr.chunks_exact_mut(4);
| ^^^^^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks_mut::<4>().0.iter()`

error: using `chunks_exact` with a constant chunk size
--> tests/ui/chunks_exact_with_const_size.rs:32:60
|
LL | let result = slice.iter().copied().collect::<Vec<_>>().chunks_exact(2);
| ^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<2>().0.iter()`

error: aborting due to 5 previous errors

Empty file.