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