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