rust-lang / rust-lang/rust

`#[non_exhaustive]` stucts can be matched exhaustively using constants as patterns

Open
#119,264 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-patterns C-bug F-non_exhaustive T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

In https://github.com/rust-lang/rfcs/pull/3535#discussion_r1429134787 it was noticed that it is possible to match a #[non_exhaustive] struct exhaustively outside the originating crate,
if constants for all posible states are accessible or definable in the other crate.

As a result adding fields such that the struct has new states is a breaking change, as the existing constants won't be able to cover all states anymore.
Which makes #[non_exhaustive] ineffective.

For Example:

// bar/src/lib.rs
#[non_exhaustive]
#[derive(PartialEq, Eq)]
pub struct Bar(bool);
pub const TRUE: Bar = Bar(true);
pub const FALSE: Bar = Bar(false);
// foo/src/main.rs
fn main() {
    match bar::TRUE {
        bar::TRUE => {}
        bar::FALSE => {}
    }
}

Changing the bar crate to the following is then a breaking change:

// bar/src/lib.rs
#[non_exhaustive]
#[derive(PartialEq, Eq)]
pub struct Bar(bool, bool);
pub const TRUE: Bar = Bar(true, true);
pub const FALSE: Bar = Bar(false, false);

This breaks the foo crate, eventhough Bar was marked #[non_exhaustive] to allow expanding.

Reproduction Repo

Meta
rustc +stable --version
rustc 1.74.1 (a28077b28 2023-12-04)
rustc +beta --version
rustc 1.76.0-beta.1 (0e09125c6 2023-12-21)
rustc +nightly --version
rustc 1.77.0-nightly (d6d7a9386 2023-12-22)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked reproduction repository and compare the matching behavior using the stable, beta, and nightly rustc versions listed in the issue. Read the linked RFC discussion about #[non_exhaustive] and determine how matching through accessible constants interacts with the intended semver guarantee; a complete result should establish the expected language behavior and its compiler impact.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.