rust-lang / rust-lang/rust-clippy
New lint that suggests using `addr_of!` instead of `&x as *const _`
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
There's quite a bit of Rust code out there that does the following pattern
let ptr = &x as *const T;
It would seem useful to have a lint that suggests using addr_of! (and addr_of_mut! for the mutable case) instead.
It should cover the simple case above as well as more complex cases like &(*some_ptr).x as *const T, &x.y as *const T, &x.y (implicit conversion from reference to pointer).
There's also a slightly more convoluted case that would be useful to cover: &(x.y as *const T) as *const U (x.y is a pointer or reference). In this case it should suggest to also get rid of the inner cast. The inner cast plus & here will cause a reference to the local stack frame to be created, which is likely unwanted and likely going to cause unsoundness later on.
That more convoluted case is actually something I had to debug a while ago and it was not easy to spot, and only caused problems in debug builds for extra fun.
Advantage
The main advantage here is that it creates the pointer without creating a temporary reference first (see addr_of! docs). The second more convoluted case would also avoid potential unsoundness.
Drawbacks
The only possible drawback I can think of is false positives, but the risk seems quite low here.
Example
let ptr = &x as *const T;
let ptr2 = &(ptr as *const U) as *const V;
Could be written as:
let ptr = addr_of!(x);
let ptr2 = addr_of!(ptr) as *const V;
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 addr_of! documentation and reviewing rust-clippy's existing lint patterns; no implementation files or tests are named in the issue. Done should cover the simple and nested reference-to-pointer cases described, including mutable references, while avoiding temporary references and producing the proposed suggestions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100