2021-03-25 19:29:11 +01:00
|
|
|
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
|
|
|
|
use clippy_utils::higher::VecArgs;
|
|
|
|
use clippy_utils::source::snippet_opt;
|
2022-10-06 09:44:38 +02:00
|
|
|
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
|
2021-12-06 12:33:31 +01:00
|
|
|
use clippy_utils::usage::local_used_after_expr;
|
2022-05-05 15:12:52 +01:00
|
|
|
use clippy_utils::{higher, is_adjusted, path_to_local, path_to_local_id};
|
2019-02-10 12:58:51 +01:00
|
|
|
use if_chain::if_chain;
|
2018-12-29 16:04:45 +01:00
|
|
|
use rustc_errors::Applicability;
|
2021-09-28 18:03:12 +01:00
|
|
|
use rustc_hir::def_id::DefId;
|
2022-06-30 14:18:51 +04:00
|
|
|
use rustc_hir::{Closure, Expr, ExprKind, Param, PatKind, Unsafety};
|
2021-09-28 18:03:12 +01:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
|
|
|
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
|
2022-02-26 14:26:21 +01:00
|
|
|
use rustc_middle::ty::binding::BindingMode;
|
2023-02-22 02:18:40 +00:00
|
|
|
use rustc_middle::ty::{self, EarlyBinder, SubstsRef, Ty, TypeVisitableExt};
|
2020-01-11 20:37:08 +09:00
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2022-01-13 13:18:19 +01:00
|
|
|
use rustc_span::symbol::sym;
|
2015-07-26 20:23:11 +05:30
|
|
|
|
2018-03-28 15:24:26 +02:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for closures which just call another function where
|
2019-03-05 11:50:33 -05:00
|
|
|
/// the function can be called directly. `unsafe` functions or calls where types
|
|
|
|
/// get adjusted are ignored.
|
|
|
|
///
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Needlessly creating a closure adds code for no benefit
|
2019-03-05 11:50:33 -05:00
|
|
|
/// and gives the optimizer more work.
|
|
|
|
///
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### Known problems
|
|
|
|
/// If creating the closure inside the closure has a side-
|
2019-03-05 11:50:33 -05:00
|
|
|
/// effect then moving the closure creation out will change when that side-
|
|
|
|
/// effect runs.
|
2021-01-15 10:56:44 +01:00
|
|
|
/// See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details.
|
2019-03-05 11:50:33 -05:00
|
|
|
///
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### Example
|
2019-03-10 23:01:56 +01:00
|
|
|
/// ```rust,ignore
|
2019-03-05 11:50:33 -05:00
|
|
|
/// xs.map(|x| foo(x))
|
2022-06-16 17:39:06 +02:00
|
|
|
/// ```
|
2020-06-09 14:36:01 +00:00
|
|
|
///
|
2022-06-16 17:39:06 +02:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// // where `foo(_)` is a plain function that takes the exact argument type of `x`.
|
2020-06-09 14:36:01 +00:00
|
|
|
/// xs.map(foo)
|
2019-03-05 11:50:33 -05:00
|
|
|
/// ```
|
2021-12-06 12:33:31 +01:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2016-08-06 10:18:36 +02:00
|
|
|
pub REDUNDANT_CLOSURE,
|
2018-03-28 15:24:26 +02:00
|
|
|
style,
|
2019-01-31 01:15:29 +00:00
|
|
|
"redundant closures, i.e., `|a| foo(a)` (which can be written as just `foo`)"
|
2016-02-06 00:13:29 +01:00
|
|
|
}
|
2015-05-10 10:39:04 +05:30
|
|
|
|
2019-05-16 08:25:39 +02:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for closures which only invoke a method on the closure
|
2019-05-16 08:25:39 +02:00
|
|
|
/// argument and can be replaced by referencing the method directly.
|
|
|
|
///
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// It's unnecessary to create the closure.
|
2019-05-16 08:25:39 +02:00
|
|
|
///
|
2021-07-29 12:16:06 +02:00
|
|
|
/// ### Example
|
2019-05-16 08:25:39 +02:00
|
|
|
/// ```rust,ignore
|
|
|
|
/// Some('a').map(|s| s.to_uppercase());
|
|
|
|
/// ```
|
|
|
|
/// may be rewritten as
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// Some('a').map(char::to_uppercase);
|
|
|
|
/// ```
|
2021-12-06 12:33:31 +01:00
|
|
|
#[clippy::version = "1.35.0"]
|
2019-05-16 09:18:15 -07:00
|
|
|
pub REDUNDANT_CLOSURE_FOR_METHOD_CALLS,
|
2019-05-16 08:25:39 +02:00
|
|
|
pedantic,
|
|
|
|
"redundant closures for method calls"
|
|
|
|
}
|
|
|
|
|
2019-05-16 09:18:15 -07:00
|
|
|
declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE, REDUNDANT_CLOSURE_FOR_METHOD_CALLS]);
|
2015-05-10 10:39:04 +05:30
|
|
|
|
2020-06-25 23:41:36 +03:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for EtaReduction {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
2021-09-28 18:03:12 +01:00
|
|
|
if expr.span.from_expansion() {
|
2019-02-25 13:40:28 +01:00
|
|
|
return;
|
|
|
|
}
|
2021-09-28 18:03:12 +01:00
|
|
|
let body = match expr.kind {
|
2022-06-30 14:18:51 +04:00
|
|
|
ExprKind::Closure(&Closure { body, .. }) => cx.tcx.hir().body(body),
|
2021-09-28 18:03:12 +01:00
|
|
|
_ => return,
|
|
|
|
};
|
|
|
|
if body.value.span.from_expansion() {
|
|
|
|
if body.params.is_empty() {
|
2022-09-09 13:36:26 +02:00
|
|
|
if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, body.value) {
|
2021-06-03 08:41:37 +02:00
|
|
|
// replace `|| vec![]` with `Vec::new`
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
REDUNDANT_CLOSURE,
|
|
|
|
expr.span,
|
|
|
|
"redundant closure",
|
|
|
|
"replace the closure with `Vec::new`",
|
|
|
|
"std::vec::Vec::new".into(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
2021-03-12 15:30:50 +01:00
|
|
|
}
|
|
|
|
// skip `foo(|| macro!())`
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-28 18:03:12 +01:00
|
|
|
let closure_ty = cx.typeck_results().expr_ty(expr);
|
2019-02-10 12:58:51 +01:00
|
|
|
|
2021-09-28 18:03:12 +01:00
|
|
|
if_chain!(
|
2022-09-09 13:36:26 +02:00
|
|
|
if !is_adjusted(cx, body.value);
|
2021-09-28 18:03:12 +01:00
|
|
|
if let ExprKind::Call(callee, args) = body.value.kind;
|
|
|
|
if let ExprKind::Path(_) = callee.kind;
|
2022-09-01 18:43:35 +09:00
|
|
|
if check_inputs(cx, body.params, None, args);
|
2021-09-28 18:03:12 +01:00
|
|
|
let callee_ty = cx.typeck_results().expr_ty_adjusted(callee);
|
|
|
|
let call_ty = cx.typeck_results().type_dependent_def_id(body.value.hir_id)
|
2023-02-07 01:29:48 -07:00
|
|
|
.map_or(callee_ty, |id| cx.tcx.type_of(id).subst_identity());
|
2021-09-28 18:03:12 +01:00
|
|
|
if check_sig(cx, closure_ty, call_ty);
|
|
|
|
let substs = cx.typeck_results().node_substs(callee.hir_id);
|
|
|
|
// This fixes some false positives that I don't entirely understand
|
|
|
|
if substs.is_empty() || !cx.typeck_results().expr_ty(expr).has_late_bound_regions();
|
|
|
|
// A type param function ref like `T::f` is not 'static, however
|
|
|
|
// it is if cast like `T::f as fn()`. This seems like a rustc bug.
|
|
|
|
if !substs.types().any(|t| matches!(t.kind(), ty::Param(_)));
|
2022-01-13 13:18:19 +01:00
|
|
|
let callee_ty_unadjusted = cx.typeck_results().expr_ty(callee).peel_refs();
|
|
|
|
if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Arc);
|
|
|
|
if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Rc);
|
2022-11-18 19:58:07 +00:00
|
|
|
if let ty::Closure(_, substs) = *closure_ty.kind();
|
2019-02-10 12:58:51 +01:00
|
|
|
then {
|
2021-03-12 15:30:50 +01:00
|
|
|
span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure", |diag| {
|
2021-09-28 18:03:12 +01:00
|
|
|
if let Some(mut snippet) = snippet_opt(cx, callee.span) {
|
2022-10-06 09:44:38 +02:00
|
|
|
if let Some(fn_mut_id) = cx.tcx.lang_items().fn_mut_trait()
|
2022-11-21 16:52:01 +01:00
|
|
|
&& let args = cx.tcx.erase_late_bound_regions(substs.as_closure().sig()).inputs()
|
2022-12-01 18:29:38 +01:00
|
|
|
&& implements_trait(
|
|
|
|
cx,
|
|
|
|
callee_ty.peel_refs(),
|
|
|
|
fn_mut_id,
|
|
|
|
&args.iter().copied().map(Into::into).collect::<Vec<_>>(),
|
|
|
|
)
|
2022-10-06 09:44:38 +02:00
|
|
|
&& path_to_local(callee).map_or(false, |l| local_used_after_expr(cx, l, expr))
|
|
|
|
{
|
2021-07-15 10:44:10 +02:00
|
|
|
// Mutable closure is used after current expr; we cannot consume it.
|
2022-10-06 09:44:38 +02:00
|
|
|
snippet = format!("&mut {snippet}");
|
2021-07-15 10:44:10 +02:00
|
|
|
}
|
2020-04-17 08:08:00 +02:00
|
|
|
diag.span_suggestion(
|
2019-02-10 12:58:51 +01:00
|
|
|
expr.span,
|
2021-03-12 15:30:50 +01:00
|
|
|
"replace the closure with the function itself",
|
2019-02-10 12:58:51 +01:00
|
|
|
snippet,
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
2016-11-16 21:57:56 +01:00
|
|
|
}
|
2019-02-10 12:58:51 +01:00
|
|
|
});
|
2016-11-16 21:57:56 +01:00
|
|
|
}
|
2019-02-10 12:58:51 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
if_chain!(
|
2022-09-09 13:36:26 +02:00
|
|
|
if !is_adjusted(cx, body.value);
|
2022-09-01 18:43:35 +09:00
|
|
|
if let ExprKind::MethodCall(path, receiver, args, _) = body.value.kind;
|
|
|
|
if check_inputs(cx, body.params, Some(receiver), args);
|
2021-09-28 18:03:12 +01:00
|
|
|
let method_def_id = cx.typeck_results().type_dependent_def_id(body.value.hir_id).unwrap();
|
|
|
|
let substs = cx.typeck_results().node_substs(body.value.hir_id);
|
2023-02-07 01:29:48 -07:00
|
|
|
let call_ty = cx.tcx.type_of(method_def_id).subst(cx.tcx, substs);
|
2021-09-28 18:03:12 +01:00
|
|
|
if check_sig(cx, closure_ty, call_ty);
|
2019-02-10 12:58:51 +01:00
|
|
|
then {
|
2021-09-28 18:03:12 +01:00
|
|
|
span_lint_and_then(cx, REDUNDANT_CLOSURE_FOR_METHOD_CALLS, expr.span, "redundant closure", |diag| {
|
2022-12-01 18:29:38 +01:00
|
|
|
let name = get_ufcs_type_name(cx, method_def_id, substs);
|
2021-09-28 18:03:12 +01:00
|
|
|
diag.span_suggestion(
|
|
|
|
expr.span,
|
|
|
|
"replace the closure with the method itself",
|
2022-10-06 09:44:38 +02:00
|
|
|
format!("{name}::{}", path.ident.name),
|
2021-09-28 18:03:12 +01:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
})
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-01 18:43:35 +09:00
|
|
|
fn check_inputs(
|
|
|
|
cx: &LateContext<'_>,
|
|
|
|
params: &[Param<'_>],
|
|
|
|
receiver: Option<&Expr<'_>>,
|
|
|
|
call_args: &[Expr<'_>],
|
|
|
|
) -> bool {
|
|
|
|
if receiver.map_or(params.len() != call_args.len(), |_| params.len() != call_args.len() + 1) {
|
2021-09-28 18:03:12 +01:00
|
|
|
return false;
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
2022-02-26 14:26:21 +01:00
|
|
|
let binding_modes = cx.typeck_results().pat_binding_modes();
|
2022-09-01 18:43:35 +09:00
|
|
|
let check_inputs = |param: &Param<'_>, arg| {
|
2021-09-28 18:03:12 +01:00
|
|
|
match param.pat.kind {
|
|
|
|
PatKind::Binding(_, id, ..) if path_to_local_id(arg, id) => {},
|
|
|
|
_ => return false,
|
|
|
|
}
|
2022-02-26 14:26:21 +01:00
|
|
|
// checks that parameters are not bound as `ref` or `ref mut`
|
|
|
|
if let Some(BindingMode::BindByReference(_)) = binding_modes.get(param.pat.hir_id) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2021-09-28 18:03:12 +01:00
|
|
|
match *cx.typeck_results().expr_adjustments(arg) {
|
|
|
|
[] => true,
|
2021-11-04 12:52:36 +00:00
|
|
|
[
|
|
|
|
Adjustment {
|
|
|
|
kind: Adjust::Deref(None),
|
|
|
|
..
|
|
|
|
},
|
|
|
|
Adjustment {
|
|
|
|
kind: Adjust::Borrow(AutoBorrow::Ref(_, mu2)),
|
|
|
|
..
|
|
|
|
},
|
|
|
|
] => {
|
2021-09-28 18:03:12 +01:00
|
|
|
// re-borrow with the same mutability is allowed
|
|
|
|
let ty = cx.typeck_results().expr_ty(arg);
|
|
|
|
matches!(*ty.kind(), ty::Ref(.., mu1) if mu1 == mu2.into())
|
|
|
|
},
|
|
|
|
_ => false,
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
2022-09-01 18:43:35 +09:00
|
|
|
};
|
2022-09-09 13:36:26 +02:00
|
|
|
std::iter::zip(params, receiver.into_iter().chain(call_args.iter())).all(|(param, arg)| check_inputs(param, arg))
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
|
|
|
|
2021-09-28 18:03:12 +01:00
|
|
|
fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure_ty: Ty<'tcx>, call_ty: Ty<'tcx>) -> bool {
|
|
|
|
let call_sig = call_ty.fn_sig(cx.tcx);
|
|
|
|
if call_sig.unsafety() == Unsafety::Unsafe {
|
|
|
|
return false;
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
2021-09-28 18:03:12 +01:00
|
|
|
if !closure_ty.has_late_bound_regions() {
|
|
|
|
return true;
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
2022-10-23 15:18:45 +02:00
|
|
|
let ty::Closure(_, substs) = closure_ty.kind() else {
|
|
|
|
return false;
|
2021-09-28 18:03:12 +01:00
|
|
|
};
|
|
|
|
let closure_sig = cx.tcx.signature_unclosure(substs.as_closure().sig(), Unsafety::Normal);
|
|
|
|
cx.tcx.erase_late_bound_regions(closure_sig) == cx.tcx.erase_late_bound_regions(call_sig)
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
|
|
|
|
2022-12-01 18:29:38 +01:00
|
|
|
fn get_ufcs_type_name<'tcx>(cx: &LateContext<'tcx>, method_def_id: DefId, substs: SubstsRef<'tcx>) -> String {
|
2022-03-13 00:52:25 +01:00
|
|
|
let assoc_item = cx.tcx.associated_item(method_def_id);
|
|
|
|
let def_id = assoc_item.container_id(cx.tcx);
|
|
|
|
match assoc_item.container {
|
|
|
|
ty::TraitContainer => cx.tcx.def_path_str(def_id),
|
|
|
|
ty::ImplContainer => {
|
2023-02-07 01:29:48 -07:00
|
|
|
let ty = cx.tcx.type_of(def_id).skip_binder();
|
2021-09-28 18:03:12 +01:00
|
|
|
match ty.kind() {
|
2022-03-05 07:28:41 +11:00
|
|
|
ty::Adt(adt, _) => cx.tcx.def_path_str(adt.did()),
|
2022-12-01 18:29:38 +01:00
|
|
|
ty::Array(..)
|
|
|
|
| ty::Dynamic(..)
|
|
|
|
| ty::Never
|
|
|
|
| ty::RawPtr(_)
|
|
|
|
| ty::Ref(..)
|
|
|
|
| ty::Slice(_)
|
|
|
|
| ty::Tuple(_) => {
|
|
|
|
format!("<{}>", EarlyBinder(ty).subst(cx.tcx, substs))
|
|
|
|
},
|
2021-09-28 18:03:12 +01:00
|
|
|
_ => ty.to_string(),
|
2019-02-10 12:58:51 +01:00
|
|
|
}
|
2021-09-28 18:03:12 +01:00
|
|
|
},
|
2015-05-10 10:39:04 +05:30
|
|
|
}
|
|
|
|
}
|