]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/eta_reduction.rs
Rollup merge of #105123 - BlackHoleFox:fixing-the-macos-deployment, r=oli-obk
[rust.git] / src / tools / clippy / 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, is_type_diagnostic_item};
5 use clippy_utils::usage::local_used_after_expr;
6 use clippy_utils::{higher, is_adjusted, path_to_local, path_to_local_id};
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::{Closure, Expr, ExprKind, Param, PatKind, Unsafety};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
13 use rustc_middle::ty::binding::BindingMode;
14 use rustc_middle::ty::{self, EarlyBinder, SubstsRef, Ty, TypeVisitable};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::symbol::sym;
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Checks for closures which just call another function where
21     /// the function can be called directly. `unsafe` functions or calls where types
22     /// get adjusted are ignored.
23     ///
24     /// ### Why is this bad?
25     /// Needlessly creating a closure adds code for no benefit
26     /// and gives the optimizer more work.
27     ///
28     /// ### Known problems
29     /// If creating the closure inside the closure has a side-
30     /// effect then moving the closure creation out will change when that side-
31     /// effect runs.
32     /// See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details.
33     ///
34     /// ### Example
35     /// ```rust,ignore
36     /// xs.map(|x| foo(x))
37     /// ```
38     ///
39     /// Use instead:
40     /// ```rust,ignore
41     /// // where `foo(_)` is a plain function that takes the exact argument type of `x`.
42     /// xs.map(foo)
43     /// ```
44     #[clippy::version = "pre 1.29.0"]
45     pub REDUNDANT_CLOSURE,
46     style,
47     "redundant closures, i.e., `|a| foo(a)` (which can be written as just `foo`)"
48 }
49
50 declare_clippy_lint! {
51     /// ### What it does
52     /// Checks for closures which only invoke a method on the closure
53     /// argument and can be replaced by referencing the method directly.
54     ///
55     /// ### Why is this bad?
56     /// It's unnecessary to create the closure.
57     ///
58     /// ### Example
59     /// ```rust,ignore
60     /// Some('a').map(|s| s.to_uppercase());
61     /// ```
62     /// may be rewritten as
63     /// ```rust,ignore
64     /// Some('a').map(char::to_uppercase);
65     /// ```
66     #[clippy::version = "1.35.0"]
67     pub REDUNDANT_CLOSURE_FOR_METHOD_CALLS,
68     pedantic,
69     "redundant closures for method calls"
70 }
71
72 declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE, REDUNDANT_CLOSURE_FOR_METHOD_CALLS]);
73
74 impl<'tcx> LateLintPass<'tcx> for EtaReduction {
75     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
76         if expr.span.from_expansion() {
77             return;
78         }
79         let body = match expr.kind {
80             ExprKind::Closure(&Closure { body, .. }) => cx.tcx.hir().body(body),
81             _ => return,
82         };
83         if body.value.span.from_expansion() {
84             if body.params.is_empty() {
85                 if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, body.value) {
86                     // replace `|| vec![]` with `Vec::new`
87                     span_lint_and_sugg(
88                         cx,
89                         REDUNDANT_CLOSURE,
90                         expr.span,
91                         "redundant closure",
92                         "replace the closure with `Vec::new`",
93                         "std::vec::Vec::new".into(),
94                         Applicability::MachineApplicable,
95                     );
96                 }
97             }
98             // skip `foo(|| macro!())`
99             return;
100         }
101
102         let closure_ty = cx.typeck_results().expr_ty(expr);
103
104         if_chain!(
105             if !is_adjusted(cx, body.value);
106             if let ExprKind::Call(callee, args) = body.value.kind;
107             if let ExprKind::Path(_) = callee.kind;
108             if check_inputs(cx, body.params, None, args);
109             let callee_ty = cx.typeck_results().expr_ty_adjusted(callee);
110             let call_ty = cx.typeck_results().type_dependent_def_id(body.value.hir_id)
111                 .map_or(callee_ty, |id| cx.tcx.type_of(id));
112             if check_sig(cx, closure_ty, call_ty);
113             let substs = cx.typeck_results().node_substs(callee.hir_id);
114             // This fixes some false positives that I don't entirely understand
115             if substs.is_empty() || !cx.typeck_results().expr_ty(expr).has_late_bound_regions();
116             // A type param function ref like `T::f` is not 'static, however
117             // it is if cast like `T::f as fn()`. This seems like a rustc bug.
118             if !substs.types().any(|t| matches!(t.kind(), ty::Param(_)));
119             let callee_ty_unadjusted = cx.typeck_results().expr_ty(callee).peel_refs();
120             if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Arc);
121             if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Rc);
122             if let ty::Closure(_, substs) = *closure_ty.kind();
123             then {
124                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure", |diag| {
125                     if let Some(mut snippet) = snippet_opt(cx, callee.span) {
126                         if let Some(fn_mut_id) = cx.tcx.lang_items().fn_mut_trait()
127                             && let args = cx.tcx.erase_late_bound_regions(substs.as_closure().sig()).inputs()
128                             && implements_trait(
129                                    cx,
130                                    callee_ty.peel_refs(),
131                                    fn_mut_id,
132                                    &args.iter().copied().map(Into::into).collect::<Vec<_>>(),
133                                )
134                             && path_to_local(callee).map_or(false, |l| local_used_after_expr(cx, l, expr))
135                         {
136                                 // Mutable closure is used after current expr; we cannot consume it.
137                                 snippet = format!("&mut {snippet}");
138                         }
139                         diag.span_suggestion(
140                             expr.span,
141                             "replace the closure with the function itself",
142                             snippet,
143                             Applicability::MachineApplicable,
144                         );
145                     }
146                 });
147             }
148         );
149
150         if_chain!(
151             if !is_adjusted(cx, body.value);
152             if let ExprKind::MethodCall(path, receiver, args, _) = body.value.kind;
153             if check_inputs(cx, body.params, Some(receiver), args);
154             let method_def_id = cx.typeck_results().type_dependent_def_id(body.value.hir_id).unwrap();
155             let substs = cx.typeck_results().node_substs(body.value.hir_id);
156             let call_ty = cx.tcx.bound_type_of(method_def_id).subst(cx.tcx, substs);
157             if check_sig(cx, closure_ty, call_ty);
158             then {
159                 span_lint_and_then(cx, REDUNDANT_CLOSURE_FOR_METHOD_CALLS, expr.span, "redundant closure", |diag| {
160                     let name = get_ufcs_type_name(cx, method_def_id, substs);
161                     diag.span_suggestion(
162                         expr.span,
163                         "replace the closure with the method itself",
164                         format!("{name}::{}", path.ident.name),
165                         Applicability::MachineApplicable,
166                     );
167                 })
168             }
169         );
170     }
171 }
172
173 fn check_inputs(
174     cx: &LateContext<'_>,
175     params: &[Param<'_>],
176     receiver: Option<&Expr<'_>>,
177     call_args: &[Expr<'_>],
178 ) -> bool {
179     if receiver.map_or(params.len() != call_args.len(), |_| params.len() != call_args.len() + 1) {
180         return false;
181     }
182     let binding_modes = cx.typeck_results().pat_binding_modes();
183     let check_inputs = |param: &Param<'_>, arg| {
184         match param.pat.kind {
185             PatKind::Binding(_, id, ..) if path_to_local_id(arg, id) => {},
186             _ => return false,
187         }
188         // checks that parameters are not bound as `ref` or `ref mut`
189         if let Some(BindingMode::BindByReference(_)) = binding_modes.get(param.pat.hir_id) {
190             return false;
191         }
192
193         match *cx.typeck_results().expr_adjustments(arg) {
194             [] => true,
195             [
196                 Adjustment {
197                     kind: Adjust::Deref(None),
198                     ..
199                 },
200                 Adjustment {
201                     kind: Adjust::Borrow(AutoBorrow::Ref(_, mu2)),
202                     ..
203                 },
204             ] => {
205                 // re-borrow with the same mutability is allowed
206                 let ty = cx.typeck_results().expr_ty(arg);
207                 matches!(*ty.kind(), ty::Ref(.., mu1) if mu1 == mu2.into())
208             },
209             _ => false,
210         }
211     };
212     std::iter::zip(params, receiver.into_iter().chain(call_args.iter())).all(|(param, arg)| check_inputs(param, arg))
213 }
214
215 fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure_ty: Ty<'tcx>, call_ty: Ty<'tcx>) -> bool {
216     let call_sig = call_ty.fn_sig(cx.tcx);
217     if call_sig.unsafety() == Unsafety::Unsafe {
218         return false;
219     }
220     if !closure_ty.has_late_bound_regions() {
221         return true;
222     }
223     let ty::Closure(_, substs) = closure_ty.kind() else {
224         return false;
225     };
226     let closure_sig = cx.tcx.signature_unclosure(substs.as_closure().sig(), Unsafety::Normal);
227     cx.tcx.erase_late_bound_regions(closure_sig) == cx.tcx.erase_late_bound_regions(call_sig)
228 }
229
230 fn get_ufcs_type_name<'tcx>(cx: &LateContext<'tcx>, method_def_id: DefId, substs: SubstsRef<'tcx>) -> String {
231     let assoc_item = cx.tcx.associated_item(method_def_id);
232     let def_id = assoc_item.container_id(cx.tcx);
233     match assoc_item.container {
234         ty::TraitContainer => cx.tcx.def_path_str(def_id),
235         ty::ImplContainer => {
236             let ty = cx.tcx.type_of(def_id);
237             match ty.kind() {
238                 ty::Adt(adt, _) => cx.tcx.def_path_str(adt.did()),
239                 ty::Array(..)
240                 | ty::Dynamic(..)
241                 | ty::Never
242                 | ty::RawPtr(_)
243                 | ty::Ref(..)
244                 | ty::Slice(_)
245                 | ty::Tuple(_) => {
246                     format!("<{}>", EarlyBinder(ty).subst(cx.tcx, substs))
247                 },
248                 _ => ty.to_string(),
249             }
250         },
251     }
252 }