]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs
Rollup merge of #94145 - ssomers:binary_heap_tests, r=jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / methods / manual_ok_or.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::{indent_of, reindent_multiline, snippet_opt};
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{is_res_lang_ctor, path_res, path_to_local_id};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::LangItem::{ResultErr, ResultOk};
8 use rustc_hir::{Expr, ExprKind, PatKind};
9 use rustc_lint::LateContext;
10 use rustc_span::symbol::sym;
11
12 use super::MANUAL_OK_OR;
13
14 pub(super) fn check<'tcx>(
15     cx: &LateContext<'tcx>,
16     expr: &'tcx Expr<'tcx>,
17     recv: &'tcx Expr<'_>,
18     or_expr: &'tcx Expr<'_>,
19     map_expr: &'tcx Expr<'_>,
20 ) {
21     if_chain! {
22         if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
23         if let Some(impl_id) = cx.tcx.impl_of_method(method_id);
24         if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id), sym::Option);
25         if let ExprKind::Call(err_path, [err_arg]) = or_expr.kind;
26         if is_res_lang_ctor(cx, path_res(cx, err_path), ResultErr);
27         if is_ok_wrapping(cx, map_expr);
28         if let Some(recv_snippet) = snippet_opt(cx, recv.span);
29         if let Some(err_arg_snippet) = snippet_opt(cx, err_arg.span);
30         if let Some(indent) = indent_of(cx, expr.span);
31         then {
32             let reindented_err_arg_snippet = reindent_multiline(err_arg_snippet.into(), true, Some(indent + 4));
33             span_lint_and_sugg(
34                 cx,
35                 MANUAL_OK_OR,
36                 expr.span,
37                 "this pattern reimplements `Option::ok_or`",
38                 "replace with",
39                 format!(
40                     "{recv_snippet}.ok_or({reindented_err_arg_snippet})"
41                 ),
42                 Applicability::MachineApplicable,
43             );
44         }
45     }
46 }
47
48 fn is_ok_wrapping(cx: &LateContext<'_>, map_expr: &Expr<'_>) -> bool {
49     match map_expr.kind {
50         ExprKind::Path(ref qpath) if is_res_lang_ctor(cx, cx.qpath_res(qpath, map_expr.hir_id), ResultOk) => true,
51         ExprKind::Closure(closure) => {
52             let body = cx.tcx.hir().body(closure.body);
53             if let PatKind::Binding(_, param_id, ..) = body.params[0].pat.kind
54                 && let ExprKind::Call(callee, [ok_arg]) = body.value.kind
55                 && is_res_lang_ctor(cx, path_res(cx, callee), ResultOk)
56             {
57                 path_to_local_id(ok_arg, param_id)
58             } else {
59                 false
60             }
61         },
62         _ => false,
63     }
64 }