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