]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_match.rs
Auto merge of #7502 - flip1995:rollup-y3ho3w0, r=flip1995
[rust.git] / clippy_lints / src / collapsible_match.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::visitors::LocalUsedVisitor;
3 use clippy_utils::{is_lang_ctor, path_to_local, peel_ref_operators, SpanlessEq};
4 use if_chain::if_chain;
5 use rustc_hir::LangItem::OptionNone;
6 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind, StmtKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::{MultiSpan, Span};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together
14     /// without adding any branches.
15     ///
16     /// Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only
17     /// cases where merging would most likely make the code more readable.
18     ///
19     /// ### Why is this bad?
20     /// It is unnecessarily verbose and complex.
21     ///
22     /// ### Example
23     /// ```rust
24     /// fn func(opt: Option<Result<u64, String>>) {
25     ///     let n = match opt {
26     ///         Some(n) => match n {
27     ///             Ok(n) => n,
28     ///             _ => return,
29     ///         }
30     ///         None => return,
31     ///     };
32     /// }
33     /// ```
34     /// Use instead:
35     /// ```rust
36     /// fn func(opt: Option<Result<u64, String>>) {
37     ///     let n = match opt {
38     ///         Some(Ok(n)) => n,
39     ///         _ => return,
40     ///     };
41     /// }
42     /// ```
43     pub COLLAPSIBLE_MATCH,
44     style,
45     "Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
46 }
47
48 declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]);
49
50 impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch {
51     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
52         if let ExprKind::Match(_expr, arms, _source) = expr.kind {
53             if let Some(wild_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) {
54                 for arm in arms {
55                     check_arm(arm, wild_arm, cx);
56                 }
57             }
58         }
59     }
60 }
61
62 fn check_arm<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, cx: &LateContext<'tcx>) {
63     let expr = strip_singleton_blocks(arm.body);
64     if_chain! {
65         if let ExprKind::Match(expr_in, arms_inner, _) = expr.kind;
66         // the outer arm pattern and the inner match
67         if expr_in.span.ctxt() == arm.pat.span.ctxt();
68         // there must be no more than two arms in the inner match for this lint
69         if arms_inner.len() == 2;
70         // no if guards on the inner match
71         if arms_inner.iter().all(|arm| arm.guard.is_none());
72         // match expression must be a local binding
73         // match <local> { .. }
74         if let Some(binding_id) = path_to_local(peel_ref_operators(cx, expr_in));
75         // one of the branches must be "wild-like"
76         if let Some(wild_inner_arm_idx) = arms_inner.iter().rposition(|arm_inner| arm_is_wild_like(cx, arm_inner));
77         let (wild_inner_arm, non_wild_inner_arm) =
78             (&arms_inner[wild_inner_arm_idx], &arms_inner[1 - wild_inner_arm_idx]);
79         if !pat_contains_or(non_wild_inner_arm.pat);
80         // the binding must come from the pattern of the containing match arm
81         // ..<local>.. => match <local> { .. }
82         if let Some(binding_span) = find_pat_binding(arm.pat, binding_id);
83         // the "wild-like" branches must be equal
84         if SpanlessEq::new(cx).eq_expr(wild_inner_arm.body, wild_outer_arm.body);
85         // the binding must not be used in the if guard
86         let mut used_visitor = LocalUsedVisitor::new(cx, binding_id);
87         if match arm.guard {
88             None => true,
89             Some(Guard::If(expr) | Guard::IfLet(_, expr)) => !used_visitor.check_expr(expr),
90         };
91         // ...or anywhere in the inner match
92         if !arms_inner.iter().any(|arm| used_visitor.check_arm(arm));
93         then {
94             span_lint_and_then(
95                 cx,
96                 COLLAPSIBLE_MATCH,
97                 expr.span,
98                 "unnecessary nested match",
99                 |diag| {
100                     let mut help_span = MultiSpan::from_spans(vec![binding_span, non_wild_inner_arm.pat.span]);
101                     help_span.push_span_label(binding_span, "replace this binding".into());
102                     help_span.push_span_label(non_wild_inner_arm.pat.span, "with this pattern".into());
103                     diag.span_help(help_span, "the outer pattern can be modified to include the inner pattern");
104                 },
105             );
106         }
107     }
108 }
109
110 fn strip_singleton_blocks<'hir>(mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
111     while let ExprKind::Block(block, _) = expr.kind {
112         match (block.stmts, block.expr) {
113             ([stmt], None) => match stmt.kind {
114                 StmtKind::Expr(e) | StmtKind::Semi(e) => expr = e,
115                 _ => break,
116             },
117             ([], Some(e)) => expr = e,
118             _ => break,
119         }
120     }
121     expr
122 }
123
124 /// A "wild-like" pattern is wild ("_") or `None`.
125 /// For this lint to apply, both the outer and inner match expressions
126 /// must have "wild-like" branches that can be combined.
127 fn arm_is_wild_like(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
128     if arm.guard.is_some() {
129         return false;
130     }
131     match arm.pat.kind {
132         PatKind::Binding(..) | PatKind::Wild => true,
133         PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
134         _ => false,
135     }
136 }
137
138 fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option<Span> {
139     let mut span = None;
140     pat.walk_short(|p| match &p.kind {
141         // ignore OR patterns
142         PatKind::Or(_) => false,
143         PatKind::Binding(_bm, _, _ident, _) => {
144             let found = p.hir_id == hir_id;
145             if found {
146                 span = Some(p.span);
147             }
148             !found
149         },
150         _ => true,
151     });
152     span
153 }
154
155 fn pat_contains_or(pat: &Pat<'_>) -> bool {
156     let mut result = false;
157     pat.walk(|p| {
158         let is_or = matches!(p.kind, PatKind::Or(_));
159         result |= is_or;
160         !is_or
161     });
162     result
163 }