1 mod crosspointer_transmute;
2 mod transmute_int_to_bool;
3 mod transmute_int_to_char;
4 mod transmute_ptr_to_ptr;
5 mod transmute_ptr_to_ref;
6 mod transmute_ref_to_ref;
14 in_constant, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, span_lint_and_then, sugg,
16 use if_chain::if_chain;
18 use rustc_errors::Applicability;
19 use rustc_hir::{Expr, ExprKind, Mutability, UnOp};
20 use rustc_lint::{LateContext, LateLintPass};
22 use rustc_session::{declare_lint_pass, declare_tool_lint};
25 declare_clippy_lint! {
26 /// **What it does:** Checks for transmutes that can't ever be correct on any
29 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
31 /// **Known problems:** When accessing C, users might want to store pointer
32 /// sized objects in `extradata` arguments to save an allocation.
36 /// let ptr: *const T = core::intrinsics::transmute('x')
40 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
43 // FIXME: Move this to `complexity` again, after #5343 is fixed
44 declare_clippy_lint! {
45 /// **What it does:** Checks for transmutes to the original type of the object
46 /// and transmutes that could be a cast.
48 /// **Why is this bad?** Readability. The code tricks people into thinking that
49 /// something complex is going on.
51 /// **Known problems:** None.
55 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
57 pub USELESS_TRANSMUTE,
59 "transmutes that have the same to and from types or could be a cast/coercion"
62 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
63 declare_clippy_lint! {
64 /// **What it does:**Checks for transmutes that could be a pointer cast.
66 /// **Why is this bad?** Readability. The code tricks people into thinking that
67 /// something complex is going on.
69 /// **Known problems:** None.
74 /// # let p: *const [i32] = &[];
75 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
79 /// # let p: *const [i32] = &[];
80 /// p as *const [u16];
82 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
84 "transmutes that could be a pointer cast"
87 declare_clippy_lint! {
88 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
90 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
91 /// pointer to that type.
93 /// **Known problems:** None.
97 /// core::intrinsics::transmute(t) // where the result type is the same as
100 pub CROSSPOINTER_TRANSMUTE,
102 "transmutes that have to or from types that are a pointer to the other"
105 declare_clippy_lint! {
106 /// **What it does:** Checks for transmutes from a pointer to a reference.
108 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
110 /// **Known problems:**
111 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
112 /// while dereferencing raw pointer is not stable yet.
113 /// If you need to do this in those places,
114 /// you would have to use `transmute` instead.
119 /// let _: &T = std::mem::transmute(p); // where p: *const T
122 /// // can be written:
125 pub TRANSMUTE_PTR_TO_REF,
127 "transmutes from a pointer to a reference type"
130 declare_clippy_lint! {
131 /// **What it does:** Checks for transmutes from an integer to a `char`.
133 /// **Why is this bad?** Not every integer is a Unicode scalar value.
135 /// **Known problems:**
136 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
137 /// as it needs to validate the input.
138 /// If you are certain that the input is always a valid Unicode scalar value,
139 /// use [`from_u32_unchecked`] which is as fast as `transmute`
140 /// but has a semantically meaningful name.
141 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
143 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
144 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
150 /// let _: char = std::mem::transmute(x); // where x: u32
154 /// let _ = std::char::from_u32(x).unwrap();
156 pub TRANSMUTE_INT_TO_CHAR,
158 "transmutes from an integer to a `char`"
161 declare_clippy_lint! {
162 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
164 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
166 /// **Known problems:**
167 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
168 /// as it needs to validate the input.
169 /// If you are certain that the input is always a valid UTF-8,
170 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
171 /// but has a semantically meaningful name.
172 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
174 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
175 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
179 /// let b: &[u8] = &[1_u8, 2_u8];
181 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
185 /// let _ = std::str::from_utf8(b).unwrap();
187 pub TRANSMUTE_BYTES_TO_STR,
189 "transmutes from a `&[u8]` to a `&str`"
192 declare_clippy_lint! {
193 /// **What it does:** Checks for transmutes from an integer to a `bool`.
195 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
197 /// **Known problems:** None.
203 /// let _: bool = std::mem::transmute(x); // where x: u8
207 /// let _: bool = x != 0;
209 pub TRANSMUTE_INT_TO_BOOL,
211 "transmutes from an integer to a `bool`"
214 declare_clippy_lint! {
215 /// **What it does:** Checks for transmutes from an integer to a float.
217 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
220 /// **Known problems:** None.
225 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
229 /// let _: f32 = f32::from_bits(1_u32);
231 pub TRANSMUTE_INT_TO_FLOAT,
233 "transmutes from an integer to a float"
236 declare_clippy_lint! {
237 /// **What it does:** Checks for transmutes from a float to an integer.
239 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
242 /// **Known problems:** None.
247 /// let _: u32 = std::mem::transmute(1f32);
251 /// let _: u32 = 1f32.to_bits();
253 pub TRANSMUTE_FLOAT_TO_INT,
255 "transmutes from a float to an integer"
258 declare_clippy_lint! {
259 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
260 /// from a reference to a reference.
262 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
263 /// written as casts.
265 /// **Known problems:** None.
269 /// let ptr = &1u32 as *const u32;
271 /// // pointer-to-pointer transmute
272 /// let _: *const f32 = std::mem::transmute(ptr);
273 /// // ref-ref transmute
274 /// let _: &f32 = std::mem::transmute(&1u32);
276 /// // These can be respectively written:
277 /// let _ = ptr as *const f32;
278 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
280 pub TRANSMUTE_PTR_TO_PTR,
282 "transmutes from a pointer to a pointer / a reference to a reference"
285 declare_clippy_lint! {
286 /// **What it does:** Checks for transmutes between collections whose
287 /// types have different ABI, size or alignment.
289 /// **Why is this bad?** This is undefined behavior.
291 /// **Known problems:** Currently, we cannot know whether a type is a
292 /// collection, so we just lint the ones that come with `std`.
296 /// // different size, therefore likely out-of-bounds memory access
297 /// // You absolutely do not want this in your code!
299 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
303 /// You must always iterate, map and collect the values:
306 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
308 pub UNSOUND_COLLECTION_TRANSMUTE,
310 "transmute between collections of layout-incompatible types"
313 declare_lint_pass!(Transmute => [
314 CROSSPOINTER_TRANSMUTE,
315 TRANSMUTE_PTR_TO_REF,
316 TRANSMUTE_PTR_TO_PTR,
319 TRANSMUTE_INT_TO_CHAR,
320 TRANSMUTE_BYTES_TO_STR,
321 TRANSMUTE_INT_TO_BOOL,
322 TRANSMUTE_INT_TO_FLOAT,
323 TRANSMUTE_FLOAT_TO_INT,
324 UNSOUND_COLLECTION_TRANSMUTE,
325 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
328 // used to check for UNSOUND_COLLECTION_TRANSMUTE
329 static COLLECTIONS: &[&[&str]] = &[
339 impl<'tcx> LateLintPass<'tcx> for Transmute {
340 #[allow(clippy::similar_names, clippy::too_many_lines)]
341 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
343 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
344 if let ExprKind::Path(ref qpath) = path_expr.kind;
345 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
346 if match_def_path(cx, def_id, &paths::TRANSMUTE);
348 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
349 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
350 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
351 let const_context = in_constant(cx, e.hir_id);
353 let from_ty = cx.typeck_results().expr_ty(&args[0]);
354 let to_ty = cx.typeck_results().expr_ty(e);
356 let triggered = useless_transmute::check(cx, e, from_ty, to_ty, args);
360 let triggered = wrong_transmute::check(cx, e, from_ty, to_ty);
364 let triggered = crosspointer_transmute::check(cx, e, from_ty, to_ty);
368 let triggered = transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
372 let triggered = transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
376 let triggered = transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
380 let triggered = transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
384 let triggered = transmute_int_to_bool::check(cx, e, from_ty, to_ty, args);
389 match (&from_ty.kind(), &to_ty.kind()) {
390 (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
392 TRANSMUTE_INT_TO_FLOAT,
394 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
396 let arg = sugg::Sugg::hir(cx, &args[0], "..");
397 let arg = if let ty::Int(int_ty) = from_ty.kind() {
400 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
405 diag.span_suggestion(
408 format!("{}::from_bits({})", to_ty, arg.to_string()),
409 Applicability::Unspecified,
413 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
415 TRANSMUTE_FLOAT_TO_INT,
417 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
419 let mut expr = &args[0];
420 let mut arg = sugg::Sugg::hir(cx, expr, "..");
422 if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
427 // if the expression is a float literal and it is unsuffixed then
428 // add a suffix so the suggestion is valid and unambiguous
429 let op = format!("{}{}", arg, float_ty.name_str()).into();
430 if let ExprKind::Lit(lit) = &expr.kind;
431 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
434 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
435 _ => arg = sugg::Sugg::NonParen(op)
440 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
442 // cast the result of `to_bits` if `to_ty` is signed
443 arg = if let ty::Int(int_ty) = to_ty.kind() {
444 arg.as_ty(int_ty.name_str().to_string())
449 diag.span_suggestion(
453 Applicability::Unspecified,
457 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
458 if from_adt.did != to_adt.did ||
459 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
462 if from_substs.types().zip(to_substs.types())
463 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
466 UNSOUND_COLLECTION_TRANSMUTE,
469 "transmute from `{}` to `{}` with mismatched layout is unsound",
476 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
478 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
481 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
486 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
487 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
488 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);