]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/unnecessary_lazy_eval.rs
740af750b48a7bdaf9fc1a50d47cd1392e21fb1e
[rust.git] / clippy_lints / src / methods / unnecessary_lazy_eval.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
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;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_span::sym;
9
10 use super::UNNECESSARY_LAZY_EVALUATIONS;
11
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<'_>,
19     simplify_using: &str,
20 ) {
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
24     if is_option || is_result {
25         if let hir::ExprKind::Closure(_, _, eid, _, _) = arg.kind {
26             let body = cx.tcx.hir().body(eid);
27             let body_expr = &body.value;
28
29             if usage::BindingUsageFinder::are_params_used(cx, body) {
30                 return;
31             }
32
33             if eager_or_lazy::is_eagerness_candidate(cx, body_expr) {
34                 let msg = if is_option {
35                     "unnecessary closure used to substitute value for `Option::None`"
36                 } else {
37                     "unnecessary closure used to substitute value for `Result::Err`"
38                 };
39                 let applicability = if body
40                     .params
41                     .iter()
42                     // bindings are checked to be unused above
43                     .all(|param| matches!(param.pat.kind, hir::PatKind::Binding(..) | hir::PatKind::Wild))
44                 {
45                     Applicability::MachineApplicable
46                 } else {
47                     // replacing the lambda may break type inference
48                     Applicability::MaybeIncorrect
49                 };
50
51                 span_lint_and_sugg(
52                     cx,
53                     UNNECESSARY_LAZY_EVALUATIONS,
54                     expr.span,
55                     msg,
56                     &format!("use `{}` instead", simplify_using),
57                     format!(
58                         "{0}.{1}({2})",
59                         snippet(cx, recv.span, ".."),
60                         simplify_using,
61                         snippet(cx, body_expr.span, ".."),
62                     ),
63                     applicability,
64                 );
65             }
66         }
67     }
68 }