2 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_span::DUMMY_SP;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
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 /// core::intrinsics::transmute::<*const [i32], *const [u16]>(p)
71 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
73 "transmutes that could be a pointer cast"
76 declare_clippy_lint! {
77 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
79 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
80 /// pointer to that type.
82 /// **Known problems:** None.
86 /// core::intrinsics::transmute(t) // where the result type is the same as
89 pub CROSSPOINTER_TRANSMUTE,
91 "transmutes that have to or from types that are a pointer to the other"
94 declare_clippy_lint! {
95 /// **What it does:** Checks for transmutes from a pointer to a reference.
97 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
99 /// **Known problems:** None.
104 /// let _: &T = std::mem::transmute(p); // where p: *const T
107 /// // can be written:
110 pub TRANSMUTE_PTR_TO_REF,
112 "transmutes from a pointer to a reference type"
115 declare_clippy_lint! {
116 /// **What it does:** Checks for transmutes from an integer to a `char`.
118 /// **Why is this bad?** Not every integer is a Unicode scalar value.
120 /// **Known problems:**
121 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
122 /// as it needs to validate the input.
123 /// If you are certain that the input is always a valid Unicode scalar value,
124 /// use [`from_u32_unchecked`] which is as fast as `transmute`
125 /// but has a semantically meaningful name.
126 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
128 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
129 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
135 /// let _: char = std::mem::transmute(x); // where x: u32
139 /// let _ = std::char::from_u32(x).unwrap();
141 pub TRANSMUTE_INT_TO_CHAR,
143 "transmutes from an integer to a `char`"
146 declare_clippy_lint! {
147 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
149 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
151 /// **Known problems:**
152 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
153 /// as it needs to validate the input.
154 /// If you are certain that the input is always a valid UTF-8,
155 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
156 /// but has a semantically meaningful name.
157 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
159 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
160 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
164 /// let b: &[u8] = &[1_u8, 2_u8];
166 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
170 /// let _ = std::str::from_utf8(b).unwrap();
172 pub TRANSMUTE_BYTES_TO_STR,
174 "transmutes from a `&[u8]` to a `&str`"
177 declare_clippy_lint! {
178 /// **What it does:** Checks for transmutes from an integer to a `bool`.
180 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
182 /// **Known problems:** None.
188 /// let _: bool = std::mem::transmute(x); // where x: u8
192 /// let _: bool = x != 0;
194 pub TRANSMUTE_INT_TO_BOOL,
196 "transmutes from an integer to a `bool`"
199 declare_clippy_lint! {
200 /// **What it does:** Checks for transmutes from an integer to a float.
202 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
205 /// **Known problems:** None.
210 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
214 /// let _: f32 = f32::from_bits(1_u32);
216 pub TRANSMUTE_INT_TO_FLOAT,
218 "transmutes from an integer to a float"
221 declare_clippy_lint! {
222 /// **What it does:** Checks for transmutes from a float to an integer.
224 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
227 /// **Known problems:** None.
232 /// let _: u32 = std::mem::transmute(1f32);
236 /// let _: u32 = 1f32.to_bits();
238 pub TRANSMUTE_FLOAT_TO_INT,
240 "transmutes from a float to an integer"
243 declare_clippy_lint! {
244 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
245 /// from a reference to a reference.
247 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
248 /// written as casts.
250 /// **Known problems:** None.
254 /// let ptr = &1u32 as *const u32;
256 /// // pointer-to-pointer transmute
257 /// let _: *const f32 = std::mem::transmute(ptr);
258 /// // ref-ref transmute
259 /// let _: &f32 = std::mem::transmute(&1u32);
261 /// // These can be respectively written:
262 /// let _ = ptr as *const f32;
263 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
265 pub TRANSMUTE_PTR_TO_PTR,
267 "transmutes from a pointer to a pointer / a reference to a reference"
270 declare_clippy_lint! {
271 /// **What it does:** Checks for transmutes between collections whose
272 /// types have different ABI, size or alignment.
274 /// **Why is this bad?** This is undefined behavior.
276 /// **Known problems:** Currently, we cannot know whether a type is a
277 /// collection, so we just lint the ones that come with `std`.
281 /// // different size, therefore likely out-of-bounds memory access
282 /// // You absolutely do not want this in your code!
284 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
288 /// You must always iterate, map and collect the values:
291 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
293 pub UNSOUND_COLLECTION_TRANSMUTE,
295 "transmute between collections of layout-incompatible types"
298 declare_lint_pass!(Transmute => [
299 CROSSPOINTER_TRANSMUTE,
300 TRANSMUTE_PTR_TO_REF,
301 TRANSMUTE_PTR_TO_PTR,
304 TRANSMUTE_INT_TO_CHAR,
305 TRANSMUTE_BYTES_TO_STR,
306 TRANSMUTE_INT_TO_BOOL,
307 TRANSMUTE_INT_TO_FLOAT,
308 TRANSMUTE_FLOAT_TO_INT,
309 UNSOUND_COLLECTION_TRANSMUTE,
310 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
313 // used to check for UNSOUND_COLLECTION_TRANSMUTE
314 static COLLECTIONS: &[&[&str]] = &[
323 impl<'tcx> LateLintPass<'tcx> for Transmute {
324 #[allow(clippy::similar_names, clippy::too_many_lines)]
325 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
327 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
328 if let ExprKind::Path(ref qpath) = path_expr.kind;
329 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
330 if match_def_path(cx, def_id, &paths::TRANSMUTE);
332 let from_ty = cx.typeck_results().expr_ty(&args[0]);
333 let to_ty = cx.typeck_results().expr_ty(e);
335 match (&from_ty.kind, &to_ty.kind) {
336 _ if from_ty == to_ty => span_lint(
340 &format!("transmute from a type (`{}`) to itself", from_ty),
342 (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
346 "transmute from a reference to a pointer",
348 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
349 let rty_and_mut = ty::TypeAndMut {
354 let sugg = if *ptr_ty == rty_and_mut {
357 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
360 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
364 (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
368 "transmute from an integer to a pointer",
370 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
371 diag.span_suggestion(
374 arg.as_ty(&to_ty.to_string()).to_string(),
375 Applicability::Unspecified,
380 (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
384 &format!("transmute from a `{}` to a pointer", from_ty),
386 (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
388 CROSSPOINTER_TRANSMUTE,
391 "transmute from a type (`{}`) to the type that it points to (`{}`)",
395 (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
397 CROSSPOINTER_TRANSMUTE,
400 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
404 (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
406 TRANSMUTE_PTR_TO_REF,
409 "transmute from a pointer type (`{}`) to a reference type \
414 let arg = sugg::Sugg::hir(cx, &args[0], "..");
415 let (deref, cast) = if *mutbl == Mutability::Mut {
421 let arg = if from_pty.ty == *to_ref_ty {
424 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
427 diag.span_suggestion(
430 sugg::make_unop(deref, arg).to_string(),
431 Applicability::Unspecified,
435 (ty::Int(ast::IntTy::I32) | ty::Uint(ast::UintTy::U32), &ty::Char) => {
438 TRANSMUTE_INT_TO_CHAR,
440 &format!("transmute from a `{}` to a `char`", from_ty),
442 let arg = sugg::Sugg::hir(cx, &args[0], "..");
443 let arg = if let ty::Int(_) = from_ty.kind {
444 arg.as_ty(ast::UintTy::U32.name_str())
448 diag.span_suggestion(
451 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
452 Applicability::Unspecified,
457 (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
459 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind, &ty_to.kind);
460 if let ty::Uint(ast::UintTy::U8) = slice_ty.kind;
461 if from_mutbl == to_mutbl;
463 let postfix = if *from_mutbl == Mutability::Mut {
471 TRANSMUTE_BYTES_TO_STR,
473 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
476 "std::str::from_utf8{}({}).unwrap()",
478 snippet(cx, args[0].span, ".."),
480 Applicability::Unspecified,
483 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
486 TRANSMUTE_PTR_TO_PTR,
488 "transmute from a reference to a reference",
489 |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
490 let ty_from_and_mut = ty::TypeAndMut {
494 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
496 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
497 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
498 let sugg = if *to_mutbl == Mutability::Mut {
499 sugg_paren.mut_addr_deref()
501 sugg_paren.addr_deref()
503 diag.span_suggestion(
507 Applicability::Unspecified,
515 (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
517 TRANSMUTE_PTR_TO_PTR,
519 "transmute from a pointer to a pointer",
521 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
522 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
523 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
527 (ty::Int(ast::IntTy::I8) | ty::Uint(ast::UintTy::U8), ty::Bool) => {
530 TRANSMUTE_INT_TO_BOOL,
532 &format!("transmute from a `{}` to a `bool`", from_ty),
534 let arg = sugg::Sugg::hir(cx, &args[0], "..");
535 let zero = sugg::Sugg::NonParen(Cow::from("0"));
536 diag.span_suggestion(
539 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
540 Applicability::Unspecified,
545 (ty::Int(_) | ty::Uint(_), ty::Float(_)) => span_lint_and_then(
547 TRANSMUTE_INT_TO_FLOAT,
549 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
551 let arg = sugg::Sugg::hir(cx, &args[0], "..");
552 let arg = if let ty::Int(int_ty) = from_ty.kind {
555 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
560 diag.span_suggestion(
563 format!("{}::from_bits({})", to_ty, arg.to_string()),
564 Applicability::Unspecified,
568 (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) => span_lint_and_then(
570 TRANSMUTE_FLOAT_TO_INT,
572 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
574 let mut expr = &args[0];
575 let mut arg = sugg::Sugg::hir(cx, expr, "..");
577 if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
582 // if the expression is a float literal and it is unsuffixed then
583 // add a suffix so the suggestion is valid and unambiguous
584 let op = format!("{}{}", arg, float_ty.name_str()).into();
585 if let ExprKind::Lit(lit) = &expr.kind;
586 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
589 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
590 _ => arg = sugg::Sugg::NonParen(op)
595 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
597 // cast the result of `to_bits` if `to_ty` is signed
598 arg = if let ty::Int(int_ty) = to_ty.kind {
599 arg.as_ty(int_ty.name_str().to_string())
604 diag.span_suggestion(
608 Applicability::Unspecified,
612 (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
613 if from_adt.did != to_adt.did ||
614 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
617 if from_substs.types().zip(to_substs.types())
618 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
621 UNSOUND_COLLECTION_TRANSMUTE,
624 "transmute from `{}` to `{}` with mismatched layout is unsound",
631 (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
633 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
636 "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
641 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
642 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
643 diag.span_suggestion(e.span, "try", sugg, Applicability::Unspecified);
656 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
657 /// not available , use
658 /// the type's `ToString` implementation. In weird cases it could lead to types
659 /// with invalid `'_`
660 /// lifetime, but it should be rare.
661 fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
662 let seg = last_path_segment(path);
664 if let Some(ref params) = seg.args;
665 if !params.parenthesized;
666 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
667 GenericArg::Type(ty) => Some(ty),
670 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
672 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
676 to_ref_ty.to_string()
679 // check if the component types of the transmuted collection and the result have different ABI,
681 fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
682 let empty_param_env = ty::ParamEnv::empty();
683 // check if `from` and `to` are normalizable to avoid ICE (#4968)
684 if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
687 let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
688 let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
689 if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
690 from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
692 // no idea about layout, so don't lint
697 /// Check if the the type conversion can be expressed as a pointer cast, instead of a transmute.
698 fn can_be_expressed_as_pointer_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool {
701 check_cast(cx, e, from_ty, to_ty),
713 /// If a cast from from_ty to to_ty is valid, returns an Ok containing the kind of the cast.
714 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
715 let hir_id = e.hir_id;
716 let local_def_id = hir_id.owner;
718 Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
719 let fn_ctxt = FnCtxt::new(
725 // If we already have errors, we can't be sure we can pointer cast.
727 !fn_ctxt.errors_reported_since_creation(),
728 "Newly created FnCtxt contained errors"
731 if let Ok(check) = CastCheck::new(
736 // We won't show any error to the user, so we don't care what the span is here.
740 check.do_check(&fn_ctxt)
742 // do_check's documentation says that it might return Ok and create
743 // errors in the fcx instead of returing Err in some cases.
744 .filter(|_| !fn_ctxt.errors_reported_since_creation())