]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_unwrap_or.rs
manual_unwrap_or / support Result::unwrap_or
[rust.git] / clippy_lints / src / manual_unwrap_or.rs
1 use crate::consts::constant_simple;
2 use crate::utils;
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{def, Arm, Expr, ExprKind, Pat, PatKind, QPath};
6 use rustc_lint::LintContext;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::lint::in_external_macro;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10
11 declare_clippy_lint! {
12     /// **What it does:**
13     /// Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`.
14     ///
15     /// **Why is this bad?**
16     /// Concise code helps focusing on behavior instead of boilerplate.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// let foo: Option<i32> = None;
23     /// match foo {
24     ///     Some(v) => v,
25     ///     None => 1,
26     /// };
27     /// ```
28     ///
29     /// Use instead:
30     /// ```rust
31     /// let foo: Option<i32> = None;
32     /// foo.unwrap_or(1);
33     /// ```
34     pub MANUAL_UNWRAP_OR,
35     complexity,
36     "finds patterns that can be encoded more concisely with `Option::unwrap_or` or `Result::unwrap_or`"
37 }
38
39 declare_lint_pass!(ManualUnwrapOr => [MANUAL_UNWRAP_OR]);
40
41 impl LateLintPass<'_> for ManualUnwrapOr {
42     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
43         if in_external_macro(cx.sess(), expr.span) {
44             return;
45         }
46         lint_manual_unwrap_or(cx, expr);
47     }
48 }
49
50 #[derive(Copy, Clone)]
51 enum Case {
52     Option,
53     Result,
54 }
55
56 impl Case {
57     fn unwrap_fn_path(&self) -> &str {
58         match self {
59             Case::Option => "Option::unwrap_or",
60             Case::Result => "Result::unwrap_or",
61         }
62     }
63 }
64
65 fn lint_manual_unwrap_or<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
66     fn applicable_or_arm<'a>(arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> {
67         if_chain! {
68             if arms.len() == 2;
69             if arms.iter().all(|arm| arm.guard.is_none());
70             if let Some((idx, or_arm)) = arms.iter().enumerate().find(|(_, arm)|
71                 match arm.pat.kind {
72                     PatKind::Path(ref some_qpath) =>
73                         utils::match_qpath(some_qpath, &utils::paths::OPTION_NONE),
74                     PatKind::TupleStruct(ref err_qpath, &[Pat { kind: PatKind::Wild, .. }], _) =>
75                         utils::match_qpath(err_qpath, &utils::paths::RESULT_ERR),
76                     _ => false,
77                 }
78             );
79             let unwrap_arm = &arms[1 - idx];
80             if let PatKind::TupleStruct(ref unwrap_qpath, &[unwrap_pat], _) = unwrap_arm.pat.kind;
81             if utils::match_qpath(unwrap_qpath, &utils::paths::OPTION_SOME)
82                 || utils::match_qpath(unwrap_qpath, &utils::paths::RESULT_OK);
83             if let PatKind::Binding(_, binding_hir_id, ..) = unwrap_pat.kind;
84             if let ExprKind::Path(QPath::Resolved(_, body_path)) = unwrap_arm.body.kind;
85             if let def::Res::Local(body_path_hir_id) = body_path.res;
86             if body_path_hir_id == binding_hir_id;
87             if !utils::usage::contains_return_break_continue_macro(or_arm.body);
88             then {
89                 Some(or_arm)
90             } else {
91                 None
92             }
93         }
94     }
95
96     if_chain! {
97         if let ExprKind::Match(scrutinee, match_arms, _) = expr.kind;
98         let ty = cx.typeck_results().expr_ty(scrutinee);
99         if let Some(case) = if utils::is_type_diagnostic_item(cx, ty, sym!(option_type)) {
100             Some(Case::Option)
101         } else if utils::is_type_diagnostic_item(cx, ty, sym!(result_type)) {
102             Some(Case::Result)
103         } else {
104             None
105         };
106         if let Some(or_arm) = applicable_or_arm(match_arms);
107         if let Some(scrutinee_snippet) = utils::snippet_opt(cx, scrutinee.span);
108         if let Some(or_body_snippet) = utils::snippet_opt(cx, or_arm.body.span);
109         if let Some(indent) = utils::indent_of(cx, expr.span);
110         if constant_simple(cx, cx.typeck_results(), or_arm.body).is_some();
111         then {
112             let reindented_or_body =
113                 utils::reindent_multiline(or_body_snippet.into(), true, Some(indent));
114             let wrap_in_parens = !matches!(scrutinee, Expr { kind: ExprKind::Call(..), .. });
115             let l_paren = if wrap_in_parens { "(" } else { "" };
116             let r_paren = if wrap_in_parens { ")" } else { "" };
117             utils::span_lint_and_sugg(
118                 cx,
119                 MANUAL_UNWRAP_OR, expr.span,
120                 &format!("this pattern reimplements `{}`", case.unwrap_fn_path()),
121                 "replace with",
122                 format!(
123                     "{}{}{}.unwrap_or({})",
124                     l_paren,
125                     scrutinee_snippet,
126                     r_paren,
127                     reindented_or_body,
128                 ),
129                 Applicability::MachineApplicable,
130             );
131         }
132     }
133 }