Skip to content

Commit ae77d68

Browse files
committed
Keep rows with guards in the matrix
1 parent c07c143 commit ae77d68

File tree

6 files changed

+52
-60
lines changed

6 files changed

+52
-60
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
@@ -388,16 +388,17 @@ impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
388388
/// works well.
389389
#[derive(Clone)]
390390
pub(crate) struct PatStack<'p, 'tcx> {
391-
pub(crate) pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
391+
pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
392+
is_under_guard: bool,
392393
}
393394

394395
impl<'p, 'tcx> PatStack<'p, 'tcx> {
395-
fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
396-
Self::from_vec(smallvec![pat])
396+
fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>, is_under_guard: bool) -> Self {
397+
PatStack { pats: smallvec![pat], is_under_guard }
397398
}
398399

399-
fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
400-
PatStack { pats: vec }
400+
fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>, is_under_guard: bool) -> Self {
401+
PatStack { pats: vec, is_under_guard }
401402
}
402403

403404
fn is_empty(&self) -> bool {
@@ -420,7 +421,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
420421
// or-pattern. Panics if `self` is empty.
421422
fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
422423
self.head().iter_fields().map(move |pat| {
423-
let mut new_patstack = PatStack::from_pattern(pat);
424+
let mut new_patstack = PatStack::from_pattern(pat, self.is_under_guard);
424425
new_patstack.pats.extend_from_slice(&self.pats[1..]);
425426
new_patstack
426427
})
@@ -430,7 +431,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
430431
fn expand_and_extend<'a>(&'a self, matrix: &mut Matrix<'p, 'tcx>) {
431432
if !self.is_empty() && self.head().is_or_pat() {
432433
for pat in self.head().iter_fields() {
433-
let mut new_patstack = PatStack::from_pattern(pat);
434+
let mut new_patstack = PatStack::from_pattern(pat, self.is_under_guard);
434435
new_patstack.pats.extend_from_slice(&self.pats[1..]);
435436
if !new_patstack.is_empty() && new_patstack.head().is_or_pat() {
436437
new_patstack.expand_and_extend(matrix);
@@ -456,7 +457,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
456457
// `self.head()`.
457458
let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(pcx, ctor);
458459
new_fields.extend_from_slice(&self.pats[1..]);
459-
PatStack::from_vec(new_fields)
460+
PatStack::from_vec(new_fields, self.is_under_guard)
460461
}
461462
}
462463

@@ -474,12 +475,12 @@ impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
474475
/// A 2D matrix.
475476
#[derive(Clone)]
476477
pub(super) struct Matrix<'p, 'tcx> {
477-
pub patterns: Vec<PatStack<'p, 'tcx>>,
478+
pub rows: Vec<PatStack<'p, 'tcx>>,
478479
}
479480

480481
impl<'p, 'tcx> Matrix<'p, 'tcx> {
481482
fn empty() -> Self {
482-
Matrix { patterns: vec![] }
483+
Matrix { rows: vec![] }
483484
}
484485

485486
/// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
@@ -488,15 +489,22 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
488489
if !row.is_empty() && row.head().is_or_pat() {
489490
row.expand_and_extend(self);
490491
} else {
491-
self.patterns.push(row);
492+
self.rows.push(row);
492493
}
493494
}
494495

496+
fn rows<'a>(
497+
&'a self,
498+
) -> impl Iterator<Item = &'a PatStack<'p, 'tcx>> + Clone + DoubleEndedIterator + ExactSizeIterator
499+
{
500+
self.rows.iter()
501+
}
502+
495503
/// Iterate over the first component of each row
496504
fn heads<'a>(
497505
&'a self,
498506
) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
499-
self.patterns.iter().map(|r| r.head())
507+
self.rows().map(|r| r.head())
500508
}
501509

502510
/// This computes `S(constructor, self)`. See top of the file for explanations.
@@ -506,7 +514,7 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
506514
ctor: &Constructor<'tcx>,
507515
) -> Matrix<'p, 'tcx> {
508516
let mut matrix = Matrix::empty();
509-
for row in &self.patterns {
517+
for row in &self.rows {
510518
if ctor.is_covered_by(pcx, row.head().ctor()) {
511519
let new_row = row.pop_head_constructor(pcx, ctor);
512520
matrix.push(new_row);
@@ -529,12 +537,12 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
529537
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530538
write!(f, "\n")?;
531539

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

536-
let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
537-
assert!(m.iter().all(|row| row.len() == column_count));
544+
let column_count = rows.iter().map(|row| row.len()).next().unwrap_or(0);
545+
assert!(rows.iter().all(|row| row.len() == column_count));
538546
let column_widths: Vec<usize> = (0..column_count)
539547
.map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
540548
.collect();
@@ -816,19 +824,16 @@ fn is_useful<'p, 'tcx>(
816824
v: &PatStack<'p, 'tcx>,
817825
witness_preference: ArmType,
818826
lint_root: HirId,
819-
is_under_guard: bool,
820827
is_top_level: bool,
821828
) -> Usefulness<'tcx> {
822829
debug!(?matrix, ?v);
823-
let Matrix { patterns: rows, .. } = matrix;
824-
825830
// The base case. We are pattern-matching on () and the return value is
826831
// based on whether our matrix has a row or not.
827832
// NOTE: This could potentially be optimized by checking rows.is_empty()
828833
// first and then, if v is non-empty, the return value is based on whether
829834
// the type of the tuple we're checking is inhabited or not.
830835
if v.is_empty() {
831-
let ret = if rows.is_empty() {
836+
let ret = if matrix.rows().all(|r| r.is_under_guard) {
832837
Usefulness::new_useful(witness_preference)
833838
} else {
834839
Usefulness::new_not_useful(witness_preference)
@@ -837,7 +842,7 @@ fn is_useful<'p, 'tcx>(
837842
return ret;
838843
}
839844

840-
debug_assert!(rows.iter().all(|r| r.len() == v.len()));
845+
debug_assert!(matrix.rows().all(|r| r.len() == v.len()));
841846

842847
// If the first pattern is an or-pattern, expand it.
843848
let mut ret = Usefulness::new_not_useful(witness_preference);
@@ -848,24 +853,21 @@ fn is_useful<'p, 'tcx>(
848853
for v in v.expand_or_pat() {
849854
debug!(?v);
850855
let usefulness = ensure_sufficient_stack(|| {
851-
is_useful(cx, &matrix, &v, witness_preference, lint_root, is_under_guard, false)
856+
is_useful(cx, &matrix, &v, witness_preference, lint_root, false)
852857
});
853858
debug!(?usefulness);
854859
ret.extend(usefulness);
855-
// If pattern has a guard don't add it to the matrix.
856-
if !is_under_guard {
857-
// We push the already-seen patterns into the matrix in order to detect redundant
858-
// branches like `Some(_) | Some(0)`.
859-
matrix.push(v);
860-
}
860+
// We push the already-seen patterns into the matrix in order to detect redundant
861+
// branches like `Some(_) | Some(0)`.
862+
matrix.push(v);
861863
}
862864
} else {
863865
let mut ty = v.head().ty();
864866

865867
// Opaque types can't get destructured/split, but the patterns can
866868
// actually hint at hidden types, so we use the patterns' types instead.
867869
if let ty::Alias(ty::Opaque, ..) = ty.kind() {
868-
if let Some(row) = rows.first() {
870+
if let Some(row) = matrix.rows().next() {
869871
ty = row.head().ty();
870872
}
871873
}
@@ -885,15 +887,7 @@ fn is_useful<'p, 'tcx>(
885887
let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
886888
let v = v.pop_head_constructor(pcx, &ctor);
887889
let usefulness = ensure_sufficient_stack(|| {
888-
is_useful(
889-
cx,
890-
&spec_matrix,
891-
&v,
892-
witness_preference,
893-
lint_root,
894-
is_under_guard,
895-
false,
896-
)
890+
is_useful(cx, &spec_matrix, &v, witness_preference, lint_root, false)
897891
});
898892
let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
899893
ret.extend(usefulness);
@@ -1163,11 +1157,9 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
11631157
.copied()
11641158
.map(|arm| {
11651159
debug!(?arm);
1166-
let v = PatStack::from_pattern(arm.pat);
1167-
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
1168-
if !arm.has_guard {
1169-
matrix.push(v);
1170-
}
1160+
let v = PatStack::from_pattern(arm.pat, arm.has_guard);
1161+
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, true);
1162+
matrix.push(v);
11711163
let reachability = if arm.pat.is_reachable() {
11721164
Reachability::Reachable(arm.pat.unreachable_spans())
11731165
} else {
@@ -1178,8 +1170,8 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
11781170
.collect();
11791171

11801172
let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty, DUMMY_SP));
1181-
let v = PatStack::from_pattern(wild_pattern);
1182-
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, lint_root, false, true);
1173+
let v = PatStack::from_pattern(wild_pattern, false);
1174+
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, lint_root, true);
11831175
let non_exhaustiveness_witnesses: Vec<_> = match usefulness {
11841176
WithWitnesses(witness_matrix) => witness_matrix.single_column(),
11851177
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

tests/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ fn main() {
4444
[] => {}
4545
}
4646
match s {
47-
//~^ ERROR `&_` not covered
47+
//~^ ERROR `&[]` and `&[_, ..]` not covered
4848
[..] if false => {}
4949
}
5050
match s {

tests/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,18 +89,18 @@ LL ~ [] => {},
8989
LL + &[_, ..] => todo!()
9090
|
9191

92-
error[E0004]: non-exhaustive patterns: `&_` not covered
92+
error[E0004]: non-exhaustive patterns: `&[]` and `&[_, ..]` not covered
9393
--> $DIR/slice-patterns-exhaustiveness.rs:46:11
9494
|
9595
LL | match s {
96-
| ^ pattern `&_` not covered
96+
| ^ patterns `&[]` and `&[_, ..]` not covered
9797
|
9898
= note: the matched value is of type `&[bool]`
9999
= note: match arms with guards don't count towards exhaustivity
100-
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
100+
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
101101
|
102102
LL ~ [..] if false => {},
103-
LL + &_ => todo!()
103+
LL + &[] | &[_, ..] => todo!()
104104
|
105105

106106
error[E0004]: non-exhaustive patterns: `&[_, _, ..]` not covered

0 commit comments

Comments
 (0)