rust-lang / rust-lang/rust-clippy
Should repr(C) enums be linted?
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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