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