]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_closure_call.rs
redundant_closure_call - extract lint from misc_early.rs, adapt to LatePass
[rust.git] / clippy_lints / src / redundant_closure_call.rs
1 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_then};
2 use if_chain::if_chain;
3 use rustc_ast::ast;
4 use rustc_ast::visit as ast_visit;
5 use rustc_ast::visit::Visitor as AstVisitor;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_hir::intravisit as hir_visit;
9 use rustc_hir::intravisit::Visitor as HirVisitor;
10 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
11 use rustc_middle::hir::map::Map;
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::symbol::Ident;
15
16 declare_clippy_lint! {
17     /// **What it does:** Detects closures called in the same expression where they
18     /// are defined.
19     ///
20     /// **Why is this bad?** It is unnecessarily adding to the expression's
21     /// complexity.
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```rust,ignore
27     /// // Bad
28     /// let a = (|| 42)()
29     ///
30     /// // Good
31     /// let a = 42
32     /// ```
33     pub REDUNDANT_CLOSURE_CALL,
34     complexity,
35     "throwaway closures called in the expression they are defined"
36 }
37
38 declare_lint_pass!(RedundantClosureCall => [REDUNDANT_CLOSURE_CALL]);
39
40 // Used to find `return` statements or equivalents e.g., `?`
41 struct ReturnVisitor {
42     found_return: bool,
43 }
44
45 impl ReturnVisitor {
46     #[must_use]
47     fn new() -> Self {
48         Self { found_return: false }
49     }
50 }
51
52 impl<'ast> ast_visit::Visitor<'ast> for ReturnVisitor {
53     fn visit_expr(&mut self, ex: &'ast ast::Expr) {
54         if let ast::ExprKind::Ret(_) = ex.kind {
55             self.found_return = true;
56         } else if let ast::ExprKind::Try(_) = ex.kind {
57             self.found_return = true;
58         }
59
60         ast_visit::walk_expr(self, ex)
61     }
62 }
63
64 impl EarlyLintPass for RedundantClosureCall {
65     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
66         if in_external_macro(cx.sess(), expr.span) {
67             return;
68         }
69         if_chain! {
70             if let ast::ExprKind::Call(ref paren, _) = expr.kind;
71             if let ast::ExprKind::Paren(ref closure) = paren.kind;
72             if let ast::ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind;
73             then {
74                 let mut visitor = ReturnVisitor::new();
75                 visitor.visit_expr(block);
76                 if !visitor.found_return {
77                     span_lint_and_then(
78                         cx,
79                         REDUNDANT_CLOSURE_CALL,
80                         expr.span,
81                         "Try not to call a closure in the expression where it is declared.",
82                         |diag| {
83                             if decl.inputs.is_empty() {
84                                 let mut app = Applicability::MachineApplicable;
85                                 let hint =
86                                     snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
87                                 diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
88                             }
89                         },
90                     );
91                 }
92             }
93         }
94     }
95 }
96
97 impl<'tcx> LateLintPass<'tcx> for RedundantClosureCall {
98     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
99         fn count_closure_usage<'tcx>(block: &'tcx hir::Block<'_>, ident: &'tcx Ident) -> usize {
100             struct ClosureUsageCount<'tcx> {
101                 ident: &'tcx Ident,
102                 count: usize,
103             };
104             impl<'tcx> hir_visit::Visitor<'tcx> for ClosureUsageCount<'tcx> {
105                 type Map = Map<'tcx>;
106
107                 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
108                     if_chain! {
109                         if let hir::ExprKind::Call(ref closure, _) = expr.kind;
110                         if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = closure.kind;
111                         if self.ident == &path.segments[0].ident;
112                         then {
113                             self.count += 1;
114                         }
115                     }
116                     hir_visit::walk_expr(self, expr);
117                 }
118
119                 fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
120                     hir_visit::NestedVisitorMap::None
121                 }
122             };
123             let mut closure_usage_count = ClosureUsageCount { ident, count: 0 };
124             closure_usage_count.visit_block(block);
125             closure_usage_count.count
126         }
127
128         for w in block.stmts.windows(2) {
129             if_chain! {
130                 if let hir::StmtKind::Local(ref local) = w[0].kind;
131                 if let Option::Some(ref t) = local.init;
132                 if let hir::ExprKind::Closure(..) = t.kind;
133                 if let hir::PatKind::Binding(_, _, ident, _) = local.pat.kind;
134                 if let hir::StmtKind::Semi(ref second) = w[1].kind;
135                 if let hir::ExprKind::Assign(_, ref call, _) = second.kind;
136                 if let hir::ExprKind::Call(ref closure, _) = call.kind;
137                 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = closure.kind;
138                 if ident == path.segments[0].ident;
139                 if  count_closure_usage(block, &ident) == 1;
140                 then {
141                     span_lint(
142                         cx,
143                         REDUNDANT_CLOSURE_CALL,
144                         second.span,
145                         "Closure called just once immediately after it was declared",
146                     );
147                 }
148             }
149         }
150     }
151 }