rust-lang / rust-lang/rust-clippy

Should repr(C) enums be linted?

Open
#3,229 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint S-needs-discussion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

The domain of applicability of #[repr(C)] enums is much smaller than people new to FFI think, and much existing usage of it is erronerous. Two common C enum idioms which are not supported by Rust enums come to bite people particularly often:

  • In C, receiving an unknown enum variant from a more recent version of an enum-based library is mostly legal, it will only test the quality of the "default:" clause of your switch statement. In Rust, that's undefined behavior.
  • In C, people often (mis-)use enum's implicit conversion to integer as a more portable alternative to bitfields or as a way to count the amount of enum variants. In Rust, randomly BitOr-ing enum variants or subtracting things from them doesn't make sense.

From this perspective, I would join other people who consider repr(C) enums as an FFI footgun, and suggest linting people towards using integer newtypes and constants instead.

That's not always the right thing to do, there are some cases where the set of enum variants in a C API is known to be closed to further modification forever and where enums are only used as enumerated cases, which is why a lint that can be silenced instead of a hard error is most appropriate.

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 by reading the Rust Reference link on undefined behavior and the linked rust-memory-model discussion, then assess the proposed risks of repr(C) enums in this Clippy issue. Done means agreeing on the lint's scope, handling the stated exceptions, and defining how users can silence it; no implementation files or tests are named.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.