Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit cb25e13

Browse files
committed
Keep track of guards in the matrix
1 parent 7cd4726 commit cb25e13

File tree

4 files changed

+47
-55
lines changed

4 files changed

+47
-55
lines changed

compiler/rustc_mir_build/src/thir/pattern/usefulness.rs

Lines changed: 38 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -380,16 +380,17 @@ impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
380380
/// works well.
381381
#[derive(Clone)]
382382
pub(crate) struct PatStack<'p, 'tcx> {
383-
pub(crate) pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
383+
pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
384+
is_under_guard: bool,
384385
}
385386

386387
impl<'p, 'tcx> PatStack<'p, 'tcx> {
387-
fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
388-
Self::from_vec(smallvec![pat])
388+
fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>, is_under_guard: bool) -> Self {
389+
PatStack { pats: smallvec![pat], is_under_guard }
389390
}
390391

391-
fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
392-
PatStack { pats: vec }
392+
fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>, is_under_guard: bool) -> Self {
393+
PatStack { pats: vec, is_under_guard }
393394
}
394395

395396
fn is_empty(&self) -> bool {
@@ -412,7 +413,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
412413
// or-pattern. Panics if `self` is empty.
413414
fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
414415
self.head().iter_fields().map(move |pat| {
415-
let mut new_patstack = PatStack::from_pattern(pat);
416+
let mut new_patstack = PatStack::from_pattern(pat, self.is_under_guard);
416417
new_patstack.pats.extend_from_slice(&self.pats[1..]);
417418
new_patstack
418419
})
@@ -422,7 +423,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
422423
fn expand_and_extend<'a>(&'a self, matrix: &mut Matrix<'p, 'tcx>) {
423424
if !self.is_empty() && self.head().is_or_pat() {
424425
for pat in self.head().iter_fields() {
425-
let mut new_patstack = PatStack::from_pattern(pat);
426+
let mut new_patstack = PatStack::from_pattern(pat, self.is_under_guard);
426427
new_patstack.pats.extend_from_slice(&self.pats[1..]);
427428
if !new_patstack.is_empty() && new_patstack.head().is_or_pat() {
428429
new_patstack.expand_and_extend(matrix);
@@ -448,7 +449,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
448449
// `self.head()`.
449450
let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(pcx, ctor);
450451
new_fields.extend_from_slice(&self.pats[1..]);
451-
PatStack::from_vec(new_fields)
452+
PatStack::from_vec(new_fields, self.is_under_guard)
452453
}
453454
}
454455

@@ -466,12 +467,12 @@ impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
466467
/// A 2D matrix.
467468
#[derive(Clone)]
468469
pub(super) struct Matrix<'p, 'tcx> {
469-
pub patterns: Vec<PatStack<'p, 'tcx>>,
470+
pub rows: Vec<PatStack<'p, 'tcx>>,
470471
}
471472

472473
impl<'p, 'tcx> Matrix<'p, 'tcx> {
473474
fn empty() -> Self {
474-
Matrix { patterns: vec![] }
475+
Matrix { rows: vec![] }
475476
}
476477

477478
/// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
@@ -480,15 +481,22 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
480481
if !row.is_empty() && row.head().is_or_pat() {
481482
row.expand_and_extend(self);
482483
} else {
483-
self.patterns.push(row);
484+
self.rows.push(row);
484485
}
485486
}
486487

488+
fn rows<'a>(
489+
&'a self,
490+
) -> impl Iterator<Item = &'a PatStack<'p, 'tcx>> + Clone + DoubleEndedIterator + ExactSizeIterator
491+
{
492+
self.rows.iter()
493+
}
494+
487495
/// Iterate over the first component of each row
488496
fn heads<'a>(
489497
&'a self,
490498
) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
491-
self.patterns.iter().map(|r| r.head())
499+
self.rows().map(|r| r.head())
492500
}
493501

494502
/// This computes `S(constructor, self)`. See top of the file for explanations.
@@ -498,7 +506,7 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
498506
ctor: &Constructor<'tcx>,
499507
) -> Matrix<'p, 'tcx> {
500508
let mut matrix = Matrix::empty();
501-
for row in &self.patterns {
509+
for row in &self.rows {
502510
if ctor.is_covered_by(pcx, row.head().ctor()) {
503511
let new_row = row.pop_head_constructor(pcx, ctor);
504512
matrix.push(new_row);
@@ -521,12 +529,12 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
521529
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522530
write!(f, "\n")?;
523531

524-
let Matrix { patterns: m, .. } = self;
532+
let Matrix { rows, .. } = self;
525533
let pretty_printed_matrix: Vec<Vec<String>> =
526-
m.iter().map(|row| row.iter().map(|pat| format!("{pat:?}")).collect()).collect();
534+
rows.iter().map(|row| row.iter().map(|pat| format!("{pat:?}")).collect()).collect();
527535

528-
let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
529-
assert!(m.iter().all(|row| row.len() == column_count));
536+
let column_count = rows.iter().map(|row| row.len()).next().unwrap_or(0);
537+
assert!(rows.iter().all(|row| row.len() == column_count));
530538
let column_widths: Vec<usize> = (0..column_count)
531539
.map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
532540
.collect();
@@ -808,19 +816,16 @@ fn is_useful<'p, 'tcx>(
808816
v: &PatStack<'p, 'tcx>,
809817
witness_preference: ArmType,
810818
lint_root: HirId,
811-
is_under_guard: bool,
812819
is_top_level: bool,
813820
) -> Usefulness<'tcx> {
814821
debug!(?matrix, ?v);
815-
let Matrix { patterns: rows, .. } = matrix;
816-
817822
// The base case. We are pattern-matching on () and the return value is
818823
// based on whether our matrix has a row or not.
819824
// NOTE: This could potentially be optimized by checking rows.is_empty()
820825
// first and then, if v is non-empty, the return value is based on whether
821826
// the type of the tuple we're checking is inhabited or not.
822827
if v.is_empty() {
823-
let ret = if rows.is_empty() {
828+
let ret = if matrix.rows().all(|r| r.is_under_guard) {
824829
Usefulness::new_useful(witness_preference)
825830
} else {
826831
Usefulness::new_not_useful(witness_preference)
@@ -829,7 +834,7 @@ fn is_useful<'p, 'tcx>(
829834
return ret;
830835
}
831836

832-
debug_assert!(rows.iter().all(|r| r.len() == v.len()));
837+
debug_assert!(matrix.rows().all(|r| r.len() == v.len()));
833838

834839
// If the first pattern is an or-pattern, expand it.
835840
let mut ret = Usefulness::new_not_useful(witness_preference);
@@ -840,24 +845,21 @@ fn is_useful<'p, 'tcx>(
840845
for v in v.expand_or_pat() {
841846
debug!(?v);
842847
let usefulness = ensure_sufficient_stack(|| {
843-
is_useful(cx, &matrix, &v, witness_preference, lint_root, is_under_guard, false)
848+
is_useful(cx, &matrix, &v, witness_preference, lint_root, false)
844849
});
845850
debug!(?usefulness);
846851
ret.extend(usefulness);
847-
// If pattern has a guard don't add it to the matrix.
848-
if !is_under_guard {
849-
// We push the already-seen patterns into the matrix in order to detect redundant
850-
// branches like `Some(_) | Some(0)`.
851-
matrix.push(v);
852-
}
852+
// We push the already-seen patterns into the matrix in order to detect redundant
853+
// branches like `Some(_) | Some(0)`.
854+
matrix.push(v);
853855
}
854856
} else {
855857
let mut ty = v.head().ty();
856858

857859
// Opaque types can't get destructured/split, but the patterns can
858860
// actually hint at hidden types, so we use the patterns' types instead.
859861
if let ty::Alias(ty::Opaque, ..) = ty.kind() {
860-
if let Some(row) = rows.first() {
862+
if let Some(row) = matrix.rows().next() {
861863
ty = row.head().ty();
862864
}
863865
}
@@ -877,15 +879,7 @@ fn is_useful<'p, 'tcx>(
877879
let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
878880
let v = v.pop_head_constructor(pcx, &ctor);
879881
let usefulness = ensure_sufficient_stack(|| {
880-
is_useful(
881-
cx,
882-
&spec_matrix,
883-
&v,
884-
witness_preference,
885-
lint_root,
886-
is_under_guard,
887-
false,
888-
)
882+
is_useful(cx, &spec_matrix, &v, witness_preference, lint_root, false)
889883
});
890884
let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
891885
ret.extend(usefulness);
@@ -1118,11 +1112,9 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
11181112
.copied()
11191113
.map(|arm| {
11201114
debug!(?arm);
1121-
let v = PatStack::from_pattern(arm.pat);
1122-
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
1123-
if !arm.has_guard {
1124-
matrix.push(v);
1125-
}
1115+
let v = PatStack::from_pattern(arm.pat, arm.has_guard);
1116+
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, true);
1117+
matrix.push(v);
11261118
let reachability = if arm.pat.is_reachable() {
11271119
Reachability::Reachable(arm.pat.unreachable_spans())
11281120
} else {
@@ -1133,8 +1125,8 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
11331125
.collect();
11341126

11351127
let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty, DUMMY_SP));
1136-
let v = PatStack::from_pattern(wild_pattern);
1137-
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, lint_root, false, true);
1128+
let v = PatStack::from_pattern(wild_pattern, false);
1129+
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, lint_root, true);
11381130
let non_exhaustiveness_witnesses: Vec<_> = match usefulness {
11391131
WithWitnesses(witness_matrix) => witness_matrix.single_column(),
11401132
NoWitnesses { .. } => bug!(),

tests/ui/pattern/usefulness/issue-3601.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn main() {
3131
//~^ ERROR non-exhaustive patterns
3232
//~| NOTE the matched value is of type
3333
//~| NOTE match arms with guards don't count towards exhaustivity
34-
//~| NOTE pattern `box _` not covered
34+
//~| NOTE pattern `box ElementKind::HTMLImageElement(_)` not covered
3535
//~| NOTE `Box<ElementKind>` defined here
3636
box ElementKind::HTMLImageElement(ref d) if d.image.is_some() => true,
3737
},

tests/ui/pattern/usefulness/issue-3601.stderr

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
error[E0004]: non-exhaustive patterns: `box _` not covered
1+
error[E0004]: non-exhaustive patterns: `box ElementKind::HTMLImageElement(_)` not covered
22
--> $DIR/issue-3601.rs:30:44
33
|
44
LL | box NodeKind::Element(ed) => match ed.kind {
5-
| ^^^^^^^ pattern `box _` not covered
5+
| ^^^^^^^ pattern `box ElementKind::HTMLImageElement(_)` not covered
66
|
77
note: `Box<ElementKind>` defined here
88
--> $SRC_DIR/alloc/src/boxed.rs:LL:COL
@@ -11,7 +11,7 @@ note: `Box<ElementKind>` defined here
1111
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
1212
|
1313
LL ~ box ElementKind::HTMLImageElement(ref d) if d.image.is_some() => true,
14-
LL ~ box _ => todo!(),
14+
LL ~ box ElementKind::HTMLImageElement(_) => todo!(),
1515
|
1616

1717
error: aborting due to previous error

tests/ui/pattern/usefulness/match-non-exhaustive.stderr

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@ help: ensure that all possible cases are being handled by adding a match arm wit
1010
LL | match 0 { 1 => (), i32::MIN..=0_i32 | 2_i32..=i32::MAX => todo!() }
1111
| ++++++++++++++++++++++++++++++++++++++++++++++++
1212

13-
error[E0004]: non-exhaustive patterns: `_` not covered
13+
error[E0004]: non-exhaustive patterns: `i32::MIN..=-1_i32` and `1_i32..=i32::MAX` not covered
1414
--> $DIR/match-non-exhaustive.rs:3:11
1515
|
1616
LL | match 0 { 0 if false => () }
17-
| ^ pattern `_` not covered
17+
| ^ patterns `i32::MIN..=-1_i32` and `1_i32..=i32::MAX` not covered
1818
|
1919
= note: the matched value is of type `i32`
2020
= note: match arms with guards don't count towards exhaustivity
21-
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
21+
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern, a match arm with multiple or-patterns as shown, or multiple match arms
2222
|
23-
LL | match 0 { 0 if false => (), _ => todo!() }
24-
| ++++++++++++++
23+
LL | match 0 { 0 if false => (), i32::MIN..=-1_i32 | 1_i32..=i32::MAX => todo!() }
24+
| +++++++++++++++++++++++++++++++++++++++++++++++++
2525

2626
error: aborting due to 2 previous errors
2727

0 commit comments

Comments
 (0)