Skip to content

Commit 07d5f19

Browse files
committed
Add an error path to the algorithm
1 parent d8b44d2 commit 07d5f19

File tree

5 files changed

+40
-28
lines changed

5 files changed

+40
-28
lines changed

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,10 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
430430
}
431431

432432
let scrut_ty = scrut.ty;
433-
let report = analyze_match(&cx, &tarms, scrut_ty);
433+
let Ok(report) = analyze_match(&cx, &tarms, scrut_ty).map_err(|err| self.error = Err(err))
434+
else {
435+
return;
436+
};
434437

435438
match source {
436439
// Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
@@ -544,7 +547,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
544547
let cx = self.new_cx(refutability, None, scrut, pat.span);
545548
let pat = self.lower_pattern(&cx, pat)?;
546549
let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
547-
let report = analyze_match(&cx, &arms, pat.ty().inner());
550+
let report = analyze_match(&cx, &arms, pat.ty().inner())?;
548551
Ok((cx, report))
549552
}
550553

compiler/rustc_pattern_analysis/src/lib.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ use std::fmt;
2424
use rustc_index::Idx;
2525
#[cfg(feature = "rustc")]
2626
use rustc_middle::ty::Ty;
27+
#[cfg(feature = "rustc")]
28+
use rustc_span::ErrorGuaranteed;
2729

2830
use crate::constructor::{Constructor, ConstructorSet};
2931
#[cfg(feature = "rustc")]
@@ -52,6 +54,8 @@ impl<'a, T: ?Sized> Captures<'a> for T {}
5254
pub trait TypeCx: Sized + fmt::Debug {
5355
/// The type of a pattern.
5456
type Ty: Copy + Clone + fmt::Debug; // FIXME: remove Copy
57+
/// Errors that can abort analysis.
58+
type Error: fmt::Debug;
5559
/// The index of an enum variant.
5660
type VariantIdx: Clone + Idx;
5761
/// A string literal
@@ -109,25 +113,25 @@ pub fn analyze_match<'p, 'tcx>(
109113
tycx: &RustcMatchCheckCtxt<'p, 'tcx>,
110114
arms: &[rustc::MatchArm<'p, 'tcx>],
111115
scrut_ty: Ty<'tcx>,
112-
) -> rustc::UsefulnessReport<'p, 'tcx> {
116+
) -> Result<rustc::UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
113117
// Arena to store the extra wildcards we construct during analysis.
114118
let wildcard_arena = tycx.pattern_arena;
115119
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
116120
let scrut_validity = ValidityConstraint::from_bool(tycx.known_valid_scrutinee);
117121
let cx = MatchCtxt { tycx, wildcard_arena };
118122

119-
let report = compute_match_usefulness(cx, arms, scrut_ty, scrut_validity);
123+
let report = compute_match_usefulness(cx, arms, scrut_ty, scrut_validity)?;
120124

121125
let pat_column = PatternColumn::new(arms);
122126

123127
// Lint on ranges that overlap on their endpoints, which is likely a mistake.
124-
lint_overlapping_range_endpoints(cx, &pat_column);
128+
lint_overlapping_range_endpoints(cx, &pat_column)?;
125129

126130
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
127131
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.
128132
if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
129-
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)
133+
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)?;
130134
}
131135

132-
report
136+
Ok(report)
133137
}

compiler/rustc_pattern_analysis/src/lints.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_data_structures::captures::Captures;
44
use rustc_middle::ty;
55
use rustc_session::lint;
66
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
7-
use rustc_span::Span;
7+
use rustc_span::{ErrorGuaranteed, Span};
88

99
use crate::constructor::{IntRange, MaybeInfiniteInt};
1010
use crate::errors::{
@@ -110,9 +110,9 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
110110
fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
111111
cx: MatchCtxt<'a, 'p, 'tcx>,
112112
column: &PatternColumn<'p, 'tcx>,
113-
) -> Vec<WitnessPat<'p, 'tcx>> {
113+
) -> Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> {
114114
let Some(ty) = column.head_ty() else {
115-
return Vec::new();
115+
return Ok(Vec::new());
116116
};
117117
let pcx = &PlaceCtxt::new_dummy(cx, ty);
118118

@@ -121,7 +121,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
121121
// We can't consistently handle the case where no constructors are present (since this would
122122
// require digging deep through any type in case there's a non_exhaustive enum somewhere),
123123
// so for consistency we refuse to handle the top-level case, where we could handle it.
124-
return vec![];
124+
return Ok(Vec::new());
125125
}
126126

127127
let mut witnesses = Vec::new();
@@ -141,7 +141,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
141141
let wild_pat = WitnessPat::wild_from_ctor(pcx, ctor);
142142
for (i, col_i) in specialized_columns.iter().enumerate() {
143143
// Compute witnesses for each column.
144-
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i);
144+
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i)?;
145145
// For each witness, we build a new pattern in the shape of `ctor(_, _, wit, _, _)`,
146146
// adding enough wildcards to match `arity`.
147147
for wit in wits_for_col_i {
@@ -151,21 +151,21 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
151151
}
152152
}
153153
}
154-
witnesses
154+
Ok(witnesses)
155155
}
156156

157157
pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
158158
cx: MatchCtxt<'a, 'p, 'tcx>,
159159
arms: &[MatchArm<'p, 'tcx>],
160160
pat_column: &PatternColumn<'p, 'tcx>,
161161
scrut_ty: RevealedTy<'tcx>,
162-
) {
162+
) -> Result<(), ErrorGuaranteed> {
163163
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
164164
if !matches!(
165165
rcx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, rcx.match_lint_level).0,
166166
rustc_session::lint::Level::Allow
167167
) {
168-
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column);
168+
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column)?;
169169
if !witnesses.is_empty() {
170170
// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
171171
// is not exhaustive enough.
@@ -204,16 +204,17 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
204204
}
205205
}
206206
}
207+
Ok(())
207208
}
208209

209210
/// Traverse the patterns to warn the user about ranges that overlap on their endpoints.
210211
#[instrument(level = "debug", skip(cx))]
211212
pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
212213
cx: MatchCtxt<'a, 'p, 'tcx>,
213214
column: &PatternColumn<'p, 'tcx>,
214-
) {
215+
) -> Result<(), ErrorGuaranteed> {
215216
let Some(ty) = column.head_ty() else {
216-
return;
217+
return Ok(());
217218
};
218219
let pcx = &PlaceCtxt::new_dummy(cx, ty);
219220
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
@@ -275,8 +276,9 @@ pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
275276
// Recurse into the fields.
276277
for ctor in set.present {
277278
for col in column.specialize(pcx, &ctor) {
278-
lint_overlapping_range_endpoints(cx, &col);
279+
lint_overlapping_range_endpoints(cx, &col)?;
279280
}
280281
}
281282
}
283+
Ok(())
282284
}

compiler/rustc_pattern_analysis/src/rustc.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use rustc_middle::mir::{self, Const};
1313
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange, PatRangeBoundary};
1414
use rustc_middle::ty::layout::IntegerExt;
1515
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, VariantDef};
16+
use rustc_span::ErrorGuaranteed;
1617
use rustc_span::{Span, DUMMY_SP};
1718
use rustc_target::abi::{FieldIdx, Integer, VariantIdx, FIRST_VARIANT};
1819
use smallvec::SmallVec;
@@ -944,6 +945,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
944945

945946
impl<'p, 'tcx> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
946947
type Ty = RevealedTy<'tcx>;
948+
type Error = ErrorGuaranteed;
947949
type VariantIdx = VariantIdx;
948950
type StrLit = Const<'tcx>;
949951
type ArmData = HirId;

compiler/rustc_pattern_analysis/src/usefulness.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,14 +1341,14 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13411341
mcx: MatchCtxt<'a, 'p, Cx>,
13421342
matrix: &mut Matrix<'p, Cx>,
13431343
is_top_level: bool,
1344-
) -> WitnessMatrix<Cx> {
1344+
) -> Result<WitnessMatrix<Cx>, Cx::Error> {
13451345
debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
13461346

13471347
if !matrix.wildcard_row_is_relevant && matrix.rows().all(|r| !r.pats.relevant) {
13481348
// Here we know that nothing will contribute further to exhaustiveness or usefulness. This
13491349
// is purely an optimization: skipping this check doesn't affect correctness. See the top of
13501350
// the file for details.
1351-
return WitnessMatrix::empty();
1351+
return Ok(WitnessMatrix::empty());
13521352
}
13531353

13541354
let Some(ty) = matrix.head_ty() else {
@@ -1360,16 +1360,16 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13601360
// When there's an unguarded row, the match is exhaustive and any subsequent row is not
13611361
// useful.
13621362
if !row.is_under_guard {
1363-
return WitnessMatrix::empty();
1363+
return Ok(WitnessMatrix::empty());
13641364
}
13651365
}
13661366
// No (unguarded) rows, so the match is not exhaustive. We return a new witness unless
13671367
// irrelevant.
13681368
return if matrix.wildcard_row_is_relevant {
1369-
WitnessMatrix::unit_witness()
1369+
Ok(WitnessMatrix::unit_witness())
13701370
} else {
13711371
// We choose to not report anything here; see at the top for details.
1372-
WitnessMatrix::empty()
1372+
Ok(WitnessMatrix::empty())
13731373
};
13741374
};
13751375

@@ -1422,7 +1422,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14221422
let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant);
14231423
let mut witnesses = ensure_sufficient_stack(|| {
14241424
compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix, false)
1425-
});
1425+
})?;
14261426

14271427
// Transform witnesses for `spec_matrix` into witnesses for `matrix`.
14281428
witnesses.apply_constructor(pcx, &missing_ctors, &ctor, report_individual_missing_ctors);
@@ -1443,7 +1443,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14431443
}
14441444
}
14451445

1446-
ret
1446+
Ok(ret)
14471447
}
14481448

14491449
/// Indicates whether or not a given arm is useful.
@@ -1474,9 +1474,10 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
14741474
arms: &[MatchArm<'p, Cx>],
14751475
scrut_ty: Cx::Ty,
14761476
scrut_validity: ValidityConstraint,
1477-
) -> UsefulnessReport<'p, Cx> {
1477+
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
14781478
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1479-
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
1479+
let non_exhaustiveness_witnesses =
1480+
compute_exhaustiveness_and_usefulness(cx, &mut matrix, true)?;
14801481

14811482
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
14821483
let arm_usefulness: Vec<_> = arms
@@ -1493,5 +1494,5 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
14931494
(arm, usefulness)
14941495
})
14951496
.collect();
1496-
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
1497+
Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses })
14971498
}

0 commit comments

Comments
 (0)