New lint cast_enum_truncation

This commit is contained in:
Jason Newcomb 2022-01-31 21:22:47 -05:00
parent 8a466454ab
commit 90bb7a3476
10 changed files with 183 additions and 52 deletions

View file

@ -139,7 +139,9 @@ fn main() {
impl E2 {
fn test(self) {
let _ = self as u8;
let _ = Self::B as u8;
let _ = self as i16; // Don't lint. `255..=256` fits in i16
let _ = Self::A as u8; // Don't lint.
}
}
@ -174,7 +176,9 @@ fn main() {
impl E5 {
fn test(self) {
let _ = self as i8;
let _ = Self::A as i8;
let _ = self as i16; // Don't lint. `-129..=127` fits in i16
let _ = Self::B as u8; // Don't lint.
}
}
@ -189,6 +193,7 @@ fn main() {
let _ = self as i16;
let _ = Self::A as u16; // Don't lint. `2^16-1` fits in u16
let _ = self as u32; // Don't lint. `2^16-1..=2^16` fits in u32
let _ = Self::A as u16; // Don't lint.
}
}
@ -201,6 +206,7 @@ fn main() {
impl E7 {
fn test(self) {
let _ = self as usize;
let _ = Self::A as usize; // Don't lint.
let _ = self as u64; // Don't lint. `2^32-1..=2^32` fits in u64
}
}
@ -227,7 +233,22 @@ fn main() {
}
impl E9 {
fn test(self) {
let _ = Self::A as u8; // Don't lint.
let _ = self as u128; // Don't lint. `0..=2^128-1` fits in u128
}
}
#[derive(Clone, Copy)]
#[repr(usize)]
enum E10 {
A,
B = u32::MAX as usize,
}
impl E10 {
fn test(self) {
let _ = self as u16;
let _ = Self::B as u32; // Don't lint.
let _ = self as u64; // Don't lint.
}
}
}

View file

@ -156,23 +156,43 @@ error: casting `main::E2` to `u8` may truncate the value
LL | let _ = self as u8;
| ^^^^^^^^^^
error: casting `main::E2::B` to `u8` will truncate the value
--> $DIR/cast.rs:142:21
|
LL | let _ = Self::B as u8;
| ^^^^^^^^^^^^^
|
= note: `-D clippy::cast-enum-truncation` implied by `-D warnings`
error: casting `main::E5` to `i8` may truncate the value
--> $DIR/cast.rs:176:21
--> $DIR/cast.rs:178:21
|
LL | let _ = self as i8;
| ^^^^^^^^^^
error: casting `main::E5::A` to `i8` will truncate the value
--> $DIR/cast.rs:179:21
|
LL | let _ = Self::A as i8;
| ^^^^^^^^^^^^^
error: casting `main::E6` to `i16` may truncate the value
--> $DIR/cast.rs:189:21
--> $DIR/cast.rs:193:21
|
LL | let _ = self as i16;
| ^^^^^^^^^^^
error: casting `main::E7` to `usize` may truncate the value on targets with 32-bit wide pointers
--> $DIR/cast.rs:203:21
--> $DIR/cast.rs:208:21
|
LL | let _ = self as usize;
| ^^^^^^^^^^^^^
error: aborting due to 28 previous errors
error: casting `main::E10` to `u16` may truncate the value
--> $DIR/cast.rs:249:21
|
LL | let _ = self as u16;
| ^^^^^^^^^^^
error: aborting due to 31 previous errors