]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eta_reduction.rs
redundant closure implemented for closures containing method calls
[rust.git] / clippy_lints / src / eta_reduction.rs
1 use crate::utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then, type_is_unsafe_function};
2 use if_chain::if_chain;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty;
6 use rustc::{declare_tool_lint, lint_array};
7 use rustc_errors::Applicability;
8
9 pub struct EtaPass;
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/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     fn name(&self) -> &'static str {
42         "EtaReduction"
43     }
44 }
45
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48         match expr.node {
49             ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
50                 for arg in args {
51                     check_closure(cx, arg)
52                 }
53             },
54             _ => (),
55         }
56     }
57 }
58
59 fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr) {
60     if let ExprKind::Closure(_, ref decl, eid, _, _) = expr.node {
61         let body = cx.tcx.hir().body(eid);
62         let ex = &body.value;
63
64         if_chain!(
65             if let ExprKind::Call(ref caller, ref args) = ex.node;
66
67             // Not the same number of arguments, there is no way the closure is the same as the function return;
68             if args.len() == decl.inputs.len();
69
70             // Are the expression or the arguments type-adjusted? Then we need the closure
71             if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)));
72
73             let fn_ty = cx.tables.expr_ty(caller);
74             if !type_is_unsafe_function(cx, fn_ty);
75
76             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
77
78             then {
79                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
80                     if let Some(snippet) = snippet_opt(cx, caller.span) {
81                         db.span_suggestion(
82                             expr.span,
83                             "remove closure as shown",
84                             snippet,
85                             Applicability::MachineApplicable,
86                         );
87                     }
88                 });
89             }
90         );
91
92         if_chain!(
93             if let ExprKind::MethodCall(ref path, _, ref args) = ex.node;
94
95             // Not the same number of arguments, there is no way the closure is the same as the function return;
96             if args.len() == decl.inputs.len();
97
98             // Are the expression or the arguments type-adjusted? Then we need the closure
99             if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg)));
100
101             let method_def_id = cx.tables.type_dependent_defs()[ex.hir_id].def_id();
102             if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id));
103
104             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
105
106             if let Some(name) = get_ufcs_type_name(cx, method_def_id, &args[0]);
107
108             then {
109                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
110                     db.span_suggestion(
111                         expr.span,
112                         "remove closure as shown",
113                         format!("{}::{}", name, path.ident.name),
114                         Applicability::MachineApplicable,
115                     );
116                 });
117             }
118         );
119     }
120 }
121
122 /// Tries to determine the type for universal function call to be used instead of the closure
123 fn get_ufcs_type_name(
124     cx: &LateContext<'_, '_>,
125     method_def_id: def_id::DefId,
126     self_arg: &Expr,
127 ) -> std::option::Option<String> {
128     let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0].sty;
129     let actual_type_of_self = &cx.tables.node_id_to_type(self_arg.hir_id).sty;
130
131     if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) {
132         //if the method expectes &self, ufcs requires explicit borrowing so closure can't be removed
133         return match (expected_type_of_self, actual_type_of_self) {
134             (ty::Ref(_, _, _), ty::Ref(_, _, _)) => Some(cx.tcx.item_path_str(trait_id)),
135             (l, r) => match (l, r) {
136                 (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _)) => None,
137                 (_, _) => Some(cx.tcx.item_path_str(trait_id)),
138             },
139         };
140     }
141
142     cx.tcx.impl_of_method(method_def_id).and_then(|_| {
143         //a type may implicitly implement other types methods (e.g. Deref)
144         if match_types(expected_type_of_self, actual_type_of_self) {
145             return Some(get_type_name(cx, &actual_type_of_self));
146         }
147         None
148     })
149 }
150
151 fn match_types(lhs: &ty::TyKind<'_>, rhs: &ty::TyKind<'_>) -> bool {
152     match (lhs, rhs) {
153         (ty::Bool, ty::Bool)
154         | (ty::Char, ty::Char)
155         | (ty::Int(_), ty::Int(_))
156         | (ty::Uint(_), ty::Uint(_))
157         | (ty::Str, ty::Str) => true,
158         (ty::Ref(_, t1, _), ty::Ref(_, t2, _))
159         | (ty::Array(t1, _), ty::Array(t2, _))
160         | (ty::Slice(t1), ty::Slice(t2)) => match_types(&t1.sty, &t2.sty),
161         (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2,
162         (_, _) => false,
163     }
164 }
165
166 fn get_type_name(cx: &LateContext<'_, '_>, kind: &ty::TyKind<'_>) -> String {
167     match kind {
168         ty::Adt(t, _) => cx.tcx.item_path_str(t.did),
169         ty::Ref(_, r, _) => get_type_name(cx, &r.sty),
170         _ => kind.to_string(),
171     }
172 }
173
174 fn compare_inputs(closure_inputs: &mut dyn Iterator<Item = &Arg>, call_args: &mut dyn Iterator<Item = &Expr>) -> bool {
175     for (closure_input, function_arg) in closure_inputs.zip(call_args) {
176         if let PatKind::Binding(_, _, _, ident, _) = closure_input.pat.node {
177             // XXXManishearth Should I be checking the binding mode here?
178             if let ExprKind::Path(QPath::Resolved(None, ref p)) = function_arg.node {
179                 if p.segments.len() != 1 {
180                     // If it's a proper path, it can't be a local variable
181                     return false;
182                 }
183                 if p.segments[0].ident.name != ident.name {
184                     // The two idents should be the same
185                     return false;
186                 }
187             } else {
188                 return false;
189             }
190         } else {
191             return false;
192         }
193     }
194     true
195 }