]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_unwrap_or.rs
manual-unwrap-or / pr remarks
[rust.git] / clippy_lints / src / manual_unwrap_or.rs
1 use crate::utils;
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{def, Arm, Expr, ExprKind, PatKind, QPath};
5 use rustc_lint::LintContext;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:**
12     /// Finds patterns that reimplement `Option::unwrap_or`.
13     ///
14     /// **Why is this bad?**
15     /// Concise code helps focusing on behavior instead of boilerplate.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust
21     /// match int_option {
22     ///     Some(v) => v,
23     ///     None => 1,
24     /// }
25     /// ```
26     ///
27     /// Use instead:
28     /// ```rust
29     /// int_option.unwrap_or(1)
30     /// ```
31     pub MANUAL_UNWRAP_OR,
32     complexity,
33     "finds patterns that can be encoded more concisely with `Option::unwrap_or(_else)`"
34 }
35
36 declare_lint_pass!(ManualUnwrapOr => [MANUAL_UNWRAP_OR]);
37
38 impl LateLintPass<'_> for ManualUnwrapOr {
39     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
40         if in_external_macro(cx.sess(), expr.span) {
41             return;
42         }
43         lint_option_unwrap_or_case(cx, expr);
44     }
45 }
46
47 fn lint_option_unwrap_or_case<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
48     fn applicable_none_arm<'a>(arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> {
49         if_chain! {
50             if arms.len() == 2;
51             if arms.iter().all(|arm| arm.guard.is_none());
52             if let Some((idx, none_arm)) = arms.iter().enumerate().find(|(_, arm)|
53                 if let PatKind::Path(ref qpath) = arm.pat.kind {
54                     utils::match_qpath(qpath, &utils::paths::OPTION_NONE)
55                 } else {
56                     false
57                 }
58             );
59             let some_arm = &arms[1 - idx];
60             if let PatKind::TupleStruct(ref some_qpath, &[some_binding], _) = some_arm.pat.kind;
61             if utils::match_qpath(some_qpath, &utils::paths::OPTION_SOME);
62             if let PatKind::Binding(_, binding_hir_id, ..) = some_binding.kind;
63             if let ExprKind::Path(QPath::Resolved(_, body_path)) = some_arm.body.kind;
64             if let def::Res::Local(body_path_hir_id) = body_path.res;
65             if body_path_hir_id == binding_hir_id;
66             if !utils::usage::contains_return_break_continue_macro(none_arm.body);
67             then {
68                 Some(none_arm)
69             }
70             else {
71                 None
72             }
73         }
74     }
75
76     if_chain! {
77         if let ExprKind::Match(scrutinee, match_arms, _) = expr.kind;
78         let ty = cx.typeck_results().expr_ty(scrutinee);
79         if utils::is_type_diagnostic_item(cx, ty, sym!(option_type));
80         if let Some(none_arm) = applicable_none_arm(match_arms);
81         if let Some(scrutinee_snippet) = utils::snippet_opt(cx, scrutinee.span);
82         if let Some(none_body_snippet) = utils::snippet_opt(cx, none_arm.body.span);
83         if let Some(indent) = utils::indent_of(cx, expr.span);
84         then {
85             let reindented_none_body =
86                 utils::reindent_multiline(none_body_snippet.into(), true, Some(indent));
87             let eager_eval = utils::eager_or_lazy::is_eagerness_candidate(cx, none_arm.body);
88             let method = if eager_eval {
89                 "unwrap_or"
90             } else {
91                 "unwrap_or_else"
92             };
93             utils::span_lint_and_sugg(
94                 cx,
95                 MANUAL_UNWRAP_OR, expr.span,
96                 &format!("this pattern reimplements `Option::{}`", &method),
97                 "replace with",
98                 format!(
99                     "{}.{}({}{})",
100                     scrutinee_snippet,
101                     method,
102                     if eager_eval { ""} else { "|| " },
103                     reindented_none_body
104                 ),
105                 Applicability::MachineApplicable,
106             );
107             true
108         } else {
109             false
110         }
111     }
112 }