rust-lang / rust-lang/rust-clippy

Unnecessary_cast wrongly triggers on primitive methods of i32

Open
#11,298 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.