]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_match.rs
Auto merge of #80851 - m-ou-se:panic-2021, r=petrochenkov
[rust.git] / clippy_lints / src / collapsible_match.rs
1 use crate::utils::visitors::LocalUsedVisitor;
2 use crate::utils::{span_lint_and_then, SpanlessEq};
3 use if_chain::if_chain;
4 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
5 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind, QPath, StmtKind, UnOp};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::{DefIdTree, TyCtxt};
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:** Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together
13     /// without adding any branches.
14     ///
15     /// Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only
16     /// cases where merging would most likely make the code more readable.
17     ///
18     /// **Why is this bad?** It is unnecessarily verbose and complex.
19     ///
20     /// **Known problems:** None.
21     ///
22     /// **Example:**
23     ///
24     /// ```rust
25     /// fn func(opt: Option<Result<u64, String>>) {
26     ///     let n = match opt {
27     ///         Some(n) => match n {
28     ///             Ok(n) => n,
29     ///             _ => return,
30     ///         }
31     ///         None => return,
32     ///     };
33     /// }
34     /// ```
35     /// Use instead:
36     /// ```rust
37     /// fn func(opt: Option<Result<u64, String>>) {
38     ///     let n = match opt {
39     ///         Some(Ok(n)) => n,
40     ///         _ => return,
41     ///     };
42     /// }
43     /// ```
44     pub COLLAPSIBLE_MATCH,
45     style,
46     "Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
47 }
48
49 declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]);
50
51 impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch {
52     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
53         if let ExprKind::Match(_expr, arms, _source) = expr.kind {
54             if let Some(wild_arm) = arms.iter().rfind(|arm| arm_is_wild_like(arm, cx.tcx)) {
55                 for arm in arms {
56                     check_arm(arm, wild_arm, cx);
57                 }
58             }
59         }
60     }
61 }
62
63 fn check_arm(arm: &Arm<'_>, wild_outer_arm: &Arm<'_>, cx: &LateContext<'_>) {
64     if_chain! {
65         let expr = strip_singleton_blocks(arm.body);
66         if let ExprKind::Match(expr_in, arms_inner, _) = expr.kind;
67         // the outer arm pattern and the inner match
68         if expr_in.span.ctxt() == arm.pat.span.ctxt();
69         // there must be no more than two arms in the inner match for this lint
70         if arms_inner.len() == 2;
71         // no if guards on the inner match
72         if arms_inner.iter().all(|arm| arm.guard.is_none());
73         // match expression must be a local binding
74         // match <local> { .. }
75         if let Some(binding_id) = addr_adjusted_binding(expr_in, cx);
76         // one of the branches must be "wild-like"
77         if let Some(wild_inner_arm_idx) = arms_inner.iter().rposition(|arm_inner| arm_is_wild_like(arm_inner, cx.tcx));
78         let (wild_inner_arm, non_wild_inner_arm) =
79             (&arms_inner[wild_inner_arm_idx], &arms_inner[1 - wild_inner_arm_idx]);
80         if !pat_contains_or(non_wild_inner_arm.pat);
81         // the binding must come from the pattern of the containing match arm
82         // ..<local>.. => match <local> { .. }
83         if let Some(binding_span) = find_pat_binding(arm.pat, binding_id);
84         // the "wild-like" branches must be equal
85         if SpanlessEq::new(cx).eq_expr(wild_inner_arm.body, wild_outer_arm.body);
86         // the binding must not be used in the if guard
87         if match arm.guard {
88             None => true,
89             Some(Guard::If(expr) | Guard::IfLet(_, expr)) => {
90                 !LocalUsedVisitor::new(binding_id).check_expr(expr)
91             }
92         };
93         // ...or anywhere in the inner match
94         if !arms_inner.iter().any(|arm| LocalUsedVisitor::new(binding_id).check_arm(arm));
95         then {
96             span_lint_and_then(
97                 cx,
98                 COLLAPSIBLE_MATCH,
99                 expr.span,
100                 "Unnecessary nested match",
101                 |diag| {
102                     let mut help_span = MultiSpan::from_spans(vec![binding_span, non_wild_inner_arm.pat.span]);
103                     help_span.push_span_label(binding_span, "Replace this binding".into());
104                     help_span.push_span_label(non_wild_inner_arm.pat.span, "with this pattern".into());
105                     diag.span_help(help_span, "The outer pattern can be modified to include the inner pattern.");
106                 },
107             );
108         }
109     }
110 }
111
112 fn strip_singleton_blocks<'hir>(mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
113     while let ExprKind::Block(block, _) = expr.kind {
114         match (block.stmts, block.expr) {
115             ([stmt], None) => match stmt.kind {
116                 StmtKind::Expr(e) | StmtKind::Semi(e) => expr = e,
117                 _ => break,
118             },
119             ([], Some(e)) => expr = e,
120             _ => break,
121         }
122     }
123     expr
124 }
125
126 /// A "wild-like" pattern is wild ("_") or `None`.
127 /// For this lint to apply, both the outer and inner match expressions
128 /// must have "wild-like" branches that can be combined.
129 fn arm_is_wild_like(arm: &Arm<'_>, tcx: TyCtxt<'_>) -> bool {
130     if arm.guard.is_some() {
131         return false;
132     }
133     match arm.pat.kind {
134         PatKind::Binding(..) | PatKind::Wild => true,
135         PatKind::Path(QPath::Resolved(None, path)) if is_none_ctor(path.res, tcx) => true,
136         _ => false,
137     }
138 }
139
140 fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option<Span> {
141     let mut span = None;
142     pat.walk_short(|p| match &p.kind {
143         // ignore OR patterns
144         PatKind::Or(_) => false,
145         PatKind::Binding(_bm, _, _ident, _) => {
146             let found = p.hir_id == hir_id;
147             if found {
148                 span = Some(p.span);
149             }
150             !found
151         },
152         _ => true,
153     });
154     span
155 }
156
157 fn pat_contains_or(pat: &Pat<'_>) -> bool {
158     let mut result = false;
159     pat.walk(|p| {
160         let is_or = matches!(p.kind, PatKind::Or(_));
161         result |= is_or;
162         !is_or
163     });
164     result
165 }
166
167 fn is_none_ctor(res: Res, tcx: TyCtxt<'_>) -> bool {
168     if let Some(none_id) = tcx.lang_items().option_none_variant() {
169         if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), id) = res {
170             if let Some(variant_id) = tcx.parent(id) {
171                 return variant_id == none_id;
172             }
173         }
174     }
175     false
176 }
177
178 /// Retrieves a binding ID with optional `&` and/or `*` operators removed. (e.g. `&**foo`)
179 /// Returns `None` if a non-reference type is de-referenced.
180 /// For example, if `Vec` is de-referenced to a slice, `None` is returned.
181 fn addr_adjusted_binding(mut expr: &Expr<'_>, cx: &LateContext<'_>) -> Option<HirId> {
182     loop {
183         match expr.kind {
184             ExprKind::AddrOf(_, _, e) => expr = e,
185             ExprKind::Path(QPath::Resolved(None, path)) => match path.res {
186                 Res::Local(binding_id) => break Some(binding_id),
187                 _ => break None,
188             },
189             ExprKind::Unary(UnOp::UnDeref, e) if cx.typeck_results().expr_ty(e).is_ref() => expr = e,
190             _ => break None,
191         }
192     }
193 }