rust-lang / rust-lang/rust-clippy
unnecessary_cast false positive when casting pointers to types with lifetime parameters
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
unnecessary-lint suggests x as *const T instead of x as *const T as *const S where both casts are actually needed, otherwise the code doesn't compile.
Lint Name
unnecessary-cast
Reproducer
I tried this code:
pub struct Foo<'a>(pub &'a [u8]);
/// # Safety
pub unsafe fn foo<'a, 'b>(x: &'a Foo<'a>) -> &'b Foo<'b> {
unsafe { &*(x as *const Foo<'a> as *const Foo<'b>) }
}
I saw this happen:
warning: casting raw pointers to the same type and constness is unnecessary (`*const Foo<'_>` -> `*const Foo<'_>`)
--> src/lib.rs:5:16
|
5 | unsafe { &*(x as *const Foo<'a> as *const Foo<'b>) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x as *const Foo<'a>`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
= note: `#[warn(clippy::unnecessary_cast)]` on by default
I expected to see this happen: compiles without warning
Version
rustc 1.80.0-nightly (7d83a4c13 2024-05-06)
binary: rustc
commit-hash: 7d83a4c131ab9ae81a74c6fd825c827d74a2881d
commit-date: 2024-05-06
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.4
Additional Labels
No response
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 locating the unnecessary-cast lint implementation in rust-clippy and inspect how it compares raw pointer types with lifetime parameters. Use the reproducer in src/lib.rs as the regression case, then verify that the necessary cast is no longer warned about while genuinely redundant casts still are.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100