Skip to content

Commit a27386d

Browse files
authored
Rollup merge of rust-lang#122792 - Nadrieril:stabilize-min-exh-pats2, r=fee1-dead
Stabilize `min_exhaustive_patterns` ## Stabilisation report I propose we stabilize the [`min_exhaustive_patterns`](rust-lang#119612) language feature. With this feature, patterns of empty types are considered unreachable when matched by-value. This allows: ```rust enum Void {} fn foo() -> Result<u32, Void>; fn main() { let Ok(x) = foo(); // also match foo() { Ok(x) => ..., } } ``` This is a subset of the long-unstable [`exhaustive_patterns`](rust-lang#51085) feature. That feature is blocked because omitting empty patterns is tricky when *not* matched by-value. This PR stabilizes the by-value case, which is not tricky. The not-by-value cases (behind references, pointers, and unions) stay as they are today, e.g. ```rust enum Void {} fn foo() -> Result<u32, &Void>; fn main() { let Ok(x) = foo(); // ERROR: missing `Err(_)` } ``` The consequence on existing code is some extra "unreachable pattern" warnings. This is fully backwards-compatible. ### Comparison with today's rust This proposal only affects match checking of empty types (i.e. types with no valid values). Non-empty types behave the same with or without this feature. Note that everything below is phrased in terms of `match` but applies equallly to `if let` and other pattern-matching expressions. To be precise, a visibly empty type is: - an enum with no variants; - the never type `!`; - a struct with a *visible* field of a visibly empty type (and no #[non_exhaustive] annotation); - a tuple where one of the types is visibly empty; - en enum with all variants visibly empty (and no `#[non_exhaustive]` annotation); - a `[T; N]` with `N != 0` and `T` visibly empty; - all other types are nonempty. (An extra change was proposed below: that we ignore #[non_exhaustive] for structs since adding fields cannot turn an empty struct into a non-empty one) For normal types, exhaustiveness checking requires that we list all variants (or use a wildcard). For empty types it's more subtle: in some cases we require a `_` pattern even though there are no valid values that can match it. This is where the difference lies regarding this feature. #### Today's rust Under today's rust, a `_` is required for all empty types, except specifically: if the matched expression is of type `!` (the never type) or `EmptyEnum` (where `EmptyEnum` is an enum with no variants), then the `_` is not required. ```rust let foo: Result<u32, !> = ...; match foo { Ok(x) => ..., Err(_) => ..., // required } let foo: Result<u32, &!> = ...; match foo { Ok(x) => ..., Err(_) => ..., // required } let foo: &! = ...; match foo { _ => ..., // required } fn blah(foo: (u32, !)) { match foo { _ => ..., // required } } unsafe { let ptr: *const ! = ...; match *ptr {} // allowed let ptr: *const (u32, !) = ...; match *ptr { (x, _) => { ... } // required } let ptr: *const Result<u32, !> = ...; match *ptr { Ok(x) => { ... } Err(_) => { ... } // required } } ``` #### After this PR After this PR, a pattern of an empty type can be omitted if (and only if): - the match scrutinee expression has type `!` or `EmptyEnum` (like before); - *or* the empty type is matched by value (that's the new behavior). In all other cases, a `_` is required to match on an empty type. ```rust let foo: Result<u32, !> = ...; match foo { Ok(x) => ..., // `Err` not required } let foo: Result<u32, &!> = ...; match foo { Ok(x) => ..., Err(_) => ..., // required because `!` is under a dereference } let foo: &! = ...; match foo { _ => ..., // required because `!` is under a dereference } fn blah(foo: (u32, !)) { match foo {} // allowed } unsafe { let ptr: *const ! = ...; match *ptr {} // allowed let ptr: *const (u32, !) = ...; match *ptr { (x, _) => { ... } // required because the matched place is under a (pointer) dereference } let ptr: *const Result<u32, !> = ...; match *ptr { Ok(x) => { ... } Err(_) => { ... } // required because the matched place is under a (pointer) dereference } } ``` ### Documentation The reference does not say anything specific about exhaustiveness checking, hence there is nothing to update there. The nomicon does, I opened rust-lang/nomicon#445 to reflect the changes. ### Tests The relevant tests are in `tests/ui/pattern/usefulness/empty-types.rs`. ### Unresolved Questions None that I know of.
2 parents c9687a9 + 48c7ebe commit a27386d

File tree

98 files changed

+1059
-935
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+1059
-935
lines changed

compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,7 @@ pub enum E2<X> {
585585
V4,
586586
}
587587

588+
#[allow(unreachable_patterns)]
588589
fn check_niche_behavior() {
589590
if let E1::V2 { .. } = (E1::V1 { f: true }) {
590591
intrinsics::abort();

compiler/rustc_codegen_gcc/example/mini_core_hello_world.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ pub enum E2<X> {
430430
V4,
431431
}
432432

433+
#[allow(unreachable_patterns)]
433434
fn check_niche_behavior () {
434435
if let E1::V2 { .. } = (E1::V1 { f: true }) {
435436
intrinsics::abort();

compiler/rustc_errors/src/diagnostic_impls.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ macro_rules! into_diag_arg_for_number {
6666
impl IntoDiagArg for $ty {
6767
fn into_diag_arg(self) -> DiagArgValue {
6868
// Convert to a string if it won't fit into `Number`.
69+
#[allow(irrefutable_let_patterns)]
6970
if let Ok(n) = TryInto::<i32>::try_into(self) {
7071
DiagArgValue::Number(n)
7172
} else {

compiler/rustc_feature/src/accepted.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,8 @@ declare_features! (
267267
(accepted, min_const_generics, "1.51.0", Some(74878)),
268268
/// Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
269269
(accepted, min_const_unsafe_fn, "1.33.0", Some(55607)),
270+
/// Allows exhaustive pattern matching on uninhabited types when matched by value.
271+
(accepted, min_exhaustive_patterns, "CURRENT_RUSTC_VERSION", Some(119612)),
270272
/// Allows using `Self` and associated types in struct expressions and patterns.
271273
(accepted, more_struct_aliases, "1.16.0", Some(37544)),
272274
/// Allows using the MOVBE target feature.

compiler/rustc_feature/src/unstable.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -519,9 +519,6 @@ declare_features! (
519519
(unstable, macro_metavar_expr_concat, "1.81.0", Some(124225)),
520520
/// Allows `#[marker]` on certain traits allowing overlapping implementations.
521521
(unstable, marker_trait_attr, "1.30.0", Some(29864)),
522-
/// Allows exhaustive pattern matching on types that contain uninhabited types in cases that are
523-
/// unambiguously sound.
524-
(unstable, min_exhaustive_patterns, "1.77.0", Some(119612)),
525522
/// A minimal, sound subset of specialization intended to be used by the
526523
/// standard library until the soundness issues with specialization
527524
/// are fixed.

compiler/rustc_middle/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#![allow(rustc::diagnostic_outside_of_impl)]
2929
#![allow(rustc::potential_query_instability)]
3030
#![allow(rustc::untranslatable_diagnostic)]
31+
#![cfg_attr(bootstrap, feature(min_exhaustive_patterns))]
3132
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
3233
#![doc(rust_logo)]
3334
#![feature(allocator_api)]
@@ -48,7 +49,6 @@
4849
#![feature(iter_from_coroutine)]
4950
#![feature(let_chains)]
5051
#![feature(macro_metavar_expr)]
51-
#![feature(min_exhaustive_patterns)]
5252
#![feature(min_specialization)]
5353
#![feature(negative_impls)]
5454
#![feature(never_type)]

compiler/rustc_mir_build/src/build/matches/match_pair.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -208,14 +208,11 @@ impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> {
208208
subpairs = cx.field_match_pairs(downcast_place, subpatterns);
209209

210210
let irrefutable = adt_def.variants().iter_enumerated().all(|(i, v)| {
211-
i == variant_index || {
212-
(cx.tcx.features().exhaustive_patterns
213-
|| cx.tcx.features().min_exhaustive_patterns)
214-
&& !v
215-
.inhabited_predicate(cx.tcx, adt_def)
216-
.instantiate(cx.tcx, args)
217-
.apply_ignore_module(cx.tcx, cx.param_env)
218-
}
211+
i == variant_index
212+
|| !v
213+
.inhabited_predicate(cx.tcx, adt_def)
214+
.instantiate(cx.tcx, args)
215+
.apply_ignore_module(cx.tcx, cx.param_env)
219216
}) && (adt_def.did().is_local()
220217
|| !adt_def.is_variant_list_non_exhaustive());
221218
if irrefutable {

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -695,9 +695,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
695695

696696
// Emit an extra note if the first uncovered witness would be uninhabited
697697
// if we disregard visibility.
698-
let witness_1_is_privately_uninhabited = if (self.tcx.features().exhaustive_patterns
699-
|| self.tcx.features().min_exhaustive_patterns)
700-
&& let Some(witness_1) = witnesses.get(0)
698+
let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
701699
&& let ty::Adt(adt, args) = witness_1.ty().kind()
702700
&& adt.is_enum()
703701
&& let Constructor::Variant(variant_index) = witness_1.ctor()
@@ -1059,7 +1057,7 @@ fn report_non_exhaustive_match<'p, 'tcx>(
10591057
err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
10601058
} else if cx.is_foreign_non_exhaustive_enum(ty) {
10611059
err.note(format!("`{ty}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively"));
1062-
} else if cx.is_uninhabited(ty.inner()) && cx.tcx.features().min_exhaustive_patterns {
1060+
} else if cx.is_uninhabited(ty.inner()) {
10631061
// The type is uninhabited yet there is a witness: we must be in the `MaybeInvalid`
10641062
// case.
10651063
err.note(format!("`{ty}` is uninhabited but is not being matched by value, so a wildcard `_` is required"));

compiler/rustc_pattern_analysis/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ pub trait PatCx: Sized + fmt::Debug {
5454
type PatData: Clone;
5555

5656
fn is_exhaustive_patterns_feature_on(&self) -> bool;
57-
fn is_min_exhaustive_patterns_feature_on(&self) -> bool;
5857

5958
/// The number of fields for this constructor.
6059
fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;

compiler/rustc_pattern_analysis/src/rustc.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> {
237237
let tys = cx.variant_sub_tys(ty, variant).map(|(field, ty)| {
238238
let is_visible =
239239
adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
240-
let is_uninhabited = (cx.tcx.features().exhaustive_patterns
241-
|| cx.tcx.features().min_exhaustive_patterns)
242-
&& cx.is_uninhabited(*ty);
240+
let is_uninhabited = cx.is_uninhabited(*ty);
243241
let skip = is_uninhabited && (!is_visible || is_non_exhaustive);
244242
(ty, PrivateUninhabitedField(skip))
245243
});
@@ -925,9 +923,6 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> {
925923
fn is_exhaustive_patterns_feature_on(&self) -> bool {
926924
self.tcx.features().exhaustive_patterns
927925
}
928-
fn is_min_exhaustive_patterns_feature_on(&self) -> bool {
929-
self.tcx.features().min_exhaustive_patterns
930-
}
931926

932927
fn ctor_arity(&self, ctor: &crate::constructor::Constructor<Self>, ty: &Self::Ty) -> usize {
933928
self.ctor_arity(ctor, *ty)

0 commit comments

Comments
 (0)