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