Skip to content

Commit 7481e6d

Browse files
committed
Auto merge of rust-lang#88163 - camsteffen:collapsible-match-fix, r=Manishearth
Fix clippy::collapsible_match with let expressions This fixes rust-lang/rust-clippy#7575 which is a regression from rust-lang#80357. I am fixing the bug here instead of in the clippy repo (if that's okay) because a) the regression has not been synced yet and b) I would like to land the fix on nightly asap. The fix is basically to re-generalize `match` and `if let` for the lint implementation (they were split because `if let` no longer desugars to `match` in the HIR). Also fixes rust-lang/rust-clippy#7586 and fixes rust-lang/rust-clippy#7591 cc `@rust-lang/clippy` `@xFrednet` do you want to review this?
2 parents 1eb187c + ada9282 commit 7481e6d

17 files changed

+136
-150
lines changed

src/tools/clippy/clippy_lints/src/collapsible_match.rs

+78-79
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
22
use clippy_utils::visitors::LocalUsedVisitor;
3-
use clippy_utils::{higher, is_lang_ctor, path_to_local, peel_ref_operators, SpanlessEq};
3+
use clippy_utils::{higher, is_lang_ctor, is_unit_expr, path_to_local, peel_ref_operators, SpanlessEq};
44
use if_chain::if_chain;
55
use rustc_hir::LangItem::OptionNone;
6-
use rustc_hir::{Expr, ExprKind, Guard, HirId, Pat, PatKind, StmtKind};
6+
use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, MatchSource, Pat, PatKind, StmtKind};
77
use rustc_lint::{LateContext, LateLintPass};
88
use rustc_session::{declare_lint_pass, declare_tool_lint};
99
use rustc_span::{MultiSpan, Span};
@@ -49,104 +49,87 @@ declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]);
4949

5050
impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch {
5151
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
52-
if let Some(higher::IfLet {
53-
let_pat,
54-
if_then,
55-
if_else,
56-
..
57-
}) = higher::IfLet::hir(expr)
58-
{
59-
check_arm(cx, if_then, None, let_pat, if_else);
60-
61-
check_if_let(cx, if_then, let_pat);
62-
}
63-
64-
if let ExprKind::Match(_expr, arms, _source) = expr.kind {
65-
if let Some(wild_arm) = arms.iter().rfind(|arm| is_wild_like(cx, &arm.pat.kind, &arm.guard)) {
66-
for arm in arms {
67-
check_arm(cx, arm.body, arm.guard.as_ref(), arm.pat, Some(wild_arm.body));
52+
match IfLetOrMatch::parse(cx, expr) {
53+
Some(IfLetOrMatch::Match(_, arms, _)) => {
54+
if let Some(els_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) {
55+
for arm in arms {
56+
check_arm(cx, true, arm.pat, arm.body, arm.guard.as_ref(), Some(els_arm.body));
57+
}
6858
}
6959
}
70-
71-
if let Some(first_arm) = arms.get(0) {
72-
check_if_let(cx, &first_arm.body, &first_arm.pat);
60+
Some(IfLetOrMatch::IfLet(_, pat, body, els)) => {
61+
check_arm(cx, false, pat, body, None, els);
7362
}
63+
None => {}
7464
}
7565
}
7666
}
7767

7868
fn check_arm<'tcx>(
7969
cx: &LateContext<'tcx>,
80-
outer_block: &'tcx Expr<'tcx>,
81-
outer_guard: Option<&Guard<'tcx>>,
70+
outer_is_match: bool,
8271
outer_pat: &'tcx Pat<'tcx>,
83-
wild_outer_block: Option<&'tcx Expr<'tcx>>,
72+
outer_then_body: &'tcx Expr<'tcx>,
73+
outer_guard: Option<&'tcx Guard<'tcx>>,
74+
outer_else_body: Option<&'tcx Expr<'tcx>>
8475
) {
85-
let expr = strip_singleton_blocks(outer_block);
76+
let inner_expr = strip_singleton_blocks(outer_then_body);
8677
if_chain! {
87-
if let ExprKind::Match(expr_in, arms_inner, _) = expr.kind;
88-
// the outer arm pattern and the inner match
89-
if expr_in.span.ctxt() == outer_pat.span.ctxt();
90-
// there must be no more than two arms in the inner match for this lint
91-
if arms_inner.len() == 2;
92-
// no if guards on the inner match
93-
if arms_inner.iter().all(|arm| arm.guard.is_none());
78+
if let Some(inner) = IfLetOrMatch::parse(cx, inner_expr);
79+
if let Some((inner_scrutinee, inner_then_pat, inner_else_body)) = match inner {
80+
IfLetOrMatch::IfLet(scrutinee, pat, _, els) => Some((scrutinee, pat, els)),
81+
IfLetOrMatch::Match(scrutinee, arms, ..) => if_chain! {
82+
// if there are more than two arms, collapsing would be non-trivial
83+
if arms.len() == 2 && arms.iter().all(|a| a.guard.is_none());
84+
// one of the arms must be "wild-like"
85+
if let Some(wild_idx) = arms.iter().rposition(|a| arm_is_wild_like(cx, a));
86+
then {
87+
let (then, els) = (&arms[1 - wild_idx], &arms[wild_idx]);
88+
Some((scrutinee, then.pat, Some(els.body)))
89+
} else {
90+
None
91+
}
92+
},
93+
};
94+
if outer_pat.span.ctxt() == inner_scrutinee.span.ctxt();
9495
// match expression must be a local binding
9596
// match <local> { .. }
96-
if let Some(binding_id) = path_to_local(peel_ref_operators(cx, expr_in));
97-
// one of the branches must be "wild-like"
98-
if let Some(wild_inner_arm_idx) = arms_inner.iter().rposition(|arm_inner| is_wild_like(cx, &arm_inner.pat.kind, &arm_inner.guard));
99-
let (wild_inner_arm, non_wild_inner_arm) =
100-
(&arms_inner[wild_inner_arm_idx], &arms_inner[1 - wild_inner_arm_idx]);
101-
if !pat_contains_or(non_wild_inner_arm.pat);
97+
if let Some(binding_id) = path_to_local(peel_ref_operators(cx, inner_scrutinee));
98+
if !pat_contains_or(inner_then_pat);
10299
// the binding must come from the pattern of the containing match arm
103100
// ..<local>.. => match <local> { .. }
104101
if let Some(binding_span) = find_pat_binding(outer_pat, binding_id);
105-
// the "wild-like" branches must be equal
106-
if wild_outer_block.map(|el| SpanlessEq::new(cx).eq_expr(wild_inner_arm.body, el)).unwrap_or(true);
102+
// the "else" branches must be equal
103+
if match (outer_else_body, inner_else_body) {
104+
(None, None) => true,
105+
(None, Some(e)) | (Some(e), None) => is_unit_expr(e),
106+
(Some(a), Some(b)) => SpanlessEq::new(cx).eq_expr(a, b),
107+
};
107108
// the binding must not be used in the if guard
108109
let mut used_visitor = LocalUsedVisitor::new(cx, binding_id);
109-
if match outer_guard {
110-
None => true,
111-
Some(Guard::If(expr) | Guard::IfLet(_, expr)) => !used_visitor.check_expr(expr),
110+
if outer_guard.map_or(true, |(Guard::If(e) | Guard::IfLet(_, e))| !used_visitor.check_expr(e));
111+
// ...or anywhere in the inner expression
112+
if match inner {
113+
IfLetOrMatch::IfLet(_, _, body, els) => {
114+
!used_visitor.check_expr(body) && els.map_or(true, |e| !used_visitor.check_expr(e))
115+
},
116+
IfLetOrMatch::Match(_, arms, ..) => !arms.iter().any(|arm| used_visitor.check_arm(arm)),
112117
};
113-
// ...or anywhere in the inner match
114-
if !arms_inner.iter().any(|arm| used_visitor.check_arm(arm));
115118
then {
116-
span_lint_and_then(
117-
cx,
118-
COLLAPSIBLE_MATCH,
119-
expr.span,
120-
"unnecessary nested match",
121-
|diag| {
122-
let mut help_span = MultiSpan::from_spans(vec![binding_span, non_wild_inner_arm.pat.span]);
123-
help_span.push_span_label(binding_span, "replace this binding".into());
124-
help_span.push_span_label(non_wild_inner_arm.pat.span, "with this pattern".into());
125-
diag.span_help(help_span, "the outer pattern can be modified to include the inner pattern");
126-
},
119+
let msg = format!(
120+
"this `{}` can be collapsed into the outer `{}`",
121+
if matches!(inner, IfLetOrMatch::Match(..)) { "match" } else { "if let" },
122+
if outer_is_match { "match" } else { "if let" },
127123
);
128-
}
129-
}
130-
}
131-
132-
fn check_if_let<'tcx>(cx: &LateContext<'tcx>, outer_expr: &'tcx Expr<'tcx>, outer_pat: &'tcx Pat<'tcx>) {
133-
let block_inner = strip_singleton_blocks(outer_expr);
134-
if_chain! {
135-
if let Some(higher::IfLet { if_then: inner_if_then, let_expr: inner_let_expr, let_pat: inner_let_pat, .. }) = higher::IfLet::hir(block_inner);
136-
if let Some(binding_id) = path_to_local(peel_ref_operators(cx, inner_let_expr));
137-
if let Some(binding_span) = find_pat_binding(outer_pat, binding_id);
138-
let mut used_visitor = LocalUsedVisitor::new(cx, binding_id);
139-
if !used_visitor.check_expr(inner_if_then);
140-
then {
141124
span_lint_and_then(
142125
cx,
143126
COLLAPSIBLE_MATCH,
144-
block_inner.span,
145-
"unnecessary nested `if let` or `match`",
127+
inner_expr.span,
128+
&msg,
146129
|diag| {
147-
let mut help_span = MultiSpan::from_spans(vec![binding_span, inner_let_pat.span]);
130+
let mut help_span = MultiSpan::from_spans(vec![binding_span, inner_then_pat.span]);
148131
help_span.push_span_label(binding_span, "replace this binding".into());
149-
help_span.push_span_label(inner_let_pat.span, "with this pattern".into());
132+
help_span.push_span_label(inner_then_pat.span, "with this pattern".into());
150133
diag.span_help(help_span, "the outer pattern can be modified to include the inner pattern");
151134
},
152135
);
@@ -168,14 +151,30 @@ fn strip_singleton_blocks<'hir>(mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir>
168151
expr
169152
}
170153

171-
/// A "wild-like" pattern is wild ("_") or `None`.
172-
/// For this lint to apply, both the outer and inner patterns
173-
/// must have "wild-like" branches that can be combined.
174-
fn is_wild_like(cx: &LateContext<'_>, pat_kind: &PatKind<'_>, arm_guard: &Option<Guard<'_>>) -> bool {
175-
if arm_guard.is_some() {
154+
enum IfLetOrMatch<'hir> {
155+
Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
156+
/// scrutinee, pattern, then block, else block
157+
IfLet(&'hir Expr<'hir>, &'hir Pat<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
158+
}
159+
160+
impl<'hir> IfLetOrMatch<'hir> {
161+
fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
162+
match expr.kind {
163+
ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
164+
_ => higher::IfLet::hir(cx, expr).map(|higher::IfLet { let_expr, let_pat, if_then, if_else }| {
165+
Self::IfLet(let_expr, let_pat, if_then, if_else)
166+
})
167+
}
168+
}
169+
}
170+
171+
/// A "wild-like" arm has a wild (`_`) or `None` pattern and no guard. Such arms can be "collapsed"
172+
/// into a single wild arm without any significant loss in semantics or readability.
173+
fn arm_is_wild_like(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
174+
if arm.guard.is_some() {
176175
return false;
177176
}
178-
match pat_kind {
177+
match arm.pat.kind {
179178
PatKind::Binding(..) | PatKind::Wild => true,
180179
PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
181180
_ => false,

src/tools/clippy/clippy_lints/src/if_let_mutex.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for IfLetMutex {
5959
if_then,
6060
if_else: Some(if_else),
6161
..
62-
}) = higher::IfLet::hir(expr)
62+
}) = higher::IfLet::hir(cx, expr)
6363
{
6464
op_visit.visit_expr(let_expr);
6565
if op_visit.mutex_lock_called {

src/tools/clippy/clippy_lints/src/if_let_some_result.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ declare_lint_pass!(OkIfLet => [IF_LET_SOME_RESULT]);
4545
impl<'tcx> LateLintPass<'tcx> for OkIfLet {
4646
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
4747
if_chain! { //begin checking variables
48-
if let Some(higher::IfLet { let_pat, let_expr, .. }) = higher::IfLet::hir(expr);
48+
if let Some(higher::IfLet { let_pat, let_expr, .. }) = higher::IfLet::hir(cx, expr);
4949
if let ExprKind::MethodCall(_, ok_span, ref result_types, _) = let_expr.kind; //check is expr.ok() has type Result<T,E>.ok(, _)
5050
if let PatKind::TupleStruct(QPath::Resolved(_, ref x), ref y, _) = let_pat.kind; //get operation
5151
if method_chain_args(let_expr, &["ok"]).is_some(); //test to see if using ok() methoduse std::marker::Sized;

src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ pub(super) fn check<'tcx>(
3737

3838
if_chain! {
3939
if let Some(inner_expr) = inner_expr;
40-
if let Some(higher::IfLet { let_pat, let_expr, if_else: None, .. }) = higher::IfLet::hir(inner_expr);
40+
if let Some(higher::IfLet { let_pat, let_expr, if_else: None, .. }) = higher::IfLet::hir(cx, inner_expr);
4141
// Ensure match_expr in `if let` statement is the same as the pat from the for-loop
4242
if let PatKind::Binding(_, pat_hir_id, _, _) = pat.kind;
4343
if path_to_local_id(let_expr, pat_hir_id);

src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &'
1717
let_expr,
1818
if_else: Some(if_else),
1919
..
20-
}) = higher::IfLet::hir(inner)
20+
}) = higher::IfLet::hir(cx, inner)
2121
{
2222
if is_simple_break_expr(if_else) {
2323
could_be_while_let(cx, expr, let_pat, let_expr);

src/tools/clippy/clippy_lints/src/manual_map.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ impl LateLintPass<'_> for ManualMap {
4949
let_expr,
5050
if_then,
5151
if_else: Some(if_else),
52-
}) = higher::IfLet::hir(expr)
52+
}) = higher::IfLet::hir(cx, expr)
5353
{
5454
manage_lint(cx, expr, (&let_pat.kind, if_then), (&PatKind::Wild, if_else), let_expr);
5555
}

src/tools/clippy/clippy_lints/src/matches.rs

+6-14
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ use clippy_utils::sugg::Sugg;
88
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
99
use clippy_utils::visitors::LocalUsedVisitor;
1010
use clippy_utils::{
11-
get_parent_expr, in_macro, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_wild, meets_msrv, msrvs,
12-
path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks,
13-
strip_pat_refs,
11+
get_parent_expr, in_macro, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_unit_expr, is_wild,
12+
meets_msrv, msrvs, path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns,
13+
remove_blocks, strip_pat_refs,
1414
};
1515
use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
1616
use core::array;
@@ -634,7 +634,7 @@ impl<'tcx> LateLintPass<'tcx> for Matches {
634634
if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
635635
check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
636636
}
637-
if let Some(higher::IfLet { let_pat, let_expr, .. }) = higher::IfLet::hir(expr) {
637+
if let Some(higher::IfLet { let_pat, let_expr, .. }) = higher::IfLet::hir(cx, expr) {
638638
check_match_ref_pats(cx, let_expr, once(let_pat), expr);
639639
}
640640
}
@@ -1298,7 +1298,7 @@ fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)
12981298
let_expr,
12991299
if_then,
13001300
if_else: Some(if_else),
1301-
}) = higher::IfLet::hir(expr)
1301+
}) = higher::IfLet::hir(cx, expr)
13021302
{
13031303
return find_matches_sugg(
13041304
cx,
@@ -1672,14 +1672,6 @@ fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
16721672
.collect()
16731673
}
16741674

1675-
fn is_unit_expr(expr: &Expr<'_>) -> bool {
1676-
match expr.kind {
1677-
ExprKind::Tup(v) if v.is_empty() => true,
1678-
ExprKind::Block(b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1679-
_ => false,
1680-
}
1681-
}
1682-
16831675
// Checks if arm has the form `None => None`
16841676
fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
16851677
matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
@@ -1835,7 +1827,7 @@ mod redundant_pattern_match {
18351827
let_pat,
18361828
let_expr,
18371829
..
1838-
}) = higher::IfLet::ast(cx, expr)
1830+
}) = higher::IfLet::hir(cx, expr)
18391831
{
18401832
find_sugg_for_if_let(cx, expr, let_pat, let_expr, "if", if_else.is_some())
18411833
}

src/tools/clippy/clippy_lints/src/option_if_let_else.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ fn format_option_in_sugg(cx: &LateContext<'_>, cond_expr: &Expr<'_>, as_ref: boo
125125
fn detect_option_if_let_else<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> Option<OptionIfLetElseOccurence> {
126126
if_chain! {
127127
if !in_macro(expr.span); // Don't lint macros, because it behaves weirdly
128-
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) }) = higher::IfLet::hir(expr);
128+
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) }) = higher::IfLet::hir(cx, expr);
129129
if !is_else_clause(cx.tcx, expr);
130130
if !is_result_ok(cx, let_expr); // Don't lint on Result::ok because a different lint does it already
131131
if let PatKind::TupleStruct(struct_qpath, [inner_pat], _) = &let_pat.kind;

src/tools/clippy/clippy_lints/src/question_mark.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ impl QuestionMark {
9797

9898
fn check_if_let_some_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
9999
if_chain! {
100-
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) }) = higher::IfLet::hir(expr);
100+
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) }) = higher::IfLet::hir(cx, expr);
101101
if Self::is_option(cx, let_expr);
102102

103103
if let PatKind::TupleStruct(ref path1, fields, None) = let_pat.kind;

src/tools/clippy/clippy_utils/src/higher.rs

+9-25
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,7 @@ pub struct IfLet<'hir> {
7979
}
8080

8181
impl<'hir> IfLet<'hir> {
82-
#[inline]
83-
pub fn ast(cx: &LateContext<'tcx>, expr: &Expr<'hir>) -> Option<Self> {
84-
let rslt = Self::hir(expr)?;
85-
Self::is_not_within_while_context(cx, expr)?;
86-
Some(rslt)
87-
}
88-
89-
#[inline]
90-
pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
82+
pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
9183
if let ExprKind::If(
9284
Expr {
9385
kind: ExprKind::Let(let_pat, let_expr, _),
@@ -97,6 +89,14 @@ impl<'hir> IfLet<'hir> {
9789
if_else,
9890
) = expr.kind
9991
{
92+
let hir = cx.tcx.hir();
93+
let mut iter = hir.parent_iter(expr.hir_id);
94+
if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
95+
if let Some((_, Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::While, _), .. }))) = iter.next() {
96+
// while loop desugar
97+
return None;
98+
}
99+
}
100100
return Some(Self {
101101
let_pat,
102102
let_expr,
@@ -106,22 +106,6 @@ impl<'hir> IfLet<'hir> {
106106
}
107107
None
108108
}
109-
110-
#[inline]
111-
fn is_not_within_while_context(cx: &LateContext<'tcx>, expr: &Expr<'hir>) -> Option<()> {
112-
let hir = cx.tcx.hir();
113-
let parent = hir.get_parent_node(expr.hir_id);
114-
let parent_parent = hir.get_parent_node(parent);
115-
let parent_parent_node = hir.get(parent_parent);
116-
if let Node::Expr(Expr {
117-
kind: ExprKind::Loop(_, _, LoopSource::While, _),
118-
..
119-
}) = parent_parent_node
120-
{
121-
return None;
122-
}
123-
Some(())
124-
}
125109
}
126110

127111
pub struct IfOrIfLet<'hir> {

src/tools/clippy/clippy_utils/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,10 @@ pub fn in_macro(span: Span) -> bool {
254254
}
255255
}
256256

257+
pub fn is_unit_expr(expr: &Expr<'_>) -> bool {
258+
matches!(expr.kind, ExprKind::Block(Block { stmts: [], expr: None, .. }, _) | ExprKind::Tup([]))
259+
}
260+
257261
/// Checks if given pattern is a wildcard (`_`)
258262
pub fn is_wild(pat: &Pat<'_>) -> bool {
259263
matches!(pat.kind, PatKind::Wild)

0 commit comments

Comments
 (0)