Skip to content

Confusing error message on negative enum-discriminants #97319

Closed
@Bryysen

Description

@Bryysen

Given the following code:

Playground

#[repr(i8)]
enum DisEnum {
    First = -1,
    Second = -2,
    Third = -3,
    Last,
}

The current output is:

error[E0081]: discriminant value `254` already exists
 --> src/lib.rs:8:5
  |
6 |     Second = -2,
  |              -- first use of `254`
7 |     Third = -3,
8 |     Last,
  |     ^^^^ enum already has `254`

For more information about this error, try `rustc --explain E0081`.
error: could not compile `playground` due to previous error
<rustc output>

Ideally the output should look like:

error[E0081]: discriminant value `254` already exists
 --> src/lib.rs:8:5
  |
6 |     Second = -2,
  |              -- first use of `-2`
7 |     Third = -3,
8 |     Last,
  |     ^^^^ enum already has `-2`

For more information about this error, try `rustc --explain E0081`.
error: could not compile `playground` due to previous error
<proposed output>

I don't have any understanding of the internal machinery of the diagnostics, but it seems that the value is being cast to the unsigned variant of the integer before displayed (in this case i8 -> u8). Of course, the discriminant does its job just fine, and explicitly casting DisEnum to an i8 also works as expected, only the diagnostics are a bit unfortunate.

Changing #[repr(i8)] to #[repr(isize)] in the example causes it to underflow close to usize::MAX which may seem a little intimidating to a newer user who accidentally stumbles on this 😄

The output is the same on both Stable and Nightly

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.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