rust-lang / rust-lang/rust-clippy
Unnecessary_cast wrongly triggers on primitive methods of i32
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
I tried to see if this bug existed on all the integer number types, and while I haven't exhaustively tested every primitive method, count_ones(), as I used in my example, is correctly handled on:
i8 , u8,
i16 , u16
__ , u32
i64 , u64
i128 , u128
It seems to me that this only fails when i is i32
Other methods that fail with i32 are: (count_zeros(), ilog2(), trailing_ones(), trailing_zeroes()...) <- not exhaustive
Lint Name
unnecessary_cast
Reproducer
I tried this code:
fn main() {
for i in 1..(1 << 4) {
println!("{}", (i as i32).count_ones() << 2 );
}
}
I saw this happen:
warning: casting to the same type is unnecessary (`i32` -> `i32`)
--> src/main.rs:3:24
|
3 | println!("{}", (i as i32).count_ones() << 2 );
| ^^^^^^^^^^ help: try: `i`
|
= 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:
no warning, allowing clippy to go through with its suggestion for i32 would result in a compiler error
Version
rustc 1.71.1 (eb26296b5 2023-08-03)
binary: rustc
commit-hash: eb26296b556cef10fb713a38f3d16b9886080f26
commit-date: 2023-08-03
host: aarch64-apple-darwin
release: 1.71.1
LLVM version: 16.0.5
Additional Labels
@rustbot label +I-suggestion-causes-error
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 reproducing the unnecessary_cast warning with the provided Rust example, then trace the lint's handling of primitive methods on i32, especially count_ones(), count_zeros(), ilog2(), and the trailing-bit methods. Done means the lint no longer suggests removing a cast when that suggestion causes a compiler error, while the reported behavior for the other integer types remains correct.
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
- 35/100