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