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