2 in_constant, is_normalizable, last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_sugg,
3 span_lint_and_then, sugg,
5 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{Expr, ExprKind, GenericArg, Mutability, QPath, TyKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, cast::CastKind, Ty};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::DUMMY_SP;
13 use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited};
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:** None.
106 /// let _: &T = std::mem::transmute(p); // where p: *const T
109 /// // can be written:
112 pub TRANSMUTE_PTR_TO_REF,
114 "transmutes from a pointer to a reference type"
117 declare_clippy_lint! {
118 /// **What it does:** Checks for transmutes from an integer to a `char`.
120 /// **Why is this bad?** Not every integer is a Unicode scalar value.
122 /// **Known problems:**
123 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
124 /// as it needs to validate the input.
125 /// If you are certain that the input is always a valid Unicode scalar value,
126 /// use [`from_u32_unchecked`] which is as fast as `transmute`
127 /// but has a semantically meaningful name.
128 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
130 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
131 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
137 /// let _: char = std::mem::transmute(x); // where x: u32
141 /// let _ = std::char::from_u32(x).unwrap();
143 pub TRANSMUTE_INT_TO_CHAR,
145 "transmutes from an integer to a `char`"
148 declare_clippy_lint! {
149 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
151 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
153 /// **Known problems:**
154 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
155 /// as it needs to validate the input.
156 /// If you are certain that the input is always a valid UTF-8,
157 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
158 /// but has a semantically meaningful name.
159 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
161 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
162 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
166 /// let b: &[u8] = &[1_u8, 2_u8];
168 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
172 /// let _ = std::str::from_utf8(b).unwrap();
174 pub TRANSMUTE_BYTES_TO_STR,
176 "transmutes from a `&[u8]` to a `&str`"
179 declare_clippy_lint! {
180 /// **What it does:** Checks for transmutes from an integer to a `bool`.
182 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
184 /// **Known problems:** None.
190 /// let _: bool = std::mem::transmute(x); // where x: u8
194 /// let _: bool = x != 0;
196 pub TRANSMUTE_INT_TO_BOOL,
198 "transmutes from an integer to a `bool`"
201 declare_clippy_lint! {
202 /// **What it does:** Checks for transmutes from an integer to a float.
204 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
207 /// **Known problems:** None.
212 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
216 /// let _: f32 = f32::from_bits(1_u32);
218 pub TRANSMUTE_INT_TO_FLOAT,
220 "transmutes from an integer to a float"
223 declare_clippy_lint! {
224 /// **What it does:** Checks for transmutes from a float to an integer.
226 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
229 /// **Known problems:** None.
234 /// let _: u32 = std::mem::transmute(1f32);
238 /// let _: u32 = 1f32.to_bits();
240 pub TRANSMUTE_FLOAT_TO_INT,
242 "transmutes from a float to an integer"
245 declare_clippy_lint! {
246 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
247 /// from a reference to a reference.
249 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
250 /// written as casts.
252 /// **Known problems:** None.
256 /// let ptr = &1u32 as *const u32;
258 /// // pointer-to-pointer transmute
259 /// let _: *const f32 = std::mem::transmute(ptr);
260 /// // ref-ref transmute
261 /// let _: &f32 = std::mem::transmute(&1u32);
263 /// // These can be respectively written:
264 /// let _ = ptr as *const f32;
265 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
267 pub TRANSMUTE_PTR_TO_PTR,
269 "transmutes from a pointer to a pointer / a reference to a reference"
272 declare_clippy_lint! {
273 /// **What it does:** Checks for transmutes between collections whose
274 /// types have different ABI, size or alignment.
276 /// **Why is this bad?** This is undefined behavior.
278 /// **Known problems:** Currently, we cannot know whether a type is a
279 /// collection, so we just lint the ones that come with `std`.
283 /// // different size, therefore likely out-of-bounds memory access
284 /// // You absolutely do not want this in your code!
286 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
290 /// You must always iterate, map and collect the values:
293 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
295 pub UNSOUND_COLLECTION_TRANSMUTE,
297 "transmute between collections of layout-incompatible types"
300 declare_lint_pass!(Transmute => [
301 CROSSPOINTER_TRANSMUTE,
302 TRANSMUTE_PTR_TO_REF,
303 TRANSMUTE_PTR_TO_PTR,
306 TRANSMUTE_INT_TO_CHAR,
307 TRANSMUTE_BYTES_TO_STR,
308 TRANSMUTE_INT_TO_BOOL,
309 TRANSMUTE_INT_TO_FLOAT,
310 TRANSMUTE_FLOAT_TO_INT,
311 UNSOUND_COLLECTION_TRANSMUTE,
312 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
315 // used to check for UNSOUND_COLLECTION_TRANSMUTE
316 static COLLECTIONS: &[&[&str]] = &[
325 impl<'tcx> LateLintPass<'tcx> for Transmute {
326 #[allow(clippy::similar_names, clippy::too_many_lines)]
327 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
329 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
330 if let ExprKind::Path(ref qpath) = path_expr.kind;
331 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
332 if match_def_path(cx, def_id, &paths::TRANSMUTE);
334 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
335 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
336 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
337 let const_context = in_constant(cx, e.hir_id);
339 let from_ty = cx.typeck_results().expr_ty(&args[0]);
340 let to_ty = cx.typeck_results().expr_ty(e);
342 match (&from_ty.kind(), &to_ty.kind()) {
343 _ if from_ty == to_ty => span_lint(
347 &format!("transmute from a type (`{}`) to itself", from_ty),
349 (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
353 "transmute from a reference to a pointer",
355 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
356 let rty_and_mut = ty::TypeAndMut {
361 let sugg = if *ptr_ty == rty_and_mut {
364 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
367 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
371 (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
375 "transmute from an integer to a pointer",
377 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
378 diag.span_suggestion(
381 arg.as_ty(&to_ty.to_string()).to_string(),
382 Applicability::Unspecified,
387 (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
391 &format!("transmute from a `{}` to a pointer", from_ty),
393 (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
395 CROSSPOINTER_TRANSMUTE,
398 "transmute from a type (`{}`) to the type that it points to (`{}`)",
402 (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
404 CROSSPOINTER_TRANSMUTE,
407 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
411 (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
413 TRANSMUTE_PTR_TO_REF,
416 "transmute from a pointer type (`{}`) to a reference type \
421 let arg = sugg::Sugg::hir(cx, &args[0], "..");
422 let (deref, cast) = if *mutbl == Mutability::Mut {
428 let arg = if from_pty.ty == *to_ref_ty {
431 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
434 diag.span_suggestion(
437 sugg::make_unop(deref, arg).to_string(),
438 Applicability::Unspecified,
442 (ty::Int(ast::IntTy::I32) | ty::Uint(ast::UintTy::U32), &ty::Char) => {
445 TRANSMUTE_INT_TO_CHAR,
447 &format!("transmute from a `{}` to a `char`", from_ty),
449 let arg = sugg::Sugg::hir(cx, &args[0], "..");
450 let arg = if let ty::Int(_) = from_ty.kind() {
451 arg.as_ty(ast::UintTy::U32.name_str())
455 diag.span_suggestion(
458 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
459 Applicability::Unspecified,
464 (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
466 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
467 if let ty::Uint(ast::UintTy::U8) = slice_ty.kind();
468 if from_mutbl == to_mutbl;
470 let postfix = if *from_mutbl == Mutability::Mut {
478 TRANSMUTE_BYTES_TO_STR,
480 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
483 "std::str::from_utf8{}({}).unwrap()",
485 snippet(cx, args[0].span, ".."),
487 Applicability::Unspecified,
490 if (cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty))
494 TRANSMUTE_PTR_TO_PTR,
496 "transmute from a reference to a reference",
497 |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
498 let ty_from_and_mut = ty::TypeAndMut {
502 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
504 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
505 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
506 let sugg = if *to_mutbl == Mutability::Mut {
507 sugg_paren.mut_addr_deref()
509 sugg_paren.addr_deref()
511 diag.span_suggestion(
515 Applicability::Unspecified,
523 (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
525 TRANSMUTE_PTR_TO_PTR,
527 "transmute from a pointer to a pointer",
529 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
530 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
531 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
535 (ty::Int(ast::IntTy::I8) | ty::Uint(ast::UintTy::U8), ty::Bool) => {
538 TRANSMUTE_INT_TO_BOOL,
540 &format!("transmute from a `{}` to a `bool`", from_ty),
542 let arg = sugg::Sugg::hir(cx, &args[0], "..");
543 let zero = sugg::Sugg::NonParen(Cow::from("0"));
544 diag.span_suggestion(
547 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
548 Applicability::Unspecified,
553 (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
555 TRANSMUTE_INT_TO_FLOAT,
557 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
559 let arg = sugg::Sugg::hir(cx, &args[0], "..");
560 let arg = if let ty::Int(int_ty) = from_ty.kind() {
563 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
568 diag.span_suggestion(
571 format!("{}::from_bits({})", to_ty, arg.to_string()),
572 Applicability::Unspecified,
576 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
578 TRANSMUTE_FLOAT_TO_INT,
580 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
582 let mut expr = &args[0];
583 let mut arg = sugg::Sugg::hir(cx, expr, "..");
585 if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
590 // if the expression is a float literal and it is unsuffixed then
591 // add a suffix so the suggestion is valid and unambiguous
592 let op = format!("{}{}", arg, float_ty.name_str()).into();
593 if let ExprKind::Lit(lit) = &expr.kind;
594 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
597 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
598 _ => arg = sugg::Sugg::NonParen(op)
603 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
605 // cast the result of `to_bits` if `to_ty` is signed
606 arg = if let ty::Int(int_ty) = to_ty.kind() {
607 arg.as_ty(int_ty.name_str().to_string())
612 diag.span_suggestion(
616 Applicability::Unspecified,
620 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
621 if from_adt.did != to_adt.did ||
622 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
625 if from_substs.types().zip(to_substs.types())
626 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
629 UNSOUND_COLLECTION_TRANSMUTE,
632 "transmute from `{}` to `{}` with mismatched layout is unsound",
639 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
641 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
644 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
649 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
650 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
651 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);
664 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
665 /// not available , use
666 /// the type's `ToString` implementation. In weird cases it could lead to types
667 /// with invalid `'_`
668 /// lifetime, but it should be rare.
669 fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
670 let seg = last_path_segment(path);
672 if let Some(ref params) = seg.args;
673 if !params.parenthesized;
674 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
675 GenericArg::Type(ty) => Some(ty),
678 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
680 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
684 to_ref_ty.to_string()
687 // check if the component types of the transmuted collection and the result have different ABI,
689 fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
690 let empty_param_env = ty::ParamEnv::empty();
691 // check if `from` and `to` are normalizable to avoid ICE (#4968)
692 if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
695 let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
696 let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
697 if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
698 from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
700 // no idea about layout, so don't lint
705 /// Check if the type conversion can be expressed as a pointer cast, instead of
706 /// a transmute. In certain cases, including some invalid casts from array
707 /// references to pointers, this may cause additional errors to be emitted and/or
708 /// ICE error messages. This function will panic if that occurs.
709 fn can_be_expressed_as_pointer_cast<'tcx>(
710 cx: &LateContext<'tcx>,
715 use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
717 check_cast(cx, e, from_ty, to_ty),
718 Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
722 /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
723 /// the cast. In certain cases, including some invalid casts from array references
724 /// to pointers, this may cause additional errors to be emitted and/or ICE error
725 /// messages. This function will panic if that occurs.
726 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
727 let hir_id = e.hir_id;
728 let local_def_id = hir_id.owner;
730 Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
731 let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id);
733 // If we already have errors, we can't be sure we can pointer cast.
735 !fn_ctxt.errors_reported_since_creation(),
736 "Newly created FnCtxt contained errors"
739 if let Ok(check) = CastCheck::new(
740 &fn_ctxt, e, from_ty, to_ty,
741 // We won't show any error to the user, so we don't care what the span is here.
744 let res = check.do_check(&fn_ctxt);
746 // do_check's documentation says that it might return Ok and create
747 // errors in the fcx instead of returing Err in some cases. Those cases
748 // should be filtered out before getting here.
750 !fn_ctxt.errors_reported_since_creation(),
751 "`fn_ctxt` contained errors after cast check!"