-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
30
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 all commits
Commits
Show all changes
30 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 3876101
Fix type check to require signle slice reference
rommeld 4c5a8f6
Fix unused import for ty
rommeld c970717
remove not needed comments
rommeld 21f02ba
Add tests for direct iteration and for array coercing to slice reference
rommeld e509232
Replace eval with is_const_evaluatable to reduce overhead during linting
rommeld 75e8019
Only suggest .iter() when chunks_exact is not in a for loop
rommeld 219eca3
Refact suggestion logic and make it more conservative and implement s…
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
110 changes: 110 additions & 0 deletions
110
clippy_lints/src/methods/chunks_exact_with_const_size.rs
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,110 @@ | ||
| use super::CHUNKS_EXACT_WITH_CONST_SIZE; | ||
| use clippy_utils::diagnostics::span_lint_and_then; | ||
| use clippy_utils::higher::ForLoop; | ||
| use clippy_utils::msrvs::{self, Msrv}; | ||
| use clippy_utils::source::snippet_with_context; | ||
| use clippy_utils::visitors::is_const_evaluatable; | ||
| use clippy_utils::{expr_use_ctxt, get_parent_expr, sym}; | ||
| use rustc_errors::Applicability; | ||
| use rustc_hir::{Expr, ExprKind, Node, PatKind}; | ||
| use rustc_lint::LateContext; | ||
| use rustc_middle::ty; | ||
| use rustc_span::{Span, Symbol}; | ||
|
|
||
| pub(super) fn check<'tcx>( | ||
| cx: &LateContext<'tcx>, | ||
| recv: &'tcx Expr<'tcx>, | ||
| arg: &'tcx Expr<'tcx>, | ||
| expr: &'tcx Expr<'tcx>, | ||
| call_span: Span, | ||
| method_name: Symbol, | ||
| msrv: Msrv, | ||
| ) { | ||
| let recv_ty = cx.typeck_results().expr_ty_adjusted(recv); | ||
| if !matches!(recv_ty.kind(), ty::Ref(_, inner, _) if inner.is_slice()) { | ||
| return; | ||
| } | ||
|
|
||
| if is_const_evaluatable(cx, arg) { | ||
| if !msrv.meets(cx, msrvs::AS_CHUNKS) { | ||
| return; | ||
| } | ||
|
|
||
| let suggestion_method = if method_name == sym::chunks_exact_mut { | ||
| "as_chunks_mut" | ||
| } else { | ||
| "as_chunks" | ||
| }; | ||
|
|
||
| let mut applicability = Applicability::MachineApplicable; | ||
| let arg_str = snippet_with_context(cx, arg.span, expr.span.ctxt(), "_", &mut applicability).0; | ||
|
|
||
| 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| { | ||
| let use_ctxt = expr_use_ctxt(cx, expr); | ||
|
|
||
| let in_for_loop = { | ||
| let mut cur_expr = expr; | ||
| loop { | ||
| if let Some(parent_expr) = get_parent_expr(cx, cur_expr) { | ||
| if let Some(for_loop) = ForLoop::hir(parent_expr) | ||
| && for_loop.arg.hir_id == expr.hir_id | ||
| { | ||
| break true; | ||
| } | ||
| cur_expr = parent_expr; | ||
| } else { | ||
| break false; | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| let is_iterator_method = if let Node::Expr(parent_expr) = use_ctxt.node | ||
| && let ExprKind::MethodCall(_, receiver, _, _) = parent_expr.kind | ||
| && receiver.hir_id == use_ctxt.child_id | ||
| && let Some(method_did) = cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) | ||
| && let Some(trait_did) = cx.tcx.trait_of_assoc(method_did) | ||
| { | ||
| matches!( | ||
| cx.tcx.get_diagnostic_name(trait_did), | ||
| Some(sym::Iterator | sym::IntoIterator) | ||
| ) | ||
| } else { | ||
| false | ||
| }; | ||
|
|
||
| if in_for_loop { | ||
| diag.span_suggestion( | ||
| call_span, | ||
| "consider using `as_chunks` instead", | ||
| format!("{as_chunks}.0"), | ||
| applicability, | ||
| ); | ||
| } else if is_iterator_method { | ||
| diag.span_suggestion( | ||
| call_span, | ||
| "consider using `as_chunks` instead", | ||
| format!("{as_chunks}.0.iter()"), | ||
| applicability, | ||
| ); | ||
| } else { | ||
| diag.span_help(call_span, format!("consider using `{as_chunks}` instead")); | ||
|
|
||
| if let Node::LetStmt(let_stmt) = use_ctxt.node | ||
| && let PatKind::Binding(_, _, ident, _) = let_stmt.pat.kind | ||
| { | ||
| diag.note(format!( | ||
| "you can access the chunks using `{ident}.0.iter()`, and the remainder using `{ident}.1`" | ||
| )); | ||
| } | ||
| } | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
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,45 @@ | ||
| #![warn(clippy::chunks_exact_with_const_size)] | ||
| #![allow(unused)] | ||
|
|
||
| fn main() { | ||
| let slice = [1, 2, 3, 4, 5, 6, 7, 8]; | ||
|
|
||
| // Should NOT trigger - runtime value | ||
| let size = 4; | ||
| let mut it = slice.chunks_exact(size); | ||
| for chunk in it {} | ||
|
|
||
| // Should trigger - direct iteration without binding (gets suggestion) | ||
| for chunk in slice.as_chunks::<4>().0 { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - direct iteration with const | ||
| const CHUNK_SIZE: usize = 4; | ||
| for chunk in slice.as_chunks::<CHUNK_SIZE>().0 { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - chunks_exact_mut with direct iteration (gets suggestion without .iter()) | ||
| let mut arr = [1, 2, 3, 4, 5, 6, 7, 8]; | ||
| for chunk in arr.as_chunks_mut::<4>().0 { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - used with iterator method (not for loop, so needs .iter()) | ||
| let _: Vec<_> = slice.as_chunks::<4>().0.iter().collect(); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // Should NOT trigger - macro-expanded sizes are not recognized as const by is_const_evaluatable | ||
| macro_rules! chunk_size { | ||
| () => { | ||
| 4 | ||
| }; | ||
| } | ||
| for chunk in slice.chunks_exact(chunk_size!()) { | ||
| let _ = chunk; | ||
| } | ||
| } |
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,45 @@ | ||
| #![warn(clippy::chunks_exact_with_const_size)] | ||
| #![allow(unused)] | ||
|
|
||
| fn main() { | ||
| let slice = [1, 2, 3, 4, 5, 6, 7, 8]; | ||
|
|
||
| // Should NOT trigger - runtime value | ||
| let size = 4; | ||
| let mut it = slice.chunks_exact(size); | ||
| for chunk in it {} | ||
|
|
||
| // Should trigger - direct iteration without binding (gets suggestion) | ||
| for chunk in slice.chunks_exact(4) { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - direct iteration with const | ||
| const CHUNK_SIZE: usize = 4; | ||
| for chunk in slice.chunks_exact(CHUNK_SIZE) { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - chunks_exact_mut with direct iteration (gets suggestion without .iter()) | ||
| let mut arr = [1, 2, 3, 4, 5, 6, 7, 8]; | ||
| for chunk in arr.chunks_exact_mut(4) { | ||
| //~^ chunks_exact_with_const_size | ||
| let _ = chunk; | ||
| } | ||
|
|
||
| // Should trigger - used with iterator method (not for loop, so needs .iter()) | ||
| let _: Vec<_> = slice.chunks_exact(4).collect(); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // Should NOT trigger - macro-expanded sizes are not recognized as const by is_const_evaluatable | ||
| macro_rules! chunk_size { | ||
| () => { | ||
| 4 | ||
| }; | ||
| } | ||
| for chunk in slice.chunks_exact(chunk_size!()) { | ||
| let _ = chunk; | ||
| } | ||
| } |
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,29 @@ | ||
| error: using `chunks_exact` with a constant chunk size | ||
| --> tests/ui/chunks_exact_with_const_size.rs:13:24 | ||
| | | ||
| LL | for chunk in slice.chunks_exact(4) { | ||
| | ^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<4>().0` | ||
| | | ||
| = 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:20:24 | ||
| | | ||
| LL | for chunk in slice.chunks_exact(CHUNK_SIZE) { | ||
| | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<CHUNK_SIZE>().0` | ||
|
|
||
| error: using `chunks_exact_mut` with a constant chunk size | ||
| --> tests/ui/chunks_exact_with_const_size.rs:27:22 | ||
| | | ||
| LL | for chunk in arr.chunks_exact_mut(4) { | ||
| | ^^^^^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks_mut::<4>().0` | ||
|
|
||
| error: using `chunks_exact` with a constant chunk size | ||
| --> tests/ui/chunks_exact_with_const_size.rs:33:27 | ||
| | | ||
| LL | let _: Vec<_> = slice.chunks_exact(4).collect(); | ||
| | ^^^^^^^^^^^^^^^ help: consider using `as_chunks` instead: `as_chunks::<4>().0.iter()` | ||
|
|
||
| error: aborting due to 4 previous errors | ||
|
|
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,52 @@ | ||
| #![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]; | ||
| const CHUNK_SIZE: usize = 4; | ||
|
|
||
| // Should trigger lint - literal constant (stored in let binding, so help not suggestion) | ||
| let result = slice.chunks_exact(4); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // Should trigger lint - const value | ||
| let result = slice.chunks_exact(CHUNK_SIZE); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // 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 | ||
| #[rustfmt::skip] | ||
| let result = slice | ||
| .iter() | ||
| .copied() | ||
| .collect::<Vec<_>>() | ||
| .chunks_exact(2); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // Should trigger - array coerces to slice reference | ||
| let array = [1, 2, 3, 4, 5, 6, 7, 8]; | ||
| let result = array.chunks_exact(4); | ||
| //~^ chunks_exact_with_const_size | ||
|
|
||
| // Should trigger lint with help message only (not suggestion) - stored in variable | ||
| let mut chunk_iter = slice.chunks_exact(CHUNK_SIZE); | ||
| //~^ chunks_exact_with_const_size | ||
| for chunk in chunk_iter.by_ref() {} | ||
| let _remainder = chunk_iter.remainder(); | ||
|
|
||
| // Similar for mutable version - help message only | ||
| let mut arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | ||
| let mut chunk_iter = arr2.chunks_exact_mut(CHUNK_SIZE); | ||
| //~^ chunks_exact_with_const_size | ||
| for chunk in chunk_iter.by_ref() {} | ||
| let _remainder = chunk_iter.into_remainder(); | ||
| } |
Oops, something went wrong.
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.
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.
This can be simplified quite a bit:
You'll also need to avoid linting on
use_ctxt.is_ty_unifiedsince that will just be a type error.