summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/needless_for_each.rs
blob: 3233d87c073193f99a0046745ff49c603f7576a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use rustc_errors::Applicability;
use rustc_hir::{
    intravisit::{walk_expr, Visitor},
    Closure, Expr, ExprKind, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass};
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.
    ///
    /// ### 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);
    /// }
    /// ```
    #[clippy::version = "1.53.0"]
    pub NEEDLESS_FOR_EACH,
    pedantic,
    "using `for_each` where a `for` loop would be simpler"
}

declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]);

impl<'tcx> LateLintPass<'tcx> 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(&Closure { body, .. }) = for_each_arg.kind;
            let body = cx.tcx.hir().body(body);
            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
/// [`clippy_utils::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 {
    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);
    }
}