Rollup merge of #140431 - bend-n:dont_handle_bool_transmute, r=Nadrieril

dont handle bool transmute

removes `transmute(u8) -> bool` suggestion due to ambiguity, leave it for clippy

elaboration on ambiguity in question:
`transmute::<u8, bool>(x)` will codegen to an `assume(u8 < 2)`;
`_ == 1` or `_ != 0` or `_ % 2 == 0` would remove that assumption
`match _ { x @ (0 | 1) => x == 1, _ => std::hint::unreachable_unchecked() }` is very verbose

`@rustbot` label L-unnecessary_transmutes
This commit is contained in:
Matthias Krüger 2025-05-22 07:19:01 +02:00 committed by GitHub
commit cc87ae85dd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 7 additions and 14 deletions

View file

@ -9,6 +9,7 @@ use crate::errors::UnnecessaryTransmute as Error;
/// Check for transmutes that overlap with stdlib methods.
/// For example, transmuting `[u8; 4]` to `u32`.
/// We chose not to lint u8 -> bool transmutes, see #140431
pub(super) struct CheckUnnecessaryTransmutes;
impl<'tcx> crate::MirLint<'tcx> for CheckUnnecessaryTransmutes {
@ -98,8 +99,6 @@ impl<'a, 'tcx> UnnecessaryTransmuteChecker<'a, 'tcx> {
(Uint(_), Float(ty)) => err(format!("{}::from_bits({arg})", ty.name_str())),
// bool → { x8 }
(Bool, Int(..) | Uint(..)) => err(format!("({arg}) as {}", fn_sig.output())),
// u8 → bool
(Uint(_), Bool) => err(format!("({arg} == 1)")),
_ => return None,
})
}

View file

@ -81,13 +81,13 @@ fn main() {
let y: i64 = f64::to_bits(1f64).cast_signed();
//~^ ERROR
let z: bool = (1u8 == 1);
//~^ ERROR
let z: bool = transmute(1u8);
// clippy
let z: u8 = (z) as u8;
//~^ ERROR
let z: bool = transmute(1i8);
// no error!
// clippy
let z: i8 = (z) as i8;
//~^ ERROR
}

View file

@ -82,12 +82,12 @@ fn main() {
//~^ ERROR
let z: bool = transmute(1u8);
//~^ ERROR
// clippy
let z: u8 = transmute(z);
//~^ ERROR
let z: bool = transmute(1i8);
// no error!
// clippy
let z: i8 = transmute(z);
//~^ ERROR
}

View file

@ -239,12 +239,6 @@ error: unnecessary transmute
LL | let y: i64 = transmute(1f64);
| ^^^^^^^^^^^^^^^ help: replace this with: `f64::to_bits(1f64).cast_signed()`
error: unnecessary transmute
--> $DIR/unnecessary-transmutation.rs:84:23
|
LL | let z: bool = transmute(1u8);
| ^^^^^^^^^^^^^^ help: replace this with: `(1u8 == 1)`
error: unnecessary transmute
--> $DIR/unnecessary-transmutation.rs:86:21
|
@ -257,5 +251,5 @@ error: unnecessary transmute
LL | let z: i8 = transmute(z);
| ^^^^^^^^^^^^ help: replace this with: `(z) as i8`
error: aborting due to 36 previous errors
error: aborting due to 35 previous errors