-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Add lint to suggest as_chunks over chunks_exact with constant #16002
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rommeld
wants to merge
23
commits into
rust-lang:master
Choose a base branch
from
rommeld:suggest-as-chunks-over-chunks-exact
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 4a4c955
Fix pass value instead of reference
rommeld d332ec5
Switched to symbols instead of using strings
rommeld 610acda
Added suggestions and changes from review
rommeld 632e37b
Updated CHANGELOG.md via
rommeld bc1d010
Reduced error message verbosity
rommeld 1d99b91
Added check for types that can be adjusted as slices
rommeld 2731771
Moved Rust version check and removed
rommeld 7082eef
Added lint suggestion
rommeld dc9fa9d
Reduced highlighting to method call for better understanding
rommeld afaf92b
Moved method to lints which handle methods whose receivers and argume…
rommeld dfd8065
Changed suggestion to return iterator instead of tuple
rommeld 3cfa99a
Moved version check after cheaper checks is slice and constant evalua…
rommeld 94181ab
Changed suggestion to just consider method call
rommeld 370d0ae
Changed linting suggestion span_lint_and_then to span_lint_and_sugg
rommeld 24798af
Added skipping multi-line test from cargo dev fmt
rommeld 5e05b1d
Improved lint by only suggesting fix when method not stored in variable
rommeld ae2cb12
Fixed missing curly brakets
rommeld 43a7a72
Deleted comment from lint declaration
rommeld 64aae82
Moved unfixable tests to separate file because ui_test otherwise woul…
rommeld 83e0039
Swapped plain with so help function is visually attached to method
rommeld 1e276d7
Fixed wrongly replaced comment in lint declaration
rommeld c50ccf8
Fixed one last typo in the lint declaration comment
rommeld File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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) returnsChunksExact, and apart from being an iterator, that struct also has aremaindermethod, which returns, well, the remainder. But since we replace the wholechunks_exactcall withas_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_exactis 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:would be turned into something like this:
But that'd be pretty complicated, so I suggest we do the following instead:
.chunks_exactis stored into a variable,(1) can be done as follows:
Here's how that would probably look in your code:
Suggestion
Footnotes
foreshadowing :P ↩
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
ChunksExactin 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_chunksis 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:
To do that, you'll need to:
patfromLetStmtpatis 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 justPatKind::Binding. Therefore, match on that and extractident-- the identifier (=name) of the variablediag.span_note(after emitting the help message)There was a problem hiding this comment.
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-rustfixthing you'll often see in such files, but you don't need to worry about that for now)There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in 64aae82
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.