Skip to content

unnecessary_cast can silently change behavior of numeric code #11882

@Jules-Bertholet

Description

@Jules-Bertholet

Summary

The unnecessary_cast lint, which is marked machine-applicable, can give suggestions that make code no longer compile—or even worse, silently change its behavior.

Reproducer

I tried this code:

fn main() { let k: u64 = (!0 as u64).overflowing_shr(1_u32).0; println!("{k}"); }

I expected to see this happen: Suggest replacing (!0 as u64) with (!0_u64).

Instead, this happened:

warning: casting to the same type is unnecessary (`u64` -> `u64`) --> src/main.rs:2:18 | 2 | let k: u64 = (!0 as u64).overflowing_shr(1_u32).0; | ^^^^^^^^^^^ help: try: `!0` | = 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 

Applying the machine-applicable suggestion results in:

fn main() { let k: u64 = !0.overflowing_shr(1_u32).0; println!("{k}"); }
error[E0689]: can't call method `overflowing_shr` on ambiguous numeric type `{integer}` --> src/main.rs:2:21 | 2 | let k: u64 = !0.overflowing_shr(1_u32).0; | ^^^^^^^^^^^^^^^ | help: you must specify a concrete type for this numeric value, like `i32` | 2 | let k: u64 = !0_i32.overflowing_shr(1_u32).0; | ~~~~~

I tried this code:

fn main() { let k: u64 = (!0_u64 as u64).overflowing_shr(1_u32).0; println!("{k}"); }

I expected to see this happen: Suggest replacing (!0_u64 as u64) with (!0_u64).

Instead, this happened:

warning: casting to the same type is unnecessary (`u64` -> `u64`) --> src/main.rs:2:18 | 2 | let k: u64 = (!0_u64 as u64).overflowing_shr(1_u32).0; | ^^^^^^^^^^^^^^^ help: try: `!0_u64` | = 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 

Applying the machine-applicable suggestion results in:

fn main() { let k: u64 = !0_u64.overflowing_shr(1_u32).0; println!("{k}"); }

Which compiles without warning, but prints a different value than the original, because ! has lower precedence than ..

Version

0.1.76 (2023-11-26 6cf0888) 

Additional Labels

@rustbot label I-suggestion-causes-error

Metadata

Metadata

Labels

C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions