Skip to content

Commit 503bd57

Browse files
authored
Unrolled build for rust-lang#119715
Rollup merge of rust-lang#119715 - Nadrieril:graceful-type-error, r=compiler-errors Exhaustiveness: abort on type error This adds an error path to exhaustiveness checking so that we abort instead of ICEing when encountering a stray `ty::Error`. Fixes rust-lang#119493 Fixes rust-lang#119778 r? `@compiler-errors`
2 parents 0a89233 + dee657f commit 503bd57

File tree

9 files changed

+158
-39
lines changed

9 files changed

+158
-39
lines changed

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

+8-2
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,13 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
432432
}
433433

434434
let scrut_ty = scrut.ty;
435-
let report = analyze_match(&cx, &tarms, scrut_ty);
435+
let report = match analyze_match(&cx, &tarms, scrut_ty) {
436+
Ok(report) => report,
437+
Err(err) => {
438+
self.error = Err(err);
439+
return;
440+
}
441+
};
436442

437443
match source {
438444
// Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
@@ -546,7 +552,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
546552
let cx = self.new_cx(refutability, None, scrut, pat.span);
547553
let pat = self.lower_pattern(&cx, pat)?;
548554
let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
549-
let report = analyze_match(&cx, &arms, pat.ty().inner());
555+
let report = analyze_match(&cx, &arms, pat.ty().inner())?;
550556
Ok((cx, report))
551557
}
552558

compiler/rustc_pattern_analysis/src/lib.rs

+10-6
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
@@ -73,7 +77,7 @@ pub trait TypeCx: Sized + fmt::Debug {
7377
/// The set of all the constructors for `ty`.
7478
///
7579
/// This must follow the invariants of `ConstructorSet`
76-
fn ctors_for_ty(&self, ty: Self::Ty) -> ConstructorSet<Self>;
80+
fn ctors_for_ty(&self, ty: Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
7781

7882
/// Best-effort `Debug` implementation.
7983
fn debug_pat(f: &mut fmt::Formatter<'_>, pat: &DeconstructedPat<'_, Self>) -> fmt::Result;
@@ -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

+21-15
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::{
@@ -59,9 +59,13 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
5959
}
6060

6161
/// Do constructor splitting on the constructors of the column.
62-
fn analyze_ctors(&self, pcx: &PlaceCtxt<'_, 'p, 'tcx>) -> SplitConstructorSet<'p, 'tcx> {
62+
fn analyze_ctors(
63+
&self,
64+
pcx: &PlaceCtxt<'_, 'p, 'tcx>,
65+
) -> Result<SplitConstructorSet<'p, 'tcx>, ErrorGuaranteed> {
6366
let column_ctors = self.patterns.iter().map(|p| p.ctor());
64-
pcx.ctors_for_ty().split(pcx, column_ctors)
67+
let ctors_for_ty = &pcx.ctors_for_ty()?;
68+
Ok(ctors_for_ty.split(pcx, column_ctors))
6569
}
6670

6771
fn iter(&self) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'_> {
@@ -106,18 +110,18 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
106110
fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
107111
cx: MatchCtxt<'a, 'p, 'tcx>,
108112
column: &PatternColumn<'p, 'tcx>,
109-
) -> Vec<WitnessPat<'p, 'tcx>> {
113+
) -> Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> {
110114
let Some(ty) = column.head_ty() else {
111-
return Vec::new();
115+
return Ok(Vec::new());
112116
};
113117
let pcx = &PlaceCtxt::new_dummy(cx, ty);
114118

115-
let set = column.analyze_ctors(pcx);
119+
let set = column.analyze_ctors(pcx)?;
116120
if set.present.is_empty() {
117121
// We can't consistently handle the case where no constructors are present (since this would
118122
// require digging deep through any type in case there's a non_exhaustive enum somewhere),
119123
// so for consistency we refuse to handle the top-level case, where we could handle it.
120-
return vec![];
124+
return Ok(Vec::new());
121125
}
122126

123127
let mut witnesses = Vec::new();
@@ -137,7 +141,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
137141
let wild_pat = WitnessPat::wild_from_ctor(pcx, ctor);
138142
for (i, col_i) in specialized_columns.iter().enumerate() {
139143
// Compute witnesses for each column.
140-
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)?;
141145
// For each witness, we build a new pattern in the shape of `ctor(_, _, wit, _, _)`,
142146
// adding enough wildcards to match `arity`.
143147
for wit in wits_for_col_i {
@@ -147,21 +151,21 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
147151
}
148152
}
149153
}
150-
witnesses
154+
Ok(witnesses)
151155
}
152156

153157
pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
154158
cx: MatchCtxt<'a, 'p, 'tcx>,
155159
arms: &[MatchArm<'p, 'tcx>],
156160
pat_column: &PatternColumn<'p, 'tcx>,
157161
scrut_ty: RevealedTy<'tcx>,
158-
) {
162+
) -> Result<(), ErrorGuaranteed> {
159163
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
160164
if !matches!(
161165
rcx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, rcx.match_lint_level).0,
162166
rustc_session::lint::Level::Allow
163167
) {
164-
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column);
168+
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column)?;
165169
if !witnesses.is_empty() {
166170
// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
167171
// is not exhaustive enough.
@@ -200,21 +204,22 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
200204
}
201205
}
202206
}
207+
Ok(())
203208
}
204209

205210
/// Traverse the patterns to warn the user about ranges that overlap on their endpoints.
206211
#[instrument(level = "debug", skip(cx))]
207212
pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
208213
cx: MatchCtxt<'a, 'p, 'tcx>,
209214
column: &PatternColumn<'p, 'tcx>,
210-
) {
215+
) -> Result<(), ErrorGuaranteed> {
211216
let Some(ty) = column.head_ty() else {
212-
return;
217+
return Ok(());
213218
};
214219
let pcx = &PlaceCtxt::new_dummy(cx, ty);
215220
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
216221

217-
let set = column.analyze_ctors(pcx);
222+
let set = column.analyze_ctors(pcx)?;
218223

219224
if matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_)) {
220225
let emit_lint = |overlap: &IntRange, this_span: Span, overlapped_spans: &[Span]| {
@@ -271,8 +276,9 @@ pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
271276
// Recurse into the fields.
272277
for ctor in set.present {
273278
for col in column.specialize(pcx, &ctor) {
274-
lint_overlapping_range_endpoints(cx, &col);
279+
lint_overlapping_range_endpoints(cx, &col)?;
275280
}
276281
}
277282
}
283+
Ok(())
278284
}

compiler/rustc_pattern_analysis/src/rustc.rs

+15-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ use rustc_middle::mir::interpret::Scalar;
1212
use rustc_middle::mir::{self, Const};
1313
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange, PatRangeBoundary};
1414
use rustc_middle::ty::layout::IntegerExt;
15+
use rustc_middle::ty::TypeVisitableExt;
1516
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, VariantDef};
17+
use rustc_span::ErrorGuaranteed;
1618
use rustc_span::{Span, DUMMY_SP};
1719
use rustc_target::abi::{FieldIdx, Integer, VariantIdx, FIRST_VARIANT};
1820
use smallvec::SmallVec;
@@ -302,7 +304,10 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
302304
///
303305
/// See [`crate::constructor`] for considerations of emptiness.
304306
#[instrument(level = "debug", skip(self), ret)]
305-
pub fn ctors_for_ty(&self, ty: RevealedTy<'tcx>) -> ConstructorSet<'p, 'tcx> {
307+
pub fn ctors_for_ty(
308+
&self,
309+
ty: RevealedTy<'tcx>,
310+
) -> Result<ConstructorSet<'p, 'tcx>, ErrorGuaranteed> {
306311
let cx = self;
307312
let make_uint_range = |start, end| {
308313
IntRange::from_range(
@@ -311,9 +316,11 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
311316
RangeEnd::Included,
312317
)
313318
};
319+
// Abort on type error.
320+
ty.error_reported()?;
314321
// This determines the set of all possible constructors for the type `ty`. For numbers,
315322
// arrays and slices we use ranges and variable-length slices when appropriate.
316-
match ty.kind() {
323+
Ok(match ty.kind() {
317324
ty::Bool => ConstructorSet::Bool,
318325
ty::Char => {
319326
// The valid Unicode Scalar Value ranges.
@@ -423,7 +430,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
423430
ty::CoroutineWitness(_, _) | ty::Bound(_, _) | ty::Placeholder(_) | ty::Infer(_) => {
424431
bug!("Encountered unexpected type in `ConstructorSet::for_ty`: {ty:?}")
425432
}
426-
}
433+
})
427434
}
428435

429436
pub(crate) fn lower_pat_range_bdy(
@@ -944,6 +951,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
944951

945952
impl<'p, 'tcx> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
946953
type Ty = RevealedTy<'tcx>;
954+
type Error = ErrorGuaranteed;
947955
type VariantIdx = VariantIdx;
948956
type StrLit = Const<'tcx>;
949957
type ArmData = HirId;
@@ -963,7 +971,10 @@ impl<'p, 'tcx> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
963971
) -> &[Self::Ty] {
964972
self.ctor_sub_tys(ctor, ty)
965973
}
966-
fn ctors_for_ty(&self, ty: Self::Ty) -> crate::constructor::ConstructorSet<Self> {
974+
fn ctors_for_ty(
975+
&self,
976+
ty: Self::Ty,
977+
) -> Result<crate::constructor::ConstructorSet<Self>, Self::Error> {
967978
self.ctors_for_ty(ty)
968979
}
969980

compiler/rustc_pattern_analysis/src/usefulness.rs

+13-12
Original file line numberDiff line numberDiff line change
@@ -753,7 +753,7 @@ impl<'a, 'p, Cx: TypeCx> PlaceCtxt<'a, 'p, Cx> {
753753
pub(crate) fn ctor_sub_tys(&self, ctor: &Constructor<Cx>) -> &[Cx::Ty] {
754754
self.mcx.tycx.ctor_sub_tys(ctor, self.ty)
755755
}
756-
pub(crate) fn ctors_for_ty(&self) -> ConstructorSet<Cx> {
756+
pub(crate) fn ctors_for_ty(&self) -> Result<ConstructorSet<Cx>, Cx::Error> {
757757
self.mcx.tycx.ctors_for_ty(self.ty)
758758
}
759759
}
@@ -1336,14 +1336,14 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13361336
mcx: MatchCtxt<'a, 'p, Cx>,
13371337
matrix: &mut Matrix<'p, Cx>,
13381338
is_top_level: bool,
1339-
) -> WitnessMatrix<Cx> {
1339+
) -> Result<WitnessMatrix<Cx>, Cx::Error> {
13401340
debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
13411341

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

13491349
let Some(ty) = matrix.head_ty() else {
@@ -1355,16 +1355,16 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13551355
// When there's an unguarded row, the match is exhaustive and any subsequent row is not
13561356
// useful.
13571357
if !row.is_under_guard {
1358-
return WitnessMatrix::empty();
1358+
return Ok(WitnessMatrix::empty());
13591359
}
13601360
}
13611361
// No (unguarded) rows, so the match is not exhaustive. We return a new witness unless
13621362
// irrelevant.
13631363
return if matrix.wildcard_row_is_relevant {
1364-
WitnessMatrix::unit_witness()
1364+
Ok(WitnessMatrix::unit_witness())
13651365
} else {
13661366
// We choose to not report anything here; see at the top for details.
1367-
WitnessMatrix::empty()
1367+
Ok(WitnessMatrix::empty())
13681368
};
13691369
};
13701370

@@ -1378,7 +1378,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13781378

13791379
// Analyze the constructors present in this column.
13801380
let ctors = matrix.heads().map(|p| p.ctor());
1381-
let ctors_for_ty = pcx.ctors_for_ty();
1381+
let ctors_for_ty = pcx.ctors_for_ty()?;
13821382
let is_integers = matches!(ctors_for_ty, ConstructorSet::Integers { .. }); // For diagnostics.
13831383
let split_set = ctors_for_ty.split(pcx, ctors);
13841384
let all_missing = split_set.present.is_empty();
@@ -1417,7 +1417,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14171417
let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant);
14181418
let mut witnesses = ensure_sufficient_stack(|| {
14191419
compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix, false)
1420-
});
1420+
})?;
14211421

14221422
// Transform witnesses for `spec_matrix` into witnesses for `matrix`.
14231423
witnesses.apply_constructor(pcx, &missing_ctors, &ctor, report_individual_missing_ctors);
@@ -1438,7 +1438,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14381438
}
14391439
}
14401440

1441-
ret
1441+
Ok(ret)
14421442
}
14431443

14441444
/// Indicates whether or not a given arm is useful.
@@ -1469,9 +1469,10 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
14691469
arms: &[MatchArm<'p, Cx>],
14701470
scrut_ty: Cx::Ty,
14711471
scrut_validity: ValidityConstraint,
1472-
) -> UsefulnessReport<'p, Cx> {
1472+
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
14731473
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1474-
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
1474+
let non_exhaustiveness_witnesses =
1475+
compute_exhaustiveness_and_usefulness(cx, &mut matrix, true)?;
14751476

14761477
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
14771478
let arm_usefulness: Vec<_> = arms
@@ -1488,5 +1489,5 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
14881489
(arm, usefulness)
14891490
})
14901491
.collect();
1491-
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
1492+
Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses })
14921493
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fn main() {}
2+
3+
fn foo() {
4+
#[derive(Copy, Clone)]
5+
struct Foo(NonExistent);
6+
//~^ ERROR cannot find type
7+
//~| ERROR cannot find type
8+
9+
type U = impl Copy;
10+
//~^ ERROR `impl Trait` in type aliases is unstable
11+
let foo: U = Foo(());
12+
let Foo(()) = foo;
13+
}

0 commit comments

Comments
 (0)