rust-lang / rust-lang/rust

repr(C) on an enum accepts discriminants that do not fit into the default C enum size (repr_c_enums_larger_than_int lint)

Open
#124,403 29 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-enum A-FFI A-repr C-tracking-issue O-windows O-windows-msvc
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Example:

#[repr(C)]
enum OverflowingEnum {
    A = 1111111111111111111,
}
enum overflowing_enum {
    OVERFLOWING_ENUM_A = 1111111111111111111,
};

Rust currently gives size_of::<OverflowingEnum>() = 8. MSVC gives sizeof(enum overflowing_enum) = 4. Additionally, Rust gives OverflowingEnum::A as usize = 1111111111111111111 and MSVC gives OVERFLOWING_ENUM_A = 734294471. (Godbolt)

This should probably be a hard error (forward compatibility lint). The nomicon currently states

repr(C) is equivalent to one of repr(u*) (see the next section) for fieldless enums. The chosen size is the default enum size for the target platform's C application binary interface (ABI).

and the reference currently states

For field-less enums, the C representation has the size and alignment of the default enum size and alignment for the target platform's C ABI.

The nomicon is clearly wrong here: #[repr(c_int)] on the enum would fail to compile (where c_int is the correct primitive) (because of the overflowing literal). I think erroring (forward compatibility linting) and pointing the user to use #[repr(u64)] in this case makes sense.

(Summary by @CAD97)

@CAD97 this should error on all targets, not just MSVC, I assume? What do non-MSVC C compilers do with such an enum?

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

Read the Nomicon and Reference passages on fieldless repr(C) enums, then inspect the repr_c_enums_larger_than_int lint and the enum representation checks. Determine the intended cross-target diagnostic for discriminants exceeding the C enum size, and verify that valid repr(u64) guidance and the relevant compiler tests reflect the decision.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.