1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::higher::IfLetOrMatch;
3 use clippy_utils::visitors::is_local_used;
4 use clippy_utils::{is_lang_ctor, is_unit_expr, path_to_local, peel_blocks_with_stmt, peel_ref_operators, SpanlessEq};
5 use if_chain::if_chain;
6 use rustc_errors::MultiSpan;
7 use rustc_hir::LangItem::OptionNone;
8 use rustc_hir::{Arm, Expr, Guard, HirId, Let, Pat, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 declare_clippy_lint! {
15 /// Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together
16 /// without adding any branches.
18 /// Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only
19 /// cases where merging would most likely make the code more readable.
21 /// ### Why is this bad?
22 /// It is unnecessarily verbose and complex.
26 /// fn func(opt: Option<Result<u64, String>>) {
27 /// let n = match opt {
28 /// Some(n) => match n {
38 /// fn func(opt: Option<Result<u64, String>>) {
39 /// let n = match opt {
45 #[clippy::version = "1.50.0"]
46 pub COLLAPSIBLE_MATCH,
48 "Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
51 declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]);
53 impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch {
54 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
55 match IfLetOrMatch::parse(cx, expr) {
56 Some(IfLetOrMatch::Match(_, arms, _)) => {
57 if let Some(els_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) {
59 check_arm(cx, true, arm.pat, arm.body, arm.guard.as_ref(), Some(els_arm.body));
63 Some(IfLetOrMatch::IfLet(_, pat, body, els)) => {
64 check_arm(cx, false, pat, body, None, els);
72 cx: &LateContext<'tcx>,
74 outer_pat: &'tcx Pat<'tcx>,
75 outer_then_body: &'tcx Expr<'tcx>,
76 outer_guard: Option<&'tcx Guard<'tcx>>,
77 outer_else_body: Option<&'tcx Expr<'tcx>>,
79 let inner_expr = peel_blocks_with_stmt(outer_then_body);
81 if let Some(inner) = IfLetOrMatch::parse(cx, inner_expr);
82 if let Some((inner_scrutinee, inner_then_pat, inner_else_body)) = match inner {
83 IfLetOrMatch::IfLet(scrutinee, pat, _, els) => Some((scrutinee, pat, els)),
84 IfLetOrMatch::Match(scrutinee, arms, ..) => if_chain! {
85 // if there are more than two arms, collapsing would be non-trivial
86 if arms.len() == 2 && arms.iter().all(|a| a.guard.is_none());
87 // one of the arms must be "wild-like"
88 if let Some(wild_idx) = arms.iter().rposition(|a| arm_is_wild_like(cx, a));
90 let (then, els) = (&arms[1 - wild_idx], &arms[wild_idx]);
91 Some((scrutinee, then.pat, Some(els.body)))
97 if outer_pat.span.ctxt() == inner_scrutinee.span.ctxt();
98 // match expression must be a local binding
99 // match <local> { .. }
100 if let Some(binding_id) = path_to_local(peel_ref_operators(cx, inner_scrutinee));
101 if !pat_contains_or(inner_then_pat);
102 // the binding must come from the pattern of the containing match arm
103 // ..<local>.. => match <local> { .. }
104 if let Some(binding_span) = find_pat_binding(outer_pat, binding_id);
105 // the "else" branches must be equal
106 if match (outer_else_body, inner_else_body) {
107 (None, None) => true,
108 (None, Some(e)) | (Some(e), None) => is_unit_expr(e),
109 (Some(a), Some(b)) => SpanlessEq::new(cx).eq_expr(a, b),
111 // the binding must not be used in the if guard
112 if outer_guard.map_or(
114 |(Guard::If(e) | Guard::IfLet(Let { init: e, .. }))| !is_local_used(cx, *e, binding_id)
116 // ...or anywhere in the inner expression
118 IfLetOrMatch::IfLet(_, _, body, els) => {
119 !is_local_used(cx, body, binding_id) && els.map_or(true, |e| !is_local_used(cx, e, binding_id))
121 IfLetOrMatch::Match(_, arms, ..) => !arms.iter().any(|arm| is_local_used(cx, arm, binding_id)),
125 "this `{}` can be collapsed into the outer `{}`",
126 if matches!(inner, IfLetOrMatch::Match(..)) { "match" } else { "if let" },
127 if outer_is_match { "match" } else { "if let" },
135 let mut help_span = MultiSpan::from_spans(vec![binding_span, inner_then_pat.span]);
136 help_span.push_span_label(binding_span, "replace this binding");
137 help_span.push_span_label(inner_then_pat.span, "with this pattern");
138 diag.span_help(help_span, "the outer pattern can be modified to include the inner pattern");
145 /// A "wild-like" arm has a wild (`_`) or `None` pattern and no guard. Such arms can be "collapsed"
146 /// into a single wild arm without any significant loss in semantics or readability.
147 fn arm_is_wild_like(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
148 if arm.guard.is_some() {
152 PatKind::Binding(..) | PatKind::Wild => true,
153 PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
158 fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option<Span> {
160 pat.walk_short(|p| match &p.kind {
161 // ignore OR patterns
162 PatKind::Or(_) => false,
163 PatKind::Binding(_bm, _, _ident, _) => {
164 let found = p.hir_id == hir_id;
175 fn pat_contains_or(pat: &Pat<'_>) -> bool {
176 let mut result = false;
178 let is_or = matches!(p.kind, PatKind::Or(_));