1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{eager_or_lazy, usage};
5 use rustc_errors::Applicability;
7 use rustc_lint::LateContext;
10 use super::UNNECESSARY_LAZY_EVALUATIONS;
12 /// lint use of `<fn>_else(simple closure)` for `Option`s and `Result`s that can be
13 /// replaced with `<fn>(return value of simple closure)`
14 pub(super) fn check<'tcx>(
15 cx: &LateContext<'tcx>,
16 expr: &'tcx hir::Expr<'_>,
17 recv: &'tcx hir::Expr<'_>,
18 arg: &'tcx hir::Expr<'_>,
21 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Option);
22 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result);
23 let is_bool = cx.typeck_results().expr_ty(recv).is_bool();
25 if is_option || is_result || is_bool {
26 if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = arg.kind {
27 let body = cx.tcx.hir().body(body);
28 let body_expr = &body.value;
30 if usage::BindingUsageFinder::are_params_used(cx, body) {
34 if eager_or_lazy::switch_to_eager_eval(cx, body_expr) {
35 let msg = if is_option {
36 "unnecessary closure used to substitute value for `Option::None`"
38 "unnecessary closure used to substitute value for `Result::Err`"
40 "unnecessary closure used with `bool::then`"
42 let applicability = if body
45 // bindings are checked to be unused above
46 .all(|param| matches!(param.pat.kind, hir::PatKind::Binding(..) | hir::PatKind::Wild))
48 Applicability::MachineApplicable
50 // replacing the lambda may break type inference
51 Applicability::MaybeIncorrect
54 // This is a duplicate of what's happening in clippy_lints::methods::method_call,
55 // which isn't ideal, We want to get the method call span,
56 // but prefer to avoid changing the signature of the function itself.
57 if let hir::ExprKind::MethodCall(_, _, span) = expr.kind {
58 span_lint_and_then(cx, UNNECESSARY_LAZY_EVALUATIONS, expr.span, msg, |diag| {
61 &format!("use `{}(..)` instead", simplify_using),
62 format!("{}({})", simplify_using, snippet(cx, body_expr.span, "..")),