5 in_constant, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, span_lint_and_then, sugg,
7 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::{Expr, ExprKind, Mutability, UnOp};
11 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 declare_clippy_lint! {
17 /// **What it does:** Checks for transmutes that can't ever be correct on any
20 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
22 /// **Known problems:** When accessing C, users might want to store pointer
23 /// sized objects in `extradata` arguments to save an allocation.
27 /// let ptr: *const T = core::intrinsics::transmute('x')
31 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
34 // FIXME: Move this to `complexity` again, after #5343 is fixed
35 declare_clippy_lint! {
36 /// **What it does:** Checks for transmutes to the original type of the object
37 /// and transmutes that could be a cast.
39 /// **Why is this bad?** Readability. The code tricks people into thinking that
40 /// something complex is going on.
42 /// **Known problems:** None.
46 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
48 pub USELESS_TRANSMUTE,
50 "transmutes that have the same to and from types or could be a cast/coercion"
53 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
54 declare_clippy_lint! {
55 /// **What it does:**Checks for transmutes that could be a pointer cast.
57 /// **Why is this bad?** Readability. The code tricks people into thinking that
58 /// something complex is going on.
60 /// **Known problems:** None.
65 /// # let p: *const [i32] = &[];
66 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
70 /// # let p: *const [i32] = &[];
71 /// p as *const [u16];
73 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
75 "transmutes that could be a pointer cast"
78 declare_clippy_lint! {
79 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
81 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
82 /// pointer to that type.
84 /// **Known problems:** None.
88 /// core::intrinsics::transmute(t) // where the result type is the same as
91 pub CROSSPOINTER_TRANSMUTE,
93 "transmutes that have to or from types that are a pointer to the other"
96 declare_clippy_lint! {
97 /// **What it does:** Checks for transmutes from a pointer to a reference.
99 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
101 /// **Known problems:**
102 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
103 /// while dereferencing raw pointer is not stable yet.
104 /// If you need to do this in those places,
105 /// you would have to use `transmute` instead.
110 /// let _: &T = std::mem::transmute(p); // where p: *const T
113 /// // can be written:
116 pub TRANSMUTE_PTR_TO_REF,
118 "transmutes from a pointer to a reference type"
121 declare_clippy_lint! {
122 /// **What it does:** Checks for transmutes from an integer to a `char`.
124 /// **Why is this bad?** Not every integer is a Unicode scalar value.
126 /// **Known problems:**
127 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
128 /// as it needs to validate the input.
129 /// If you are certain that the input is always a valid Unicode scalar value,
130 /// use [`from_u32_unchecked`] which is as fast as `transmute`
131 /// but has a semantically meaningful name.
132 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
134 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
135 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
141 /// let _: char = std::mem::transmute(x); // where x: u32
145 /// let _ = std::char::from_u32(x).unwrap();
147 pub TRANSMUTE_INT_TO_CHAR,
149 "transmutes from an integer to a `char`"
152 declare_clippy_lint! {
153 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
155 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
157 /// **Known problems:**
158 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
159 /// as it needs to validate the input.
160 /// If you are certain that the input is always a valid UTF-8,
161 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
162 /// but has a semantically meaningful name.
163 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
165 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
166 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
170 /// let b: &[u8] = &[1_u8, 2_u8];
172 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
176 /// let _ = std::str::from_utf8(b).unwrap();
178 pub TRANSMUTE_BYTES_TO_STR,
180 "transmutes from a `&[u8]` to a `&str`"
183 declare_clippy_lint! {
184 /// **What it does:** Checks for transmutes from an integer to a `bool`.
186 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
188 /// **Known problems:** None.
194 /// let _: bool = std::mem::transmute(x); // where x: u8
198 /// let _: bool = x != 0;
200 pub TRANSMUTE_INT_TO_BOOL,
202 "transmutes from an integer to a `bool`"
205 declare_clippy_lint! {
206 /// **What it does:** Checks for transmutes from an integer to a float.
208 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
211 /// **Known problems:** None.
216 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
220 /// let _: f32 = f32::from_bits(1_u32);
222 pub TRANSMUTE_INT_TO_FLOAT,
224 "transmutes from an integer to a float"
227 declare_clippy_lint! {
228 /// **What it does:** Checks for transmutes from a float to an integer.
230 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
233 /// **Known problems:** None.
238 /// let _: u32 = std::mem::transmute(1f32);
242 /// let _: u32 = 1f32.to_bits();
244 pub TRANSMUTE_FLOAT_TO_INT,
246 "transmutes from a float to an integer"
249 declare_clippy_lint! {
250 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
251 /// from a reference to a reference.
253 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
254 /// written as casts.
256 /// **Known problems:** None.
260 /// let ptr = &1u32 as *const u32;
262 /// // pointer-to-pointer transmute
263 /// let _: *const f32 = std::mem::transmute(ptr);
264 /// // ref-ref transmute
265 /// let _: &f32 = std::mem::transmute(&1u32);
267 /// // These can be respectively written:
268 /// let _ = ptr as *const f32;
269 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
271 pub TRANSMUTE_PTR_TO_PTR,
273 "transmutes from a pointer to a pointer / a reference to a reference"
276 declare_clippy_lint! {
277 /// **What it does:** Checks for transmutes between collections whose
278 /// types have different ABI, size or alignment.
280 /// **Why is this bad?** This is undefined behavior.
282 /// **Known problems:** Currently, we cannot know whether a type is a
283 /// collection, so we just lint the ones that come with `std`.
287 /// // different size, therefore likely out-of-bounds memory access
288 /// // You absolutely do not want this in your code!
290 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
294 /// You must always iterate, map and collect the values:
297 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
299 pub UNSOUND_COLLECTION_TRANSMUTE,
301 "transmute between collections of layout-incompatible types"
304 declare_lint_pass!(Transmute => [
305 CROSSPOINTER_TRANSMUTE,
306 TRANSMUTE_PTR_TO_REF,
307 TRANSMUTE_PTR_TO_PTR,
310 TRANSMUTE_INT_TO_CHAR,
311 TRANSMUTE_BYTES_TO_STR,
312 TRANSMUTE_INT_TO_BOOL,
313 TRANSMUTE_INT_TO_FLOAT,
314 TRANSMUTE_FLOAT_TO_INT,
315 UNSOUND_COLLECTION_TRANSMUTE,
316 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
319 // used to check for UNSOUND_COLLECTION_TRANSMUTE
320 static COLLECTIONS: &[&[&str]] = &[
330 impl<'tcx> LateLintPass<'tcx> for Transmute {
331 #[allow(clippy::similar_names, clippy::too_many_lines)]
332 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
334 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
335 if let ExprKind::Path(ref qpath) = path_expr.kind;
336 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
337 if match_def_path(cx, def_id, &paths::TRANSMUTE);
339 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
340 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
341 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
342 let const_context = in_constant(cx, e.hir_id);
344 let from_ty = cx.typeck_results().expr_ty(&args[0]);
345 let to_ty = cx.typeck_results().expr_ty(e);
347 match (&from_ty.kind(), &to_ty.kind()) {
348 _ if from_ty == to_ty => span_lint(
352 &format!("transmute from a type (`{}`) to itself", from_ty),
354 (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
358 "transmute from a reference to a pointer",
360 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
361 let rty_and_mut = ty::TypeAndMut {
366 let sugg = if *ptr_ty == rty_and_mut {
369 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
372 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
376 (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
380 "transmute from an integer to a pointer",
382 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
383 diag.span_suggestion(
386 arg.as_ty(&to_ty.to_string()).to_string(),
387 Applicability::Unspecified,
392 (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
396 &format!("transmute from a `{}` to a pointer", from_ty),
398 (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
400 CROSSPOINTER_TRANSMUTE,
403 "transmute from a type (`{}`) to the type that it points to (`{}`)",
407 (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
409 CROSSPOINTER_TRANSMUTE,
412 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
416 (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
418 TRANSMUTE_PTR_TO_REF,
421 "transmute from a pointer type (`{}`) to a reference type \
426 let arg = sugg::Sugg::hir(cx, &args[0], "..");
427 let (deref, cast) = if *mutbl == Mutability::Mut {
433 let arg = if from_pty.ty == *to_ref_ty {
436 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
439 diag.span_suggestion(
442 sugg::make_unop(deref, arg).to_string(),
443 Applicability::Unspecified,
447 (ty::Int(ty::IntTy::I32) | ty::Uint(ty::UintTy::U32), &ty::Char) => {
450 TRANSMUTE_INT_TO_CHAR,
452 &format!("transmute from a `{}` to a `char`", from_ty),
454 let arg = sugg::Sugg::hir(cx, &args[0], "..");
455 let arg = if let ty::Int(_) = from_ty.kind() {
456 arg.as_ty(ast::UintTy::U32.name_str())
460 diag.span_suggestion(
463 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
464 Applicability::Unspecified,
469 (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
471 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
472 if let ty::Uint(ty::UintTy::U8) = slice_ty.kind();
473 if from_mutbl == to_mutbl;
475 let postfix = if *from_mutbl == Mutability::Mut {
483 TRANSMUTE_BYTES_TO_STR,
485 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
488 "std::str::from_utf8{}({}).unwrap()",
490 snippet(cx, args[0].span, ".."),
492 Applicability::Unspecified,
495 if (cx.tcx.erase_regions(from_ty) != cx.tcx.erase_regions(to_ty))
499 TRANSMUTE_PTR_TO_PTR,
501 "transmute from a reference to a reference",
502 |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
503 let ty_from_and_mut = ty::TypeAndMut {
507 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
509 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
510 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
511 let sugg = if *to_mutbl == Mutability::Mut {
512 sugg_paren.mut_addr_deref()
514 sugg_paren.addr_deref()
516 diag.span_suggestion(
520 Applicability::Unspecified,
528 (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
530 TRANSMUTE_PTR_TO_PTR,
532 "transmute from a pointer to a pointer",
534 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
535 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
536 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
540 (ty::Int(ty::IntTy::I8) | ty::Uint(ty::UintTy::U8), ty::Bool) => {
543 TRANSMUTE_INT_TO_BOOL,
545 &format!("transmute from a `{}` to a `bool`", from_ty),
547 let arg = sugg::Sugg::hir(cx, &args[0], "..");
548 let zero = sugg::Sugg::NonParen(Cow::from("0"));
549 diag.span_suggestion(
552 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
553 Applicability::Unspecified,
558 (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
560 TRANSMUTE_INT_TO_FLOAT,
562 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
564 let arg = sugg::Sugg::hir(cx, &args[0], "..");
565 let arg = if let ty::Int(int_ty) = from_ty.kind() {
568 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
573 diag.span_suggestion(
576 format!("{}::from_bits({})", to_ty, arg.to_string()),
577 Applicability::Unspecified,
581 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
583 TRANSMUTE_FLOAT_TO_INT,
585 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
587 let mut expr = &args[0];
588 let mut arg = sugg::Sugg::hir(cx, expr, "..");
590 if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
595 // if the expression is a float literal and it is unsuffixed then
596 // add a suffix so the suggestion is valid and unambiguous
597 let op = format!("{}{}", arg, float_ty.name_str()).into();
598 if let ExprKind::Lit(lit) = &expr.kind;
599 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
602 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
603 _ => arg = sugg::Sugg::NonParen(op)
608 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
610 // cast the result of `to_bits` if `to_ty` is signed
611 arg = if let ty::Int(int_ty) = to_ty.kind() {
612 arg.as_ty(int_ty.name_str().to_string())
617 diag.span_suggestion(
621 Applicability::Unspecified,
625 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
626 if from_adt.did != to_adt.did ||
627 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
630 if from_substs.types().zip(to_substs.types())
631 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
634 UNSOUND_COLLECTION_TRANSMUTE,
637 "transmute from `{}` to `{}` with mismatched layout is unsound",
644 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
646 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
649 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
654 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
655 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
656 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);