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