]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eta_reduction.rs
Auto merge of #3705 - matthiaskrgr:rustup, r=phansch
[rust.git] / clippy_lints / src / eta_reduction.rs
1 use crate::utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then};
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::ty;
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7
8 pub struct EtaPass;
9
10 /// **What it does:** Checks for closures which just call another function where
11 /// the function can be called directly. `unsafe` functions or calls where types
12 /// get adjusted are ignored.
13 ///
14 /// **Why is this bad?** Needlessly creating a closure adds code for no benefit
15 /// and gives the optimizer more work.
16 ///
17 /// **Known problems:** If creating the closure inside the closure has a side-
18 /// effect then moving the closure creation out will change when that side-
19 /// effect runs.
20 /// See https://github.com/rust-lang/rust-clippy/issues/1439 for more
21 /// details.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// xs.map(|x| foo(x))
26 /// ```
27 /// where `foo(_)` is a plain function that takes the exact argument type of
28 /// `x`.
29 declare_clippy_lint! {
30     pub REDUNDANT_CLOSURE,
31     style,
32     "redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
33 }
34
35 impl LintPass for EtaPass {
36     fn get_lints(&self) -> LintArray {
37         lint_array!(REDUNDANT_CLOSURE)
38     }
39
40     fn name(&self) -> &'static str {
41         "EtaReduction"
42     }
43 }
44
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
46     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
47         match expr.node {
48             ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
49                 for arg in args {
50                     check_closure(cx, arg)
51                 }
52             },
53             _ => (),
54         }
55     }
56 }
57
58 fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr) {
59     if let ExprKind::Closure(_, ref decl, eid, _, _) = expr.node {
60         let body = cx.tcx.hir().body(eid);
61         let ex = &body.value;
62         if let ExprKind::Call(ref caller, ref args) = ex.node {
63             if args.len() != decl.inputs.len() {
64                 // Not the same number of arguments, there
65                 // is no way the closure is the same as the function
66                 return;
67             }
68             if is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)) {
69                 // Are the expression or the arguments type-adjusted? Then we need the closure
70                 return;
71             }
72             let fn_ty = cx.tables.expr_ty(caller);
73             match fn_ty.sty {
74                 // Is it an unsafe function? They don't implement the closure traits
75                 ty::FnDef(..) | ty::FnPtr(_) => {
76                     let sig = fn_ty.fn_sig(cx.tcx);
77                     if sig.skip_binder().unsafety == Unsafety::Unsafe || sig.skip_binder().output().sty == ty::Never {
78                         return;
79                     }
80                 },
81                 _ => (),
82             }
83             for (a1, a2) in iter_input_pats(decl, body).zip(args) {
84                 if let PatKind::Binding(_, _, ident, _) = a1.pat.node {
85                     // XXXManishearth Should I be checking the binding mode here?
86                     if let ExprKind::Path(QPath::Resolved(None, ref p)) = a2.node {
87                         if p.segments.len() != 1 {
88                             // If it's a proper path, it can't be a local variable
89                             return;
90                         }
91                         if p.segments[0].ident.name != ident.name {
92                             // The two idents should be the same
93                             return;
94                         }
95                     } else {
96                         return;
97                     }
98                 } else {
99                     return;
100                 }
101             }
102             span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
103                 if let Some(snippet) = snippet_opt(cx, caller.span) {
104                     db.span_suggestion(
105                         expr.span,
106                         "remove closure as shown",
107                         snippet,
108                         Applicability::MachineApplicable,
109                     );
110                 }
111             });
112         }
113     }
114 }