-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New Lint: needless_for_each #6706
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
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
5029dc8
New Lint: excessive_for_each
Y-Nak 3095253
Fix codes that fails dogfood
Y-Nak 54a0471
Change a category of excessive_for_each: Style -> Restriction
Y-Nak 5bb0f16
Trigger the lint iff exposure's body is ExprKind::Block.
Y-Nak 90cbbb2
Avoid to suggest using label
Y-Nak ccd7a60
Refactor: Remove duplicated codes from excessive_for_each
Y-Nak 25d8b94
Add comments to clarify why RetCollector is needed
Y-Nak 3843171
Improve the document of excessive_for_each
Y-Nak 5543c34
Use ".." as default value of snippet in excessive_for_each
Y-Nak 527fbbe
Refactor excessive_for_each
Y-Nak f2cc995
Remove method_calls
Y-Nak 1109dc8
Fix codes that make dogfood fail
Y-Nak bf1e3f7
Skip needless_for_each if an input stmt is local
Y-Nak e61f978
Tweak a suggestion message of needless_for_each
Y-Nak 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
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,167 @@ | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{ | ||
intravisit::{walk_expr, NestedVisitorMap, Visitor}, | ||
Expr, ExprKind, Stmt, StmtKind, | ||
}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_middle::hir::map::Map; | ||
use rustc_session::{declare_lint_pass, declare_tool_lint}; | ||
use rustc_span::{source_map::Span, sym, Symbol}; | ||
|
||
use if_chain::if_chain; | ||
|
||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::is_trait_method; | ||
use clippy_utils::source::snippet_with_applicability; | ||
use clippy_utils::ty::has_iter_method; | ||
|
||
declare_clippy_lint! { | ||
/// **What it does:** Checks for usage of `for_each` that would be more simply written as a | ||
/// `for` loop. | ||
/// | ||
/// **Why is this bad?** `for_each` may be used after applying iterator transformers like | ||
/// `filter` for better readability and performance. It may also be used to fit a simple | ||
/// operation on one line. | ||
/// But when none of these apply, a simple `for` loop is more idiomatic. | ||
/// | ||
/// **Known problems:** None. | ||
/// | ||
/// **Example:** | ||
/// | ||
/// ```rust | ||
/// let v = vec![0, 1, 2]; | ||
/// v.iter().for_each(|elem| { | ||
/// println!("{}", elem); | ||
/// }) | ||
/// ``` | ||
/// Use instead: | ||
/// ```rust | ||
/// let v = vec![0, 1, 2]; | ||
/// for elem in v.iter() { | ||
/// println!("{}", elem); | ||
/// } | ||
/// ``` | ||
pub NEEDLESS_FOR_EACH, | ||
pedantic, | ||
"using `for_each` where a `for` loop would be simpler" | ||
} | ||
|
||
declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]); | ||
|
||
impl LateLintPass<'_> for NeedlessForEach { | ||
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { | ||
let expr = match stmt.kind { | ||
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr, | ||
_ => return, | ||
}; | ||
|
||
if_chain! { | ||
// Check the method name is `for_each`. | ||
if let ExprKind::MethodCall(method_name, _, [for_each_recv, for_each_arg], _) = expr.kind; | ||
if method_name.ident.name == Symbol::intern("for_each"); | ||
// Check `for_each` is an associated function of `Iterator`. | ||
if is_trait_method(cx, expr, sym::Iterator); | ||
// Checks the receiver of `for_each` is also a method call. | ||
if let ExprKind::MethodCall(_, _, [iter_recv], _) = for_each_recv.kind; | ||
// Skip the lint if the call chain is too long. e.g. `v.field.iter().for_each()` or | ||
// `v.foo().iter().for_each()` must be skipped. | ||
if matches!( | ||
iter_recv.kind, | ||
ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..) | ||
); | ||
// Checks the type of the `iter` method receiver is NOT a user defined type. | ||
if has_iter_method(cx, cx.typeck_results().expr_ty(&iter_recv)).is_some(); | ||
// Skip the lint if the body is not block because this is simpler than `for` loop. | ||
// e.g. `v.iter().for_each(f)` is simpler and clearer than using `for` loop. | ||
if let ExprKind::Closure(_, _, body_id, ..) = for_each_arg.kind; | ||
let body = cx.tcx.hir().body(body_id); | ||
if let ExprKind::Block(..) = body.value.kind; | ||
then { | ||
let mut ret_collector = RetCollector::default(); | ||
ret_collector.visit_expr(&body.value); | ||
|
||
// Skip the lint if `return` is used in `Loop` in order not to suggest using `'label`. | ||
if ret_collector.ret_in_loop { | ||
return; | ||
} | ||
|
||
let (mut applicability, ret_suggs) = if ret_collector.spans.is_empty() { | ||
(Applicability::MachineApplicable, None) | ||
} else { | ||
( | ||
Applicability::MaybeIncorrect, | ||
Some( | ||
ret_collector | ||
.spans | ||
.into_iter() | ||
.map(|span| (span, "continue".to_string())) | ||
.collect(), | ||
), | ||
) | ||
}; | ||
|
||
let sugg = format!( | ||
"for {} in {} {}", | ||
snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability), | ||
snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability), | ||
snippet_with_applicability(cx, body.value.span, "..", &mut applicability), | ||
); | ||
|
||
span_lint_and_then(cx, NEEDLESS_FOR_EACH, stmt.span, "needless use of `for_each`", |diag| { | ||
diag.span_suggestion(stmt.span, "try", sugg, applicability); | ||
if let Some(ret_suggs) = ret_suggs { | ||
diag.multipart_suggestion("...and replace `return` with `continue`", ret_suggs, applicability); | ||
} | ||
}) | ||
} | ||
} | ||
} | ||
} | ||
|
||
/// This type plays two roles. | ||
/// 1. Collect spans of `return` in the closure body. | ||
/// 2. Detect use of `return` in `Loop` in the closure body. | ||
/// | ||
/// NOTE: The functionality of this type is similar to | ||
/// [`crate::utilts::visitors::find_all_ret_expressions`], but we can't use | ||
/// `find_all_ret_expressions` instead of this type. The reasons are: | ||
/// 1. `find_all_ret_expressions` passes the argument of `ExprKind::Ret` to a callback, but what we | ||
/// need here is `ExprKind::Ret` itself. | ||
/// 2. We can't trace current loop depth with `find_all_ret_expressions`. | ||
#[derive(Default)] | ||
struct RetCollector { | ||
spans: Vec<Span>, | ||
ret_in_loop: bool, | ||
loop_depth: u16, | ||
} | ||
|
||
impl<'tcx> Visitor<'tcx> for RetCollector { | ||
type Map = Map<'tcx>; | ||
|
||
fn visit_expr(&mut self, expr: &Expr<'_>) { | ||
match expr.kind { | ||
ExprKind::Ret(..) => { | ||
if self.loop_depth > 0 && !self.ret_in_loop { | ||
self.ret_in_loop = true | ||
} | ||
|
||
self.spans.push(expr.span) | ||
}, | ||
|
||
ExprKind::Loop(..) => { | ||
self.loop_depth += 1; | ||
walk_expr(self, expr); | ||
self.loop_depth -= 1; | ||
return; | ||
}, | ||
|
||
_ => {}, | ||
} | ||
|
||
walk_expr(self, expr); | ||
} | ||
|
||
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { | ||
NestedVisitorMap::None | ||
} | ||
} |
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,113 @@ | ||
// run-rustfix | ||
#![warn(clippy::needless_for_each)] | ||
#![allow(unused, clippy::needless_return, clippy::match_single_binding)] | ||
|
||
use std::collections::HashMap; | ||
|
||
fn should_lint() { | ||
let v: Vec<i32> = Vec::new(); | ||
let mut acc = 0; | ||
for elem in v.iter() { | ||
acc += elem; | ||
} | ||
for elem in v.into_iter() { | ||
acc += elem; | ||
} | ||
|
||
for elem in [1, 2, 3].iter() { | ||
acc += elem; | ||
} | ||
|
||
let mut hash_map: HashMap<i32, i32> = HashMap::new(); | ||
for (k, v) in hash_map.iter() { | ||
acc += k + v; | ||
} | ||
for (k, v) in hash_map.iter_mut() { | ||
acc += *k + *v; | ||
} | ||
for k in hash_map.keys() { | ||
acc += k; | ||
} | ||
for v in hash_map.values() { | ||
acc += v; | ||
} | ||
|
||
fn my_vec() -> Vec<i32> { | ||
Vec::new() | ||
} | ||
for elem in my_vec().iter() { | ||
acc += elem; | ||
} | ||
} | ||
|
||
fn should_not_lint() { | ||
let v: Vec<i32> = Vec::new(); | ||
let mut acc = 0; | ||
|
||
// `for_each` argument is not closure. | ||
fn print(x: &i32) { | ||
println!("{}", x); | ||
} | ||
v.iter().for_each(print); | ||
|
||
// User defined type. | ||
struct MyStruct { | ||
v: Vec<i32>, | ||
} | ||
impl MyStruct { | ||
fn iter(&self) -> impl Iterator<Item = &i32> { | ||
self.v.iter() | ||
} | ||
} | ||
let s = MyStruct { v: Vec::new() }; | ||
s.iter().for_each(|elem| { | ||
acc += elem; | ||
}); | ||
|
||
// `for_each` follows long iterator chain. | ||
v.iter().chain(v.iter()).for_each(|v| { | ||
acc += v; | ||
}); | ||
v.as_slice().iter().for_each(|v| { | ||
acc += v; | ||
}); | ||
s.v.iter().for_each(|v| { | ||
acc += v; | ||
}); | ||
|
||
// `return` is used in `Loop` of the closure. | ||
v.iter().for_each(|v| { | ||
for i in 0..*v { | ||
if i == 10 { | ||
return; | ||
} else { | ||
println!("{}", v); | ||
} | ||
} | ||
if *v == 20 { | ||
return; | ||
} else { | ||
println!("{}", v); | ||
} | ||
}); | ||
|
||
// Previously transformed iterator variable. | ||
let it = v.iter(); | ||
it.chain(v.iter()).for_each(|elem| { | ||
acc += elem; | ||
}); | ||
|
||
// `for_each` is not directly in a statement. | ||
match 1 { | ||
_ => v.iter().for_each(|elem| { | ||
acc += elem; | ||
}), | ||
} | ||
|
||
// `for_each` is in a let bingind. | ||
let _ = v.iter().for_each(|elem| { | ||
acc += elem; | ||
}); | ||
} | ||
|
||
fn main() {} |
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.
Uh oh!
There was an error while loading. Please reload this page.