]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_ok_or.rs
Rollup merge of #81260 - vn971:restore-editorconfig, r=Mark-Simulacrum
[rust.git] / clippy_lints / src / manual_ok_or.rs
1 use crate::utils::{
2     indent_of, is_type_diagnostic_item, match_qpath, paths, reindent_multiline, snippet_opt, span_lint_and_sugg,
3 };
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{def, Expr, ExprKind, PatKind, QPath};
7 use rustc_lint::LintContext;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::symbol::sym;
12
13 declare_clippy_lint! {
14     /// **What it does:**
15     /// Finds patterns that reimplement `Option::ok_or`.
16     ///
17     /// **Why is this bad?**
18     /// Concise code helps focusing on behavior instead of boilerplate.
19     ///
20     /// **Known problems:** None.
21     ///
22     /// **Examples:**
23     /// ```rust
24     /// let foo: Option<i32> = None;
25     /// foo.map_or(Err("error"), |v| Ok(v));
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// let foo: Option<i32> = None;
31     /// foo.ok_or("error");
32     /// ```
33     pub MANUAL_OK_OR,
34     pedantic,
35     "finds patterns that can be encoded more concisely with `Option::ok_or`"
36 }
37
38 declare_lint_pass!(ManualOkOr => [MANUAL_OK_OR]);
39
40 impl LateLintPass<'_> for ManualOkOr {
41     fn check_expr(&mut self, cx: &LateContext<'tcx>, scrutinee: &'tcx Expr<'tcx>) {
42         if in_external_macro(cx.sess(), scrutinee.span) {
43             return;
44         }
45
46         if_chain! {
47             if let ExprKind::MethodCall(method_segment, _, args, _) = scrutinee.kind;
48             if method_segment.ident.name == sym!(map_or);
49             if args.len() == 3;
50             let method_receiver = &args[0];
51             let ty = cx.typeck_results().expr_ty(method_receiver);
52             if is_type_diagnostic_item(cx, ty, sym::option_type);
53             let or_expr = &args[1];
54             if is_ok_wrapping(cx, &args[2]);
55             if let ExprKind::Call(Expr { kind: ExprKind::Path(err_path), .. }, &[ref err_arg]) = or_expr.kind;
56             if match_qpath(err_path, &paths::RESULT_ERR);
57             if let Some(method_receiver_snippet) = snippet_opt(cx, method_receiver.span);
58             if let Some(err_arg_snippet) = snippet_opt(cx, err_arg.span);
59             if let Some(indent) = indent_of(cx, scrutinee.span);
60             then {
61                 let reindented_err_arg_snippet =
62                     reindent_multiline(err_arg_snippet.into(), true, Some(indent + 4));
63                 span_lint_and_sugg(
64                     cx,
65                     MANUAL_OK_OR,
66                     scrutinee.span,
67                     "this pattern reimplements `Option::ok_or`",
68                     "replace with",
69                     format!(
70                         "{}.ok_or({})",
71                         method_receiver_snippet,
72                         reindented_err_arg_snippet
73                     ),
74                     Applicability::MachineApplicable,
75                 );
76             }
77         }
78     }
79 }
80
81 fn is_ok_wrapping(cx: &LateContext<'_>, map_expr: &Expr<'_>) -> bool {
82     if let ExprKind::Path(ref qpath) = map_expr.kind {
83         if match_qpath(qpath, &paths::RESULT_OK) {
84             return true;
85         }
86     }
87     if_chain! {
88         if let ExprKind::Closure(_, _, body_id, ..) = map_expr.kind;
89         let body = cx.tcx.hir().body(body_id);
90         if let PatKind::Binding(_, param_id, ..) = body.params[0].pat.kind;
91         if let ExprKind::Call(Expr { kind: ExprKind::Path(ok_path), .. }, &[ref ok_arg]) = body.value.kind;
92         if match_qpath(ok_path, &paths::RESULT_OK);
93         if let ExprKind::Path(QPath::Resolved(_, ok_arg_path)) = ok_arg.kind;
94         if let def::Res::Local(ok_arg_path_id) = ok_arg_path.res;
95         then { param_id == ok_arg_path_id } else { false }
96     }
97 }