Skip to content

Commit 714a583

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

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

Lines changed: 1 addition & 0 deletions
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

Lines changed: 1 addition & 1 deletion
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_transmutate)]
44

55
extern crate mini_core;
66

compiler/rustc_codegen_gcc/example/example.rs

Lines changed: 1 addition & 1 deletion
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_transmutate)]
44

55
extern crate mini_core;
66

compiler/rustc_lint_defs/src/builtin.rs

Lines changed: 25 additions & 0 deletions
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_TRANSMUTATE,
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_transmutate` 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_TRANSMUTATE,
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

Lines changed: 1 addition & 0 deletions
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

Lines changed: 2 additions & 0 deletions
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
Lines changed: 103 additions & 0 deletions
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_TRANSMUTATE;
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_TRANSMUTATE, hir_id, span, lint);
101+
}
102+
}
103+
}

compiler/rustc_mir_transform/src/errors.rs

Lines changed: 20 additions & 0 deletions
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

Lines changed: 2 additions & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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_transmutate))]
45

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

0 commit comments

Comments
 (0)