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