Skip to content

Commit a743553

Browse files
committed
Auto merge of #6706 - Y-Nak:excessive-for-each, r=camsteffen
New Lint: needless_for_each resolves: #6543 changelog: Added pedantic lint: `needless_for_each`
2 parents 0b76719 + 0e42112 commit a743553

10 files changed

+565
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2369,6 +2369,7 @@ Released 2018-09-13
23692369
[`needless_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
23702370
[`needless_continue`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_continue
23712371
[`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main
2372+
[`needless_for_each`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_for_each
23722373
[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
23732374
[`needless_pass_by_value`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value
23742375
[`needless_question_mark`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_question_mark

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ mod needless_bool;
288288
mod needless_borrow;
289289
mod needless_borrowed_ref;
290290
mod needless_continue;
291+
mod needless_for_each;
291292
mod needless_pass_by_value;
292293
mod needless_question_mark;
293294
mod needless_update;
@@ -861,6 +862,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
861862
&needless_borrow::NEEDLESS_BORROW,
862863
&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE,
863864
&needless_continue::NEEDLESS_CONTINUE,
865+
&needless_for_each::NEEDLESS_FOR_EACH,
864866
&needless_pass_by_value::NEEDLESS_PASS_BY_VALUE,
865867
&needless_question_mark::NEEDLESS_QUESTION_MARK,
866868
&needless_update::NEEDLESS_UPDATE,
@@ -1041,6 +1043,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10411043
store.register_late_pass(|| box ptr_eq::PtrEq);
10421044
store.register_late_pass(|| box needless_bool::NeedlessBool);
10431045
store.register_late_pass(|| box needless_bool::BoolComparison);
1046+
store.register_late_pass(|| box needless_for_each::NeedlessForEach);
10441047
store.register_late_pass(|| box approx_const::ApproxConstant);
10451048
store.register_late_pass(|| box misc::MiscLints);
10461049
store.register_late_pass(|| box eta_reduction::EtaReduction);
@@ -1401,6 +1404,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14011404
LintId::of(&misc_early::UNSEPARATED_LITERAL_SUFFIX),
14021405
LintId::of(&mut_mut::MUT_MUT),
14031406
LintId::of(&needless_continue::NEEDLESS_CONTINUE),
1407+
LintId::of(&needless_for_each::NEEDLESS_FOR_EACH),
14041408
LintId::of(&needless_pass_by_value::NEEDLESS_PASS_BY_VALUE),
14051409
LintId::of(&non_expressive_names::SIMILAR_NAMES),
14061410
LintId::of(&option_if_let_else::OPTION_IF_LET_ELSE),

clippy_lints/src/matches.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -924,7 +924,7 @@ fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm
924924
let mut ident_bind_name = String::from("_");
925925
if !matching_wild {
926926
// Looking for unused bindings (i.e.: `_e`)
927-
inner.iter().for_each(|pat| {
927+
for pat in inner.iter() {
928928
if let PatKind::Binding(_, id, ident, None) = pat.kind {
929929
if ident.as_str().starts_with('_')
930930
&& !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
@@ -933,7 +933,7 @@ fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm
933933
matching_wild = true;
934934
}
935935
}
936-
});
936+
}
937937
}
938938
if_chain! {
939939
if matching_wild;

clippy_lints/src/needless_for_each.rs

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
use rustc_errors::Applicability;
2+
use rustc_hir::{
3+
intravisit::{walk_expr, NestedVisitorMap, Visitor},
4+
Expr, ExprKind, Stmt, StmtKind,
5+
};
6+
use rustc_lint::{LateContext, LateLintPass};
7+
use rustc_middle::hir::map::Map;
8+
use rustc_session::{declare_lint_pass, declare_tool_lint};
9+
use rustc_span::{source_map::Span, sym, Symbol};
10+
11+
use if_chain::if_chain;
12+
13+
use crate::utils::{has_iter_method, is_trait_method, snippet_with_applicability, span_lint_and_then};
14+
15+
declare_clippy_lint! {
16+
/// **What it does:** Checks for usage of `for_each` that would be more simply written as a
17+
/// `for` loop.
18+
///
19+
/// **Why is this bad?** `for_each` may be used after applying iterator transformers like
20+
/// `filter` for better readability and performance. It may also be used to fit a simple
21+
/// operation on one line.
22+
/// But when none of these apply, a simple `for` loop is more idiomatic.
23+
///
24+
/// **Known problems:** None.
25+
///
26+
/// **Example:**
27+
///
28+
/// ```rust
29+
/// let v = vec![0, 1, 2];
30+
/// v.iter().for_each(|elem| {
31+
/// println!("{}", elem);
32+
/// })
33+
/// ```
34+
/// Use instead:
35+
/// ```rust
36+
/// let v = vec![0, 1, 2];
37+
/// for elem in v.iter() {
38+
/// println!("{}", elem);
39+
/// }
40+
/// ```
41+
pub NEEDLESS_FOR_EACH,
42+
pedantic,
43+
"using `for_each` where a `for` loop would be simpler"
44+
}
45+
46+
declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]);
47+
48+
impl LateLintPass<'_> for NeedlessForEach {
49+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
50+
let expr = match stmt.kind {
51+
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
52+
_ => return,
53+
};
54+
55+
if_chain! {
56+
// Check the method name is `for_each`.
57+
if let ExprKind::MethodCall(method_name, _, [for_each_recv, for_each_arg], _) = expr.kind;
58+
if method_name.ident.name == Symbol::intern("for_each");
59+
// Check `for_each` is an associated function of `Iterator`.
60+
if is_trait_method(cx, expr, sym::Iterator);
61+
// Checks the receiver of `for_each` is also a method call.
62+
if let ExprKind::MethodCall(_, _, [iter_recv], _) = for_each_recv.kind;
63+
// Skip the lint if the call chain is too long. e.g. `v.field.iter().for_each()` or
64+
// `v.foo().iter().for_each()` must be skipped.
65+
if matches!(
66+
iter_recv.kind,
67+
ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..)
68+
);
69+
// Checks the type of the `iter` method receiver is NOT a user defined type.
70+
if has_iter_method(cx, cx.typeck_results().expr_ty(&iter_recv)).is_some();
71+
// Skip the lint if the body is not block because this is simpler than `for` loop.
72+
// e.g. `v.iter().for_each(f)` is simpler and clearer than using `for` loop.
73+
if let ExprKind::Closure(_, _, body_id, ..) = for_each_arg.kind;
74+
let body = cx.tcx.hir().body(body_id);
75+
if let ExprKind::Block(..) = body.value.kind;
76+
then {
77+
let mut ret_collector = RetCollector::default();
78+
ret_collector.visit_expr(&body.value);
79+
80+
// Skip the lint if `return` is used in `Loop` in order not to suggest using `'label`.
81+
if ret_collector.ret_in_loop {
82+
return;
83+
}
84+
85+
let (mut applicability, ret_suggs) = if ret_collector.spans.is_empty() {
86+
(Applicability::MachineApplicable, None)
87+
} else {
88+
(
89+
Applicability::MaybeIncorrect,
90+
Some(
91+
ret_collector
92+
.spans
93+
.into_iter()
94+
.map(|span| (span, "continue".to_string()))
95+
.collect(),
96+
),
97+
)
98+
};
99+
100+
let sugg = format!(
101+
"for {} in {} {}",
102+
snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability),
103+
snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability),
104+
snippet_with_applicability(cx, body.value.span, "..", &mut applicability),
105+
);
106+
107+
span_lint_and_then(cx, NEEDLESS_FOR_EACH, stmt.span, "needless use of `for_each`", |diag| {
108+
diag.span_suggestion(stmt.span, "try", sugg, applicability);
109+
if let Some(ret_suggs) = ret_suggs {
110+
diag.multipart_suggestion("...and replace `return` with `continue`", ret_suggs, applicability);
111+
}
112+
})
113+
}
114+
}
115+
}
116+
}
117+
118+
/// This type plays two roles.
119+
/// 1. Collect spans of `return` in the closure body.
120+
/// 2. Detect use of `return` in `Loop` in the closure body.
121+
///
122+
/// NOTE: The functionality of this type is similar to
123+
/// [`crate::utilts::visitors::find_all_ret_expressions`], but we can't use
124+
/// `find_all_ret_expressions` instead of this type. The reasons are:
125+
/// 1. `find_all_ret_expressions` passes the argument of `ExprKind::Ret` to a callback, but what we
126+
/// need here is `ExprKind::Ret` itself.
127+
/// 2. We can't trace current loop depth with `find_all_ret_expressions`.
128+
#[derive(Default)]
129+
struct RetCollector {
130+
spans: Vec<Span>,
131+
ret_in_loop: bool,
132+
loop_depth: u16,
133+
}
134+
135+
impl<'tcx> Visitor<'tcx> for RetCollector {
136+
type Map = Map<'tcx>;
137+
138+
fn visit_expr(&mut self, expr: &Expr<'_>) {
139+
match expr.kind {
140+
ExprKind::Ret(..) => {
141+
if self.loop_depth > 0 && !self.ret_in_loop {
142+
self.ret_in_loop = true
143+
}
144+
145+
self.spans.push(expr.span)
146+
},
147+
148+
ExprKind::Loop(..) => {
149+
self.loop_depth += 1;
150+
walk_expr(self, expr);
151+
self.loop_depth -= 1;
152+
return;
153+
},
154+
155+
_ => {},
156+
}
157+
158+
walk_expr(self, expr);
159+
}
160+
161+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
162+
NestedVisitorMap::None
163+
}
164+
}

tests/lint_message_convention.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,14 @@ fn lint_message_convention() {
8989
.filter(|message| !message.bad_lines.is_empty())
9090
.collect();
9191

92-
bad_tests.iter().for_each(|message| {
92+
for message in &bad_tests {
9393
eprintln!(
9494
"error: the test '{}' contained the following nonconforming lines :",
9595
message.path.display()
9696
);
9797
message.bad_lines.iter().for_each(|line| eprintln!("{}", line));
9898
eprintln!("\n\n");
99-
});
99+
}
100100

101101
eprintln!(
102102
"\n\n\nLint message should not start with a capital letter and should not have punctuation at the end of the message unless multiple sentences are needed."
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// run-rustfix
2+
#![warn(clippy::needless_for_each)]
3+
#![allow(unused, clippy::needless_return, clippy::match_single_binding)]
4+
5+
use std::collections::HashMap;
6+
7+
fn should_lint() {
8+
let v: Vec<i32> = Vec::new();
9+
let mut acc = 0;
10+
for elem in v.iter() {
11+
acc += elem;
12+
}
13+
for elem in v.into_iter() {
14+
acc += elem;
15+
}
16+
17+
for elem in [1, 2, 3].iter() {
18+
acc += elem;
19+
}
20+
21+
let mut hash_map: HashMap<i32, i32> = HashMap::new();
22+
for (k, v) in hash_map.iter() {
23+
acc += k + v;
24+
}
25+
for (k, v) in hash_map.iter_mut() {
26+
acc += *k + *v;
27+
}
28+
for k in hash_map.keys() {
29+
acc += k;
30+
}
31+
for v in hash_map.values() {
32+
acc += v;
33+
}
34+
35+
fn my_vec() -> Vec<i32> {
36+
Vec::new()
37+
}
38+
for elem in my_vec().iter() {
39+
acc += elem;
40+
}
41+
}
42+
43+
fn should_not_lint() {
44+
let v: Vec<i32> = Vec::new();
45+
let mut acc = 0;
46+
47+
// `for_each` argument is not closure.
48+
fn print(x: &i32) {
49+
println!("{}", x);
50+
}
51+
v.iter().for_each(print);
52+
53+
// User defined type.
54+
struct MyStruct {
55+
v: Vec<i32>,
56+
}
57+
impl MyStruct {
58+
fn iter(&self) -> impl Iterator<Item = &i32> {
59+
self.v.iter()
60+
}
61+
}
62+
let s = MyStruct { v: Vec::new() };
63+
s.iter().for_each(|elem| {
64+
acc += elem;
65+
});
66+
67+
// `for_each` follows long iterator chain.
68+
v.iter().chain(v.iter()).for_each(|v| {
69+
acc += v;
70+
});
71+
v.as_slice().iter().for_each(|v| {
72+
acc += v;
73+
});
74+
s.v.iter().for_each(|v| {
75+
acc += v;
76+
});
77+
78+
// `return` is used in `Loop` of the closure.
79+
v.iter().for_each(|v| {
80+
for i in 0..*v {
81+
if i == 10 {
82+
return;
83+
} else {
84+
println!("{}", v);
85+
}
86+
}
87+
if *v == 20 {
88+
return;
89+
} else {
90+
println!("{}", v);
91+
}
92+
});
93+
94+
// Previously transformed iterator variable.
95+
let it = v.iter();
96+
it.chain(v.iter()).for_each(|elem| {
97+
acc += elem;
98+
});
99+
100+
// `for_each` is not directly in a statement.
101+
match 1 {
102+
_ => v.iter().for_each(|elem| {
103+
acc += elem;
104+
}),
105+
}
106+
107+
// `for_each` is in a let bingind.
108+
let _ = v.iter().for_each(|elem| {
109+
acc += elem;
110+
});
111+
}
112+
113+
fn main() {}

0 commit comments

Comments
 (0)