Skip to content

"Binding is possibly uninitalized" reports some additional spans incorrectly in addition to the correct one #126133

Open

Description

Code

enum E {
    A,
    B,
    C,
}

fn foo(e: E) {
    let bar;
    match e {
        E::A => return,

        E::B => {}

        E::C => {
            bar = 5;
        }
    }

    let _baz = bar;
}

Current output

error[E0381]: used binding `bar` is possibly-uninitialized
  --> src/lib.rs:19:16
   |
8  |     let bar;
   |         --- binding declared here but left uninitialized
9  |     match e {
10 |         E::A => return,
   |         ---- if this pattern is matched, `bar` is not initialized
11 |
12 |         E::B => {}
   |         ---- if this pattern is matched, `bar` is not initialized
...
19 |     let _baz = bar;
   |                ^^^ `bar` used here but it is possibly-uninitialized

For more information about this error, try `rustc --explain E0381`.

Desired output

error[E0381]: used binding `bar` is possibly-uninitialized
  --> src/lib.rs:19:16
   |
8  |     let bar;
   |         --- binding declared here but left uninitialized
9  |     match e {
10 |         E::A => return,
11 |
12 |         E::B => {}
   |         ---- if this pattern is matched, `bar` is not initialized
...
19 |     let _baz = bar;
   |                ^^^ `bar` used here but it is possibly-uninitialized

For more information about this error, try `rustc --explain E0381`.

Rationale and extra context

Yes bar is not initialized in the E::A arm, but the goal of the diagnostic should be to print the spans that the user needs to *fix*. The E::A arm diverges so the user only needs to fix the E::B arm. So the report for E::B is correct, but the one for E::A should not be emitted.

Other cases

My original code that triggered this was similar to wrapping the whole body of foo in a loop {} and using break instead of return. The rationale is the same.

Rust Version

rustc 1.80.0-nightly (a330e4959 2024-06-04)
binary: rustc
commit-hash: a330e49593ee890f9197727a3a558b6e6b37f843
commit-date: 2024-06-04
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.6

Anything else?

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

A-control-flowArea: Control flowA-diagnosticsArea: Messages for errors, warnings, and lintsD-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions