Skip to content

Commit 0e970e6

Browse files
committed
Suggest {to,from}_ne_bytes for transmutations between arrays and integers, etc
1 parent c4b38a5 commit 0e970e6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+673
-86
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4127,6 +4127,7 @@ dependencies = [
41274127
"rustc_span",
41284128
"rustc_target",
41294129
"rustc_trait_selection",
4130+
"rustc_type_ir",
41304131
"smallvec",
41314132
"tracing",
41324133
]

compiler/rustc_codegen_cranelift/example/example.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#![feature(no_core, unboxed_closures)]
22
#![no_core]
3-
#![allow(dead_code)]
3+
#![allow(dead_code, unnecessary_transmutation)]
44

55
extern crate mini_core;
66

compiler/rustc_codegen_gcc/example/example.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#![feature(no_core, unboxed_closures)]
22
#![no_core]
3-
#![allow(dead_code)]
3+
#![allow(dead_code, unnecessary_transmutation)]
44

55
extern crate mini_core;
66

compiler/rustc_lint_defs/src/builtin.rs

+25
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ declare_lint_pass! {
8383
PUB_USE_OF_PRIVATE_EXTERN_CRATE,
8484
REDUNDANT_IMPORTS,
8585
REDUNDANT_LIFETIMES,
86+
UNNECESSARY_TRANSMUTATION,
8687
REFINING_IMPL_TRAIT_INTERNAL,
8788
REFINING_IMPL_TRAIT_REACHABLE,
8889
RENAMED_AND_REMOVED_LINTS,
@@ -4943,6 +4944,30 @@ declare_lint! {
49434944
"detects pointer to integer transmutes in const functions and associated constants",
49444945
}
49454946

4947+
declare_lint! {
4948+
/// The `unnecessary_transmutation` lint detects transmutations that have safer alternatives.
4949+
///
4950+
/// ### Example
4951+
///
4952+
/// ```rust
4953+
/// fn bytes_at_home(x: [u8; 4]) -> u32 {
4954+
/// unsafe { std::mem::transmute(x) }
4955+
/// }
4956+
/// ```
4957+
///
4958+
/// {{produces}}
4959+
///
4960+
/// ### Explanation
4961+
///
4962+
/// Using an explicit method is preferable over calls to
4963+
/// [`transmute`](https://doc.rust-lang.org/std/mem/fn.transmute.html) as
4964+
/// they more clearly communicate the intent, are easier to review, and
4965+
/// are less likely to accidentally result in unsoundness.
4966+
pub UNNECESSARY_TRANSMUTATION,
4967+
Warn,
4968+
"detects transmutes that are shadowed by std methods"
4969+
}
4970+
49464971
declare_lint! {
49474972
/// The `tail_expr_drop_order` lint looks for those values generated at the tail expression location,
49484973
/// that runs a custom `Drop` destructor.

compiler/rustc_mir_transform/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ rustc_session = { path = "../rustc_session" }
2626
rustc_span = { path = "../rustc_span" }
2727
rustc_target = { path = "../rustc_target" }
2828
rustc_trait_selection = { path = "../rustc_trait_selection" }
29+
rustc_type_ir = { version = "0.0.0", path = "../rustc_type_ir" }
2930
smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
3031
tracing = "0.1"
3132
# tidy-alphabetical-end

compiler/rustc_mir_transform/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ mir_transform_must_not_suspend = {$pre}`{$def_path}`{$post} held across a suspen
4242
.help = consider using a block (`{"{ ... }"}`) to shrink the value's scope, ending before the suspend point
4343
mir_transform_operation_will_panic = this operation will panic at runtime
4444
45+
mir_transform_unnecessary_transmute = unnecessary transmute
46+
4547
mir_transform_tail_expr_drop_order = relative drop order changing in Rust 2024
4648
.temporaries = in Rust 2024, this temporary value will be dropped first
4749
.observers = in Rust 2024, this local variable or temporary value will be dropped second
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
use rustc_middle::mir::visit::Visitor;
2+
use rustc_middle::mir::{Body, Location, Operand, Terminator, TerminatorKind};
3+
use rustc_middle::ty::{TyCtxt, UintTy};
4+
use rustc_session::lint::builtin::UNNECESSARY_TRANSMUTATION;
5+
use rustc_span::source_map::Spanned;
6+
use rustc_span::{Span, sym};
7+
use rustc_type_ir::TyKind::*;
8+
9+
use crate::errors::UnnecessaryTransmute as Error;
10+
11+
/// Check for transmutes that overlap with stdlib methods.
12+
/// For example, transmuting `[u8; 4]` to `u32`.
13+
pub(super) struct CheckUnnecessaryTransmutes;
14+
15+
impl<'tcx> crate::MirLint<'tcx> for CheckUnnecessaryTransmutes {
16+
fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
17+
let mut checker = UnnecessaryTransmuteChecker { body, tcx };
18+
checker.visit_body(body);
19+
}
20+
}
21+
22+
struct UnnecessaryTransmuteChecker<'a, 'tcx> {
23+
body: &'a Body<'tcx>,
24+
tcx: TyCtxt<'tcx>,
25+
}
26+
27+
impl<'a, 'tcx> UnnecessaryTransmuteChecker<'a, 'tcx> {
28+
fn is_redundant_transmute(
29+
&self,
30+
function: &Operand<'tcx>,
31+
arg: String,
32+
span: Span,
33+
) -> Option<Error> {
34+
let fn_sig = function.ty(self.body, self.tcx).fn_sig(self.tcx).skip_binder();
35+
let [input] = fn_sig.inputs() else { return None };
36+
37+
let err = |sugg| Error { span, sugg, help: None };
38+
39+
Some(match (input.kind(), fn_sig.output().kind()) {
40+
// dont check the length; transmute does that for us.
41+
// [u8; _] => primitive
42+
(Array(t, _), Uint(_) | Float(_) | Int(_)) if *t.kind() == Uint(UintTy::U8) => Error {
43+
sugg: format!("{}::from_ne_bytes({arg})", fn_sig.output()),
44+
help: Some(
45+
"there's also `from_le_bytes` and `from_ne_bytes` if you expect a particular byte order",
46+
),
47+
span,
48+
},
49+
// primitive => [u8; _]
50+
(Uint(_) | Float(_) | Int(_), Array(t, _)) if *t.kind() == Uint(UintTy::U8) => Error {
51+
sugg: format!("{input}::to_ne_bytes({arg})"),
52+
help: Some(
53+
"there's also `to_le_bytes` and `to_ne_bytes` if you expect a particular byte order",
54+
),
55+
span,
56+
},
57+
// char → u32
58+
(Char, Uint(UintTy::U32)) => err(format!("u32::from({arg})")),
59+
// u32 → char
60+
(Uint(UintTy::U32), Char) => Error {
61+
sugg: format!("char::from_u32_unchecked({arg})"),
62+
help: Some("consider `char::from_u32(…).unwrap()`"),
63+
span,
64+
},
65+
// uNN → iNN
66+
(Uint(ty), Int(_)) => err(format!("{}::cast_signed({arg})", ty.name_str())),
67+
// iNN → uNN
68+
(Int(ty), Uint(_)) => err(format!("{}::cast_unsigned({arg})", ty.name_str())),
69+
// fNN → uNN
70+
(Float(ty), Uint(..)) => err(format!("{}::to_bits({arg})", ty.name_str())),
71+
// uNN → fNN
72+
(Uint(_), Float(ty)) => err(format!("{}::from_bits({arg})", ty.name_str())),
73+
// bool → { x8 }
74+
(Bool, Int(..) | Uint(..)) => err(format!("({arg}) as {}", fn_sig.output())),
75+
// u8 → bool
76+
(Uint(_), Bool) => err(format!("({arg} == 1)")),
77+
_ => return None,
78+
})
79+
}
80+
}
81+
82+
impl<'tcx> Visitor<'tcx> for UnnecessaryTransmuteChecker<'_, 'tcx> {
83+
// Check each block's terminator for calls to pointer to integer transmutes
84+
// in const functions or associated constants and emit a lint.
85+
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
86+
if let TerminatorKind::Call { func, args, .. } = &terminator.kind
87+
&& let [Spanned { span: arg, .. }] = **args
88+
&& let Some((func_def_id, _)) = func.const_fn_def()
89+
&& self.tcx.is_intrinsic(func_def_id, sym::transmute)
90+
&& let span = self.body.source_info(location).span
91+
&& let Some(lint) = self.is_redundant_transmute(
92+
func,
93+
self.tcx.sess.source_map().span_to_snippet(arg).expect("ok"),
94+
span,
95+
)
96+
&& let Some(call_id) = self.body.source.def_id().as_local()
97+
{
98+
let hir_id = self.tcx.local_def_id_to_hir_id(call_id);
99+
100+
self.tcx.emit_node_span_lint(UNNECESSARY_TRANSMUTATION, hir_id, span, lint);
101+
}
102+
}
103+
}

compiler/rustc_mir_transform/src/errors.rs

+20
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,26 @@ pub(crate) struct MustNotSuspendReason {
158158
pub reason: String,
159159
}
160160

161+
pub(crate) struct UnnecessaryTransmute {
162+
pub span: Span,
163+
pub sugg: String,
164+
pub help: Option<&'static str>,
165+
}
166+
167+
// Needed for def_path_str
168+
impl<'a> LintDiagnostic<'a, ()> for UnnecessaryTransmute {
169+
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::Diag<'a, ()>) {
170+
diag.primary_message(fluent::mir_transform_unnecessary_transmute);
171+
diag.span_suggestion(
172+
self.span,
173+
"replace this with",
174+
self.sugg,
175+
lint::Applicability::MachineApplicable,
176+
);
177+
self.help.map(|help| diag.help(help));
178+
}
179+
}
180+
161181
#[derive(LintDiagnostic)]
162182
#[diag(mir_transform_undefined_transmute)]
163183
#[note]

compiler/rustc_mir_transform/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ declare_passes! {
125125
mod check_null : CheckNull;
126126
mod check_packed_ref : CheckPackedRef;
127127
mod check_undefined_transmutes : CheckUndefinedTransmutes;
128+
mod check_unnecessary_transmutes: CheckUnnecessaryTransmutes;
128129
// This pass is public to allow external drivers to perform MIR cleanup
129130
pub mod cleanup_post_borrowck : CleanupPostBorrowck;
130131

@@ -391,6 +392,7 @@ fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
391392
&Lint(check_const_item_mutation::CheckConstItemMutation),
392393
&Lint(function_item_references::FunctionItemReferences),
393394
&Lint(check_undefined_transmutes::CheckUndefinedTransmutes),
395+
&Lint(check_unnecessary_transmutes::CheckUnnecessaryTransmutes),
394396
// What we need to do constant evaluation.
395397
&simplify::SimplifyCfg::Initial,
396398
&Lint(sanity_check::SanityCheck),

library/alloctests/tests/fmt.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#![deny(warnings)]
22
// FIXME(static_mut_refs): Do not allow `static_mut_refs` lint
33
#![allow(static_mut_refs)]
4+
#![cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
45

56
use std::cell::RefCell;
67
use std::fmt::{self, Write};

library/core/src/char/convert.rs

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ pub(super) const fn from_u32(i: u32) -> Option<char> {
2121
/// Converts a `u32` to a `char`, ignoring validity. See [`char::from_u32_unchecked`].
2222
#[inline]
2323
#[must_use]
24+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
2425
pub(super) const unsafe fn from_u32_unchecked(i: u32) -> char {
2526
// SAFETY: the caller must guarantee that `i` is a valid char value.
2627
unsafe {
@@ -221,6 +222,7 @@ impl FromStr for char {
221222
}
222223

223224
#[inline]
225+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
224226
const fn char_try_from_u32(i: u32) -> Result<char, CharTryFromError> {
225227
// This is an optimized version of the check
226228
// (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF),

library/core/src/intrinsics/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1498,6 +1498,7 @@ pub const fn forget<T: ?Sized>(_: T);
14981498
/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.:
14991499
///
15001500
/// ```
1501+
/// # #![cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
15011502
/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
15021503
///
15031504
/// let num = unsafe {

library/core/src/num/f128.rs

+2
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,7 @@ impl f128 {
898898
#[inline]
899899
#[unstable(feature = "f128", issue = "116909")]
900900
#[must_use = "this returns the result of the operation, without modifying the original"]
901+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
901902
pub const fn to_bits(self) -> u128 {
902903
// SAFETY: `u128` is a plain old datatype so we can always transmute to it.
903904
unsafe { mem::transmute(self) }
@@ -945,6 +946,7 @@ impl f128 {
945946
#[inline]
946947
#[must_use]
947948
#[unstable(feature = "f128", issue = "116909")]
949+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
948950
pub const fn from_bits(v: u128) -> Self {
949951
// It turns out the safety issues with sNaN were overblown! Hooray!
950952
// SAFETY: `u128` is a plain old datatype so we can always transmute from it.

library/core/src/num/f16.rs

+2
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,7 @@ impl f16 {
886886
#[inline]
887887
#[unstable(feature = "f16", issue = "116909")]
888888
#[must_use = "this returns the result of the operation, without modifying the original"]
889+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
889890
pub const fn to_bits(self) -> u16 {
890891
// SAFETY: `u16` is a plain old datatype so we can always transmute to it.
891892
unsafe { mem::transmute(self) }
@@ -932,6 +933,7 @@ impl f16 {
932933
#[inline]
933934
#[must_use]
934935
#[unstable(feature = "f16", issue = "116909")]
936+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
935937
pub const fn from_bits(v: u16) -> Self {
936938
// It turns out the safety issues with sNaN were overblown! Hooray!
937939
// SAFETY: `u16` is a plain old datatype so we can always transmute from it.

library/core/src/num/f32.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -705,8 +705,7 @@ impl f32 {
705705
pub const fn is_sign_negative(self) -> bool {
706706
// IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
707707
// applies to zeros and NaNs as well.
708-
// SAFETY: This is just transmuting to get the sign bit, it's fine.
709-
unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
708+
self.to_bits() & 0x8000_0000 != 0
710709
}
711710

712711
/// Returns the least number greater than `self`.
@@ -1090,6 +1089,7 @@ impl f32 {
10901089
#[stable(feature = "float_bits_conv", since = "1.20.0")]
10911090
#[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
10921091
#[inline]
1092+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
10931093
pub const fn to_bits(self) -> u32 {
10941094
// SAFETY: `u32` is a plain old datatype so we can always transmute to it.
10951095
unsafe { mem::transmute(self) }
@@ -1135,6 +1135,7 @@ impl f32 {
11351135
#[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
11361136
#[must_use]
11371137
#[inline]
1138+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
11381139
pub const fn from_bits(v: u32) -> Self {
11391140
// It turns out the safety issues with sNaN were overblown! Hooray!
11401141
// SAFETY: `u32` is a plain old datatype so we can always transmute from it.

library/core/src/num/f64.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -713,8 +713,7 @@ impl f64 {
713713
pub const fn is_sign_negative(self) -> bool {
714714
// IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
715715
// applies to zeros and NaNs as well.
716-
// SAFETY: This is just transmuting to get the sign bit, it's fine.
717-
unsafe { mem::transmute::<f64, u64>(self) & Self::SIGN_MASK != 0 }
716+
self.to_bits() & Self::SIGN_MASK != 0
718717
}
719718

720719
#[must_use]
@@ -1089,6 +1088,7 @@ impl f64 {
10891088
without modifying the original"]
10901089
#[stable(feature = "float_bits_conv", since = "1.20.0")]
10911090
#[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1091+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
10921092
#[inline]
10931093
pub const fn to_bits(self) -> u64 {
10941094
// SAFETY: `u64` is a plain old datatype so we can always transmute to it.
@@ -1135,6 +1135,7 @@ impl f64 {
11351135
#[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
11361136
#[must_use]
11371137
#[inline]
1138+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
11381139
pub const fn from_bits(v: u64) -> Self {
11391140
// It turns out the safety issues with sNaN were overblown! Hooray!
11401141
// SAFETY: `u64` is a plain old datatype so we can always transmute from it.

library/core/src/num/int_macros.rs

+2
Original file line numberDiff line numberDiff line change
@@ -3678,6 +3678,7 @@ macro_rules! int_impl {
36783678
/// ```
36793679
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
36803680
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3681+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
36813682
// SAFETY: const sound because integers are plain old datatypes so we can always
36823683
// transmute them to arrays of bytes
36833684
#[must_use = "this returns the result of the operation, \
@@ -3781,6 +3782,7 @@ macro_rules! int_impl {
37813782
/// ```
37823783
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
37833784
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3785+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
37843786
#[must_use]
37853787
// SAFETY: const sound because integers are plain old datatypes so we can always
37863788
// transmute to them

library/core/src/num/uint_macros.rs

+2
Original file line numberDiff line numberDiff line change
@@ -3523,6 +3523,7 @@ macro_rules! uint_impl {
35233523
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
35243524
#[must_use = "this returns the result of the operation, \
35253525
without modifying the original"]
3526+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
35263527
// SAFETY: const sound because integers are plain old datatypes so we can always
35273528
// transmute them to arrays of bytes
35283529
#[inline]
@@ -3624,6 +3625,7 @@ macro_rules! uint_impl {
36243625
/// ```
36253626
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
36263627
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3628+
#[cfg_attr(not(bootstrap), allow(unnecessary_transmutation))]
36273629
#[must_use]
36283630
// SAFETY: const sound because integers are plain old datatypes so we can always
36293631
// transmute to them

src/tools/clippy/tests/ui/blocks_in_conditions.fixed

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![warn(clippy::blocks_in_conditions)]
44
#![allow(
55
unused,
6+
unnecessary_transmutation,
67
clippy::let_and_return,
78
clippy::needless_if,
89
clippy::missing_transmute_annotations

src/tools/clippy/tests/ui/blocks_in_conditions.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![warn(clippy::blocks_in_conditions)]
44
#![allow(
55
unused,
6+
unnecessary_transmutation,
67
clippy::let_and_return,
78
clippy::needless_if,
89
clippy::missing_transmute_annotations

0 commit comments

Comments
 (0)