]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eta_reduction.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / eta_reduction.rs
1 use if_chain::if_chain;
2 use rustc::hir::*;
3 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
4 use rustc::ty::{self, Ty};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7
8 use crate::utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then, type_is_unsafe_function};
9
10 pub struct EtaPass;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for closures which just call another function where
14     /// the function can be called directly. `unsafe` functions or calls where types
15     /// get adjusted are ignored.
16     ///
17     /// **Why is this bad?** Needlessly creating a closure adds code for no benefit
18     /// and gives the optimizer more work.
19     ///
20     /// **Known problems:** If creating the closure inside the closure has a side-
21     /// effect then moving the closure creation out will change when that side-
22     /// effect runs.
23     /// See rust-lang/rust-clippy#1439 for more details.
24     ///
25     /// **Example:**
26     /// ```rust,ignore
27     /// xs.map(|x| foo(x))
28     /// ```
29     /// where `foo(_)` is a plain function that takes the exact argument type of
30     /// `x`.
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         if in_external_macro(cx.sess(), expr.span) {
49             return;
50         }
51
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
68         if_chain!(
69             if let ExprKind::Call(ref caller, ref args) = ex.node;
70
71             // Not the same number of arguments, there is no way the closure is the same as the function return;
72             if args.len() == decl.inputs.len();
73
74             // Are the expression or the arguments type-adjusted? Then we need the closure
75             if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)));
76
77             let fn_ty = cx.tables.expr_ty(caller);
78             if !type_is_unsafe_function(cx, fn_ty);
79
80             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
81
82             then {
83                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
84                     if let Some(snippet) = snippet_opt(cx, caller.span) {
85                         db.span_suggestion(
86                             expr.span,
87                             "remove closure as shown",
88                             snippet,
89                             Applicability::MachineApplicable,
90                         );
91                     }
92                 });
93             }
94         );
95
96         if_chain!(
97             if let ExprKind::MethodCall(ref path, _, ref args) = ex.node;
98
99             // Not the same number of arguments, there is no way the closure is the same as the function return;
100             if args.len() == decl.inputs.len();
101
102             // Are the expression or the arguments type-adjusted? Then we need the closure
103             if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg)));
104
105             let method_def_id = cx.tables.type_dependent_def_id(ex.hir_id).unwrap();
106             if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id));
107
108             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
109
110             if let Some(name) = get_ufcs_type_name(cx, method_def_id, &args[0]);
111
112             then {
113                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
114                     db.span_suggestion(
115                         expr.span,
116                         "remove closure as shown",
117                         format!("{}::{}", name, path.ident.name),
118                         Applicability::MachineApplicable,
119                     );
120                 });
121             }
122         );
123     }
124 }
125
126 /// Tries to determine the type for universal function call to be used instead of the closure
127 fn get_ufcs_type_name(
128     cx: &LateContext<'_, '_>,
129     method_def_id: def_id::DefId,
130     self_arg: &Expr,
131 ) -> std::option::Option<String> {
132     let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0];
133     let actual_type_of_self = &cx.tables.node_type(self_arg.hir_id);
134
135     if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) {
136         if match_borrow_depth(expected_type_of_self, &actual_type_of_self) {
137             return Some(cx.tcx.def_path_str(trait_id));
138         }
139     }
140
141     cx.tcx.impl_of_method(method_def_id).and_then(|_| {
142         //a type may implicitly implement other type's methods (e.g. Deref)
143         if match_types(expected_type_of_self, &actual_type_of_self) {
144             return Some(get_type_name(cx, &actual_type_of_self));
145         }
146         None
147     })
148 }
149
150 fn match_borrow_depth(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
151     match (&lhs.sty, &rhs.sty) {
152         (ty::Ref(_, t1, _), ty::Ref(_, t2, _)) => match_borrow_depth(&t1, &t2),
153         (l, r) => match (l, r) {
154             (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _)) => false,
155             (_, _) => true,
156         },
157     }
158 }
159
160 fn match_types(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
161     match (&lhs.sty, &rhs.sty) {
162         (ty::Bool, ty::Bool)
163         | (ty::Char, ty::Char)
164         | (ty::Int(_), ty::Int(_))
165         | (ty::Uint(_), ty::Uint(_))
166         | (ty::Str, ty::Str) => true,
167         (ty::Ref(_, t1, _), ty::Ref(_, t2, _))
168         | (ty::Array(t1, _), ty::Array(t2, _))
169         | (ty::Slice(t1), ty::Slice(t2)) => match_types(t1, t2),
170         (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2,
171         (_, _) => false,
172     }
173 }
174
175 fn get_type_name(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> String {
176     match ty.sty {
177         ty::Adt(t, _) => cx.tcx.def_path_str(t.did),
178         ty::Ref(_, r, _) => get_type_name(cx, &r),
179         _ => ty.to_string(),
180     }
181 }
182
183 fn compare_inputs(closure_inputs: &mut dyn Iterator<Item = &Arg>, call_args: &mut dyn Iterator<Item = &Expr>) -> bool {
184     for (closure_input, function_arg) in closure_inputs.zip(call_args) {
185         if let PatKind::Binding(_, _, ident, _) = closure_input.pat.node {
186             // XXXManishearth Should I be checking the binding mode here?
187             if let ExprKind::Path(QPath::Resolved(None, ref p)) = function_arg.node {
188                 if p.segments.len() != 1 {
189                     // If it's a proper path, it can't be a local variable
190                     return false;
191                 }
192                 if p.segments[0].ident.name != ident.name {
193                     // The two idents should be the same
194                     return false;
195                 }
196             } else {
197                 return false;
198             }
199         } else {
200             return false;
201         }
202     }
203     true
204 }