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