Skip to content

Discriminant enums: negative and >i32::MAX discriminants become the variant index or truncate (as-cast and match) #1451

Closed

Description

@ehartford

Spec: §4.4a Discriminant Enums ("an integer type (i8, i16, i32, i64, u8, u16, u32, u64) that determines the underlying storage. Each variant is assigned an explicit integer value with = N"; "value as i32 extracts the underlying integer (identity cast)").

An in-range discriminant that is negative, or above i32::MAX, silently becomes a different value:

enum K: u32:
    A = 1
    B = 2
    C = 3000000000

enum L: i64:
    A = 1
    B = 5000000000

enum M: i8:
    A = 1
    B = -3

fn main:
    print(K.C as i64)
    print(L.B as i64)
    print(M.B as i32)

Prints 2, 705032704, 1; expected 3000000000, 5000000000, -3. K.C and M.B read as their variant index (2 and 1); L.B is truncated to 32 bits. A match on such a value picks the arm of the variant whose index or truncation it collides with (a u32 enum with Blue = 2, Hi = 3000000000 matches Hi as Blue, and k == Kind.Hi is true for Blue).

Next layer once values are right: MIR switch tables are Vec[i32] (MirBody.switch_table_vals, MirLower.enum_variant_discriminant_for_type), so a 64-bit discriminant outside the i32 range cannot be a switch case at all.

Distinct from #1003 (values outside the repr range are accepted) and #1444 (sub-i32 repr match; the discriminant temp is always i32).

Found while exhausting the #1444 matrix (installed nightly-20260922-local-1-8c859a7d0559; a stage2 of origin/main 1c76062).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions