]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/eta_reduction.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / eta_reduction.rs
CommitLineData
cdc7bbd5
XL
1use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2use clippy_utils::higher;
3use clippy_utils::higher::VecArgs;
4use clippy_utils::source::snippet_opt;
5use clippy_utils::ty::{implements_trait, type_is_unsafe_function};
6use clippy_utils::{is_adjusted, iter_input_pats};
f20569fa
XL
7use if_chain::if_chain;
8use rustc_errors::Applicability;
9use rustc_hir::{def_id, Expr, ExprKind, Param, PatKind, QPath};
10use rustc_lint::{LateContext, LateLintPass, LintContext};
11use rustc_middle::lint::in_external_macro;
12use rustc_middle::ty::{self, Ty};
13use rustc_session::{declare_lint_pass, declare_tool_lint};
14
f20569fa
XL
15declare_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
43declare_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
67declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE, REDUNDANT_CLOSURE_FOR_METHOD_CALLS]);
68
69impl<'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() {
17df50a5 80 check_closure(cx, arg);
f20569fa
XL
81 }
82 }
83 },
84 _ => (),
85 }
86 }
87}
88
89fn check_closure(cx: &LateContext<'_>, expr: &Expr<'_>) {
cdc7bbd5 90 if let ExprKind::Closure(_, decl, eid, _, _) = expr.kind {
f20569fa
XL
91 let body = cx.tcx.hir().body(eid);
92 let ex = &body.value;
93
94 if ex.span.ctxt() != expr.span.ctxt() {
17df50a5
XL
95 if decl.inputs.is_empty() {
96 if let Some(VecArgs::Vec(&[])) = higher::vec_macro(cx, ex) {
97 // replace `|| vec![]` with `Vec::new`
98 span_lint_and_sugg(
99 cx,
100 REDUNDANT_CLOSURE,
101 expr.span,
102 "redundant closure",
103 "replace the closure with `Vec::new`",
104 "std::vec::Vec::new".into(),
105 Applicability::MachineApplicable,
106 );
107 }
f20569fa
XL
108 }
109 // skip `foo(|| macro!())`
110 return;
111 }
112
113 if_chain!(
cdc7bbd5 114 if let ExprKind::Call(caller, args) = ex.kind;
f20569fa
XL
115
116 if let ExprKind::Path(_) = caller.kind;
117
118 // Not the same number of arguments, there is no way the closure is the same as the function return;
119 if args.len() == decl.inputs.len();
120
121 // Are the expression or the arguments type-adjusted? Then we need the closure
122 if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)));
123
124 let fn_ty = cx.typeck_results().expr_ty(caller);
125
126 if matches!(fn_ty.kind(), ty::FnDef(_, _) | ty::FnPtr(_) | ty::Closure(_, _));
127
128 if !type_is_unsafe_function(cx, fn_ty);
129
130 if compare_inputs(&mut iter_input_pats(decl, body), &mut args.iter());
131
132 then {
133 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure", |diag| {
134 if let Some(snippet) = snippet_opt(cx, caller.span) {
135 diag.span_suggestion(
136 expr.span,
137 "replace the closure with the function itself",
138 snippet,
139 Applicability::MachineApplicable,
140 );
141 }
142 });
143 }
144 );
145
146 if_chain!(
cdc7bbd5 147 if let ExprKind::MethodCall(path, _, args, _) = ex.kind;
f20569fa
XL
148
149 // Not the same number of arguments, there is no way the closure is the same as the function return;
150 if args.len() == decl.inputs.len();
151
152 // Are the expression or the arguments type-adjusted? Then we need the closure
153 if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg)));
154
155 let method_def_id = cx.typeck_results().type_dependent_def_id(ex.hir_id).unwrap();
156 if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id));
157
158 if compare_inputs(&mut iter_input_pats(decl, body), &mut args.iter());
159
160 if let Some(name) = get_ufcs_type_name(cx, method_def_id, &args[0]);
161
162 then {
163 span_lint_and_sugg(
164 cx,
165 REDUNDANT_CLOSURE_FOR_METHOD_CALLS,
166 expr.span,
167 "redundant closure",
168 "replace the closure with the method itself",
169 format!("{}::{}", name, path.ident.name),
170 Applicability::MachineApplicable,
171 );
172 }
173 );
174 }
175}
176
177/// Tries to determine the type for universal function call to be used instead of the closure
178fn get_ufcs_type_name(cx: &LateContext<'_>, method_def_id: def_id::DefId, self_arg: &Expr<'_>) -> Option<String> {
179 let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0];
180 let actual_type_of_self = &cx.typeck_results().node_type(self_arg.hir_id);
181
182 if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) {
cdc7bbd5 183 if match_borrow_depth(expected_type_of_self, actual_type_of_self)
f20569fa
XL
184 && implements_trait(cx, actual_type_of_self, trait_id, &[])
185 {
186 return Some(cx.tcx.def_path_str(trait_id));
187 }
188 }
189
190 cx.tcx.impl_of_method(method_def_id).and_then(|_| {
191 //a type may implicitly implement other type's methods (e.g. Deref)
cdc7bbd5 192 if match_types(expected_type_of_self, actual_type_of_self) {
17df50a5
XL
193 Some(get_type_name(cx, actual_type_of_self))
194 } else {
195 None
f20569fa 196 }
f20569fa
XL
197 })
198}
199
200fn match_borrow_depth(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
201 match (&lhs.kind(), &rhs.kind()) {
cdc7bbd5 202 (ty::Ref(_, t1, mut1), ty::Ref(_, t2, mut2)) => mut1 == mut2 && match_borrow_depth(t1, t2),
f20569fa
XL
203 (l, r) => !matches!((l, r), (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _))),
204 }
205}
206
207fn match_types(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
208 match (&lhs.kind(), &rhs.kind()) {
209 (ty::Bool, ty::Bool)
210 | (ty::Char, ty::Char)
211 | (ty::Int(_), ty::Int(_))
212 | (ty::Uint(_), ty::Uint(_))
213 | (ty::Str, ty::Str) => true,
214 (ty::Ref(_, t1, mut1), ty::Ref(_, t2, mut2)) => mut1 == mut2 && match_types(t1, t2),
215 (ty::Array(t1, _), ty::Array(t2, _)) | (ty::Slice(t1), ty::Slice(t2)) => match_types(t1, t2),
216 (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2,
217 (_, _) => false,
218 }
219}
220
221fn get_type_name(cx: &LateContext<'_>, ty: Ty<'_>) -> String {
222 match ty.kind() {
223 ty::Adt(t, _) => cx.tcx.def_path_str(t.did),
cdc7bbd5 224 ty::Ref(_, r, _) => get_type_name(cx, r),
f20569fa
XL
225 _ => ty.to_string(),
226 }
227}
228
229fn compare_inputs(
230 closure_inputs: &mut dyn Iterator<Item = &Param<'_>>,
231 call_args: &mut dyn Iterator<Item = &Expr<'_>>,
232) -> bool {
233 for (closure_input, function_arg) in closure_inputs.zip(call_args) {
234 if let PatKind::Binding(_, _, ident, _) = closure_input.pat.kind {
235 // XXXManishearth Should I be checking the binding mode here?
cdc7bbd5 236 if let ExprKind::Path(QPath::Resolved(None, p)) = function_arg.kind {
f20569fa
XL
237 if p.segments.len() != 1 {
238 // If it's a proper path, it can't be a local variable
239 return false;
240 }
241 if p.segments[0].ident.name != ident.name {
242 // The two idents should be the same
243 return false;
244 }
245 } else {
246 return false;
247 }
248 } else {
249 return false;
250 }
251 }
252 true
253}