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