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