rust-lang / rust-lang/rust-clippy
Suggest `cast_const()` for `*mut` to `*const` coercions (similar to `ptr_cast_constness`)
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
ptr_cast_constness warns about as casts, suggesting cast_const() in e.g.
let p = core::ptr::null_mut();
let p: *const i32 = p as _;
However, if one relies on coercion, it does not warn:
let p = core::ptr::null_mut();
let p: *const i32 = p;
This is fine for ptr_cast_constness -- after all, the documentation mentions it checks for as.
Does it make sense to have a lint that suggests cast_const() in the second example too?
Personally, I don't know if avoiding the coercion is a good idea to begin with, but given the existence of cast_const() and the following sentence in its docs, I decided to open this:
may have documentation value if used instead of implicit coercion.
The lint would need to be opt-in.
Advantage
Like the cast_const() docs mention, it "may have documentation value if used instead of implicit coercion".
It could be useful for projects that wish to be written in a more explicit (and symmetric) style around raw pointers.
Drawbacks
Ergonomics can be worse in some cases, e.g. see the type annotation needed in the example below.
Example
let p = core::ptr::null_mut();
let p: *const i32 = p;
Could be written as:
let p: *mut i32 = core::ptr::null_mut();
let p: *const i32 = p.cast_const();
Note that : *mut i32 was added in the first line as well.
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 existing ptr_cast_constness lint and the cast_const() documentation referenced in the issue. Determine whether an opt-in lint for implicit *mut to *const coercions fits Clippy's lint design, and define its expected behavior and coverage before implementation.
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
- 35/100