]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_closure_call.rs
Auto merge of #88615 - flip1995:clippyup, r=Manishearth
[rust.git] / clippy_lints / src / redundant_closure_call.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
2 use clippy_utils::source::snippet_with_applicability;
3 use if_chain::if_chain;
4 use rustc_ast::ast;
5 use rustc_ast::visit as ast_visit;
6 use rustc_ast::visit::Visitor as AstVisitor;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_hir::intravisit as hir_visit;
10 use rustc_hir::intravisit::Visitor as HirVisitor;
11 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::lint::in_external_macro;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Detects closures called in the same expression where they
19     /// are defined.
20     ///
21     /// ### Why is this bad?
22     /// It is unnecessarily adding to the expression's
23     /// complexity.
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(_) | ast::ExprKind::Try(_) = ex.kind {
55             self.found_return = true;
56         }
57
58         ast_visit::walk_expr(self, ex);
59     }
60 }
61
62 impl EarlyLintPass for RedundantClosureCall {
63     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
64         if in_external_macro(cx.sess, expr.span) {
65             return;
66         }
67         if_chain! {
68             if let ast::ExprKind::Call(ref paren, _) = expr.kind;
69             if let ast::ExprKind::Paren(ref closure) = paren.kind;
70             if let ast::ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind;
71             then {
72                 let mut visitor = ReturnVisitor::new();
73                 visitor.visit_expr(block);
74                 if !visitor.found_return {
75                     span_lint_and_then(
76                         cx,
77                         REDUNDANT_CLOSURE_CALL,
78                         expr.span,
79                         "try not to call a closure in the expression where it is declared",
80                         |diag| {
81                             if decl.inputs.is_empty() {
82                                 let mut app = Applicability::MachineApplicable;
83                                 let hint =
84                                     snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
85                                 diag.span_suggestion(expr.span, "try doing something like", hint, app);
86                             }
87                         },
88                     );
89                 }
90             }
91         }
92     }
93 }
94
95 impl<'tcx> LateLintPass<'tcx> for RedundantClosureCall {
96     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
97         fn count_closure_usage<'a, 'tcx>(
98             cx: &'a LateContext<'tcx>,
99             block: &'tcx hir::Block<'_>,
100             path: &'tcx hir::Path<'tcx>,
101         ) -> usize {
102             struct ClosureUsageCount<'a, 'tcx> {
103                 cx: &'a LateContext<'tcx>,
104                 path: &'tcx hir::Path<'tcx>,
105                 count: usize,
106             }
107             impl<'a, 'tcx> hir_visit::Visitor<'tcx> for ClosureUsageCount<'a, 'tcx> {
108                 type Map = Map<'tcx>;
109
110                 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
111                     if_chain! {
112                         if let hir::ExprKind::Call(closure, _) = expr.kind;
113                         if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = closure.kind;
114                         if self.path.segments[0].ident == path.segments[0].ident;
115                         if self.path.res == path.res;
116                         then {
117                             self.count += 1;
118                         }
119                     }
120                     hir_visit::walk_expr(self, expr);
121                 }
122
123                 fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
124                     hir_visit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
125                 }
126             }
127             let mut closure_usage_count = ClosureUsageCount { cx, path, count: 0 };
128             closure_usage_count.visit_block(block);
129             closure_usage_count.count
130         }
131
132         for w in block.stmts.windows(2) {
133             if_chain! {
134                 if let hir::StmtKind::Local(local) = w[0].kind;
135                 if let Option::Some(t) = local.init;
136                 if let hir::ExprKind::Closure(..) = t.kind;
137                 if let hir::PatKind::Binding(_, _, ident, _) = local.pat.kind;
138                 if let hir::StmtKind::Semi(second) = w[1].kind;
139                 if let hir::ExprKind::Assign(_, call, _) = second.kind;
140                 if let hir::ExprKind::Call(closure, _) = call.kind;
141                 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = closure.kind;
142                 if ident == path.segments[0].ident;
143                 if count_closure_usage(cx, block, path) == 1;
144                 then {
145                     span_lint(
146                         cx,
147                         REDUNDANT_CLOSURE_CALL,
148                         second.span,
149                         "closure called just once immediately after it was declared",
150                     );
151                 }
152             }
153         }
154     }
155 }