]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs
merge rustc history
[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_lang_ctor, 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::{Closure, 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(Expr { kind: ExprKind::Path(err_path), .. }, [err_arg]) = or_expr.kind;
26         if is_lang_ctor(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                     "{}.ok_or({})",
41                     recv_snippet,
42                     reindented_err_arg_snippet
43                 ),
44                 Applicability::MachineApplicable,
45             );
46         }
47     }
48 }
49
50 fn is_ok_wrapping(cx: &LateContext<'_>, map_expr: &Expr<'_>) -> bool {
51     if let ExprKind::Path(ref qpath) = map_expr.kind {
52         if is_lang_ctor(cx, qpath, ResultOk) {
53             return true;
54         }
55     }
56     if_chain! {
57         if let ExprKind::Closure(&Closure { body, .. }) = map_expr.kind;
58         let body = cx.tcx.hir().body(body);
59         if let PatKind::Binding(_, param_id, ..) = body.params[0].pat.kind;
60         if let ExprKind::Call(Expr { kind: ExprKind::Path(ok_path), .. }, &[ref ok_arg]) = body.value.kind;
61         if is_lang_ctor(cx, ok_path, ResultOk);
62         then { path_to_local_id(ok_arg, param_id) } else { false }
63     }
64 }