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