-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Refactor: organize loops file into loops module #6693
Closed
Closed
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
eeebe75
create loops dir; arrange manual_flatten lint and utils
nahuakang e521e52
Refactor check_for_loop_arg; rename manual_flatten's lint back to che…
nahuakang 07dd4f7
Refactor check_for_loop_over_map_kv to its own module
nahuakang e85f3c1
Refactor check_for_mut_range_bound to its own module
nahuakang d37a042
Refactor check_for_loop_range into its module
nahuakang abdd5f4
Refactor check_for_loop_explicit_counter to its own module
nahuakang 51d4678
Refactor check_for_single_element_loop to its own module
nahuakang 2050b41
Add check_infinite_loop to its own module
nahuakang 6fa5147
Add check_needless_collect to its own module
nahuakang 2ad6cc8
Add detect_same_item_push to its own module
nahuakang 7d02cd9
Move detect_manual_memcpy to its module; split up utils structs
nahuakang f06f9bc
Refactor never loop to its own module
nahuakang 19c4de5
Refactor while let on iterator lint to its module; rename for loop ex…
nahuakang d07539a
Refactor empty loop to its own module
nahuakang d08d3e2
Refactor while let loop to its own module
nahuakang 7d5dfcc
Move MinifyingSugg into manual_memcpy
nahuakang 2e9f90b
Move check_for_loop_arg back to mod; split into 4 lint files
nahuakang d8eeb97
Clean up: Rename some files to be consistent with lint names; import …
nahuakang fee0c89
Include loops.rs changes from PR#6698
nahuakang 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 was deleted.
Oops, something went wrong.
This file contains 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,17 @@ | ||
use super::EMPTY_LOOP; | ||
use crate::utils::{is_in_panic_handler, is_no_std_crate, span_lint_and_help}; | ||
|
||
use rustc_hir::{Block, Expr}; | ||
use rustc_lint::LateContext; | ||
|
||
pub(super) fn check_empty_loop(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &'tcx Block<'_>) { | ||
if loop_block.stmts.is_empty() && loop_block.expr.is_none() && !is_in_panic_handler(cx, expr) { | ||
let msg = "empty `loop {}` wastes CPU cycles"; | ||
let help = if is_no_std_crate(cx.tcx.hir().krate()) { | ||
"you should either use `panic!()` or add a call pausing or sleeping the thread to the loop body" | ||
} else { | ||
"you should either use `panic!()` or add `std::thread::sleep(..);` to the loop body" | ||
}; | ||
span_lint_and_help(cx, EMPTY_LOOP, expr.span, msg, None, help); | ||
} | ||
} |
This file contains 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 super::{ | ||
get_span_of_entire_for_loop, make_iterator_snippet, IncrementVisitor, InitializeVisitor, EXPLICIT_COUNTER_LOOP, | ||
}; | ||
use crate::utils::{get_enclosing_block, is_integer_const, snippet_with_applicability, span_lint_and_sugg}; | ||
use if_chain::if_chain; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::intravisit::{walk_block, walk_expr}; | ||
use rustc_hir::{Expr, Pat}; | ||
use rustc_lint::LateContext; | ||
|
||
// To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be | ||
// incremented exactly once in the loop body, and initialized to zero | ||
// at the start of the loop. | ||
pub(super) fn check_for_loop_explicit_counter<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
pat: &'tcx Pat<'_>, | ||
arg: &'tcx Expr<'_>, | ||
body: &'tcx Expr<'_>, | ||
expr: &'tcx Expr<'_>, | ||
) { | ||
// Look for variables that are incremented once per loop iteration. | ||
let mut increment_visitor = IncrementVisitor::new(cx); | ||
walk_expr(&mut increment_visitor, body); | ||
|
||
// For each candidate, check the parent block to see if | ||
// it's initialized to zero at the start of the loop. | ||
if let Some(block) = get_enclosing_block(&cx, expr.hir_id) { | ||
for id in increment_visitor.into_results() { | ||
let mut initialize_visitor = InitializeVisitor::new(cx, expr, id); | ||
walk_block(&mut initialize_visitor, block); | ||
|
||
if_chain! { | ||
if let Some((name, initializer)) = initialize_visitor.get_result(); | ||
if is_integer_const(cx, initializer, 0); | ||
then { | ||
let mut applicability = Applicability::MachineApplicable; | ||
|
||
let for_span = get_span_of_entire_for_loop(expr); | ||
|
||
span_lint_and_sugg( | ||
cx, | ||
EXPLICIT_COUNTER_LOOP, | ||
for_span.with_hi(arg.span.hi()), | ||
&format!("the variable `{}` is used as a loop counter.", name), | ||
"consider using", | ||
format!( | ||
"for ({}, {}) in {}.enumerate()", | ||
name, | ||
snippet_with_applicability(cx, pat.span, "item", &mut applicability), | ||
make_iterator_snippet(cx, arg, &mut applicability), | ||
), | ||
applicability, | ||
); | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains 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,20 @@ | ||
use super::EXPLICIT_INTO_ITER_LOOP; | ||
use crate::utils::{snippet_with_applicability, span_lint_and_sugg}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::Expr; | ||
use rustc_lint::LateContext; | ||
|
||
pub(super) fn check_explicit_into_iter_loop(cx: &LateContext<'_>, method_args: &'hir [Expr<'hir>], arg: &Expr<'_>) { | ||
let mut applicability = Applicability::MachineApplicable; | ||
let object = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability); | ||
span_lint_and_sugg( | ||
cx, | ||
EXPLICIT_INTO_ITER_LOOP, | ||
arg.span, | ||
"it is more concise to loop over containers instead of using explicit \ | ||
iteration methods", | ||
"to write this more concisely, try", | ||
object.to_string(), | ||
applicability, | ||
); | ||
} |
This file contains 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,21 @@ | ||
use super::EXPLICIT_ITER_LOOP; | ||
use crate::utils::{snippet_with_applicability, span_lint_and_sugg}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::Expr; | ||
use rustc_lint::LateContext; | ||
|
||
pub(super) fn lint_iter_method(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) { | ||
let mut applicability = Applicability::MachineApplicable; | ||
let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability); | ||
let muta = if method_name == "iter_mut" { "mut " } else { "" }; | ||
span_lint_and_sugg( | ||
cx, | ||
EXPLICIT_ITER_LOOP, | ||
arg.span, | ||
"it is more concise to loop over references to containers instead of using explicit \ | ||
iteration methods", | ||
"to write this more concisely, try", | ||
format!("&{}{}", muta, object), | ||
applicability, | ||
) | ||
} |
This file contains 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,70 @@ | ||
use super::FOR_KV_MAP; | ||
use crate::utils::visitors::LocalUsedVisitor; | ||
use crate::utils::{is_type_diagnostic_item, match_type, multispan_sugg, paths, snippet, span_lint_and_then, sugg}; | ||
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; | ||
use rustc_lint::LateContext; | ||
use rustc_middle::ty; | ||
|
||
/// Checks for the `FOR_KV_MAP` lint. | ||
pub(super) fn check_for_loop_over_map_kv<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
pat: &'tcx Pat<'_>, | ||
arg: &'tcx Expr<'_>, | ||
body: &'tcx Expr<'_>, | ||
expr: &'tcx Expr<'_>, | ||
) { | ||
let pat_span = pat.span; | ||
|
||
if let PatKind::Tuple(ref pat, _) = pat.kind { | ||
if pat.len() == 2 { | ||
let arg_span = arg.span; | ||
let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() { | ||
ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { | ||
(key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", ty, mutbl), | ||
(_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, Mutability::Not), | ||
_ => return, | ||
}, | ||
_ => return, | ||
}; | ||
let mutbl = match mutbl { | ||
Mutability::Not => "", | ||
Mutability::Mut => "_mut", | ||
}; | ||
let arg = match arg.kind { | ||
ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr, | ||
_ => arg, | ||
}; | ||
|
||
if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) { | ||
span_lint_and_then( | ||
cx, | ||
FOR_KV_MAP, | ||
expr.span, | ||
&format!("you seem to want to iterate on a map's {}s", kind), | ||
|diag| { | ||
let map = sugg::Sugg::hir(cx, arg, "map"); | ||
multispan_sugg( | ||
diag, | ||
"use the corresponding method", | ||
vec![ | ||
(pat_span, snippet(cx, new_pat_span, kind).into_owned()), | ||
(arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)), | ||
], | ||
); | ||
}, | ||
); | ||
} | ||
} | ||
} | ||
} | ||
|
||
/// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`. | ||
fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool { | ||
match *pat { | ||
PatKind::Wild => true, | ||
PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => { | ||
!LocalUsedVisitor::new(cx, id).check_expr(body) | ||
}, | ||
_ => false, | ||
} | ||
} |
This file contains 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 @@ | ||
use super::FOR_LOOPS_OVER_FALLIBLES; | ||
use crate::utils::{is_type_diagnostic_item, snippet, span_lint_and_help}; | ||
use rustc_hir::{Expr, Pat}; | ||
use rustc_lint::LateContext; | ||
use rustc_span::symbol::sym; | ||
|
||
/// Checks for `for` loops over `Option`s and `Result`s. | ||
pub(super) fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) { | ||
let ty = cx.typeck_results().expr_ty(arg); | ||
if is_type_diagnostic_item(cx, ty, sym::option_type) { | ||
span_lint_and_help( | ||
cx, | ||
FOR_LOOPS_OVER_FALLIBLES, | ||
arg.span, | ||
&format!( | ||
"for loop over `{0}`, which is an `Option`. This is more readably written as an \ | ||
`if let` statement.", | ||
snippet(cx, arg.span, "_") | ||
), | ||
None, | ||
&format!( | ||
"consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`", | ||
snippet(cx, pat.span, "_"), | ||
snippet(cx, arg.span, "_") | ||
), | ||
); | ||
} else if is_type_diagnostic_item(cx, ty, sym::result_type) { | ||
span_lint_and_help( | ||
cx, | ||
FOR_LOOPS_OVER_FALLIBLES, | ||
arg.span, | ||
&format!( | ||
"for loop over `{0}`, which is a `Result`. This is more readably written as an \ | ||
`if let` statement.", | ||
snippet(cx, arg.span, "_") | ||
), | ||
None, | ||
&format!( | ||
"consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`", | ||
snippet(cx, pat.span, "_"), | ||
snippet(cx, arg.span, "_") | ||
), | ||
); | ||
} | ||
} |
This file contains 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,14 @@ | ||
use super::ITER_NEXT_LOOP; | ||
use crate::utils::span_lint; | ||
use rustc_hir::Expr; | ||
use rustc_lint::LateContext; | ||
|
||
pub(super) fn lint(cx: &LateContext<'_>, expr: &Expr<'_>) { | ||
span_lint( | ||
cx, | ||
ITER_NEXT_LOOP, | ||
expr.span, | ||
"you are iterating over `Iterator::next()` which is an Option; this will compile but is \ | ||
probably not what you want", | ||
); | ||
} |
This file contains 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,79 @@ | ||
use super::utils::make_iterator_snippet; | ||
use super::MANUAL_FLATTEN; | ||
use crate::utils::{is_ok_ctor, is_some_ctor, path_to_local_id, span_lint_and_then}; | ||
use if_chain::if_chain; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{Expr, ExprKind, MatchSource, Pat, PatKind, QPath, StmtKind}; | ||
use rustc_lint::LateContext; | ||
use rustc_span::source_map::Span; | ||
|
||
/// Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the | ||
/// iterator element is used. | ||
pub(super) fn check_manual_flatten<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
pat: &'tcx Pat<'_>, | ||
arg: &'tcx Expr<'_>, | ||
body: &'tcx Expr<'_>, | ||
span: Span, | ||
) { | ||
if let ExprKind::Block(ref block, _) = body.kind { | ||
// Ensure the `if let` statement is the only expression or statement in the for-loop | ||
let inner_expr = if block.stmts.len() == 1 && block.expr.is_none() { | ||
let match_stmt = &block.stmts[0]; | ||
if let StmtKind::Semi(inner_expr) = match_stmt.kind { | ||
Some(inner_expr) | ||
} else { | ||
None | ||
} | ||
} else if block.stmts.is_empty() { | ||
block.expr | ||
} else { | ||
None | ||
}; | ||
|
||
if_chain! { | ||
if let Some(inner_expr) = inner_expr; | ||
if let ExprKind::Match( | ||
ref match_expr, ref match_arms, MatchSource::IfLetDesugar{ contains_else_clause: false } | ||
) = inner_expr.kind; | ||
// Ensure match_expr in `if let` statement is the same as the pat from the for-loop | ||
if let PatKind::Binding(_, pat_hir_id, _, _) = pat.kind; | ||
if path_to_local_id(match_expr, pat_hir_id); | ||
// Ensure the `if let` statement is for the `Some` variant of `Option` or the `Ok` variant of `Result` | ||
if let PatKind::TupleStruct(QPath::Resolved(None, path), _, _) = match_arms[0].pat.kind; | ||
let some_ctor = is_some_ctor(cx, path.res); | ||
let ok_ctor = is_ok_ctor(cx, path.res); | ||
if some_ctor || ok_ctor; | ||
let if_let_type = if some_ctor { "Some" } else { "Ok" }; | ||
|
||
then { | ||
// Prepare the error message | ||
let msg = format!("unnecessary `if let` since only the `{}` variant of the iterator element is used", if_let_type); | ||
|
||
// Prepare the help message | ||
let mut applicability = Applicability::MaybeIncorrect; | ||
let arg_snippet = make_iterator_snippet(cx, arg, &mut applicability); | ||
|
||
span_lint_and_then( | ||
cx, | ||
MANUAL_FLATTEN, | ||
span, | ||
&msg, | ||
|diag| { | ||
let sugg = format!("{}.flatten()", arg_snippet); | ||
diag.span_suggestion( | ||
arg.span, | ||
"try", | ||
sugg, | ||
Applicability::MaybeIncorrect, | ||
); | ||
diag.span_help( | ||
inner_expr.span, | ||
"...and remove the `if let` statement in the for loop", | ||
); | ||
} | ||
); | ||
} | ||
} | ||
} | ||
} |
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.
I think it would be great to unify the name of the main entry functions of all modules to
check
.