Rust-clippy: False positive in unnecessary_cast with hex literals

Created on 24 Feb 2020  路  5Comments  路  Source: rust-lang/rust-clippy


clippy 0.0.212 (69f99e7 2019-12-14)

The lint for #[warn(unnecessary_cast)] acts strangely when integers are written in hex. Example:

let r = 0x1b as f32 / 255.0;
//      ^^^^^^^^^^^ - unnecessary cast write integer literal as 29_f32

However, f32 is valid hex, so if I write 0x1b_f32 rust interprets the value as an integer. It _does_ helpfully output the integer literal as a decimal number in the suggestion, but it isn't hex anymore which defeats the purpose.

L-bug good-first-issue

All 5 comments

I would like to work on this issue and investigated a bit. Unfortunately, the AST doesn't seem to record whether the integer literal was written in hex or decimal notation. The enum LitIntType only records the suffix of the literal.

It seems to me that properly resolving these false positives would require extending the LitKind::Int node with additional information in the main rust repository. Am I missing something?

@mlegner that's unfortunate, I'm not really aware of those implementation details but from a glance it seems your summation of the problem is accurate.

Clippy has it's own struct, that can be build from literals and from where you can detect if it is a hex, bin, or oct literal:

https://github.com/rust-lang/rust-clippy/blob/0f4a3fecccd55c0e5b4d50ce59ed660ac8e67dcc/clippy_lints/src/literal_representation.rs#L132-L150

So no need to modify the rustc AST.

Thanks a lot for the pointer, @flip1995. I was able to resolve this issue but had to modify some of the code you referenced. The changes are in the linked PR #5257.

Thanks for addressing this so quickly!

Was this page helpful?
0 / 5 - 0 ratings