2 is_normalizable, last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then, sugg,
4 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind, GenericArg, Mutability, QPath, TyKind, UnOp};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::{self, Ty};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for transmutes that can't ever be correct on any
17 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
19 /// **Known problems:** When accessing C, users might want to store pointer
20 /// sized objects in `extradata` arguments to save an allocation.
24 /// let ptr: *const T = core::intrinsics::transmute('x')
28 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
31 // FIXME: Move this to `complexity` again, after #5343 is fixed
32 declare_clippy_lint! {
33 /// **What it does:** Checks for transmutes to the original type of the object
34 /// and transmutes that could be a cast.
36 /// **Why is this bad?** Readability. The code tricks people into thinking that
37 /// something complex is going on.
39 /// **Known problems:** None.
43 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
45 pub USELESS_TRANSMUTE,
47 "transmutes that have the same to and from types or could be a cast/coercion"
50 declare_clippy_lint! {
51 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
53 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
54 /// pointer to that type.
56 /// **Known problems:** None.
60 /// core::intrinsics::transmute(t) // where the result type is the same as
63 pub CROSSPOINTER_TRANSMUTE,
65 "transmutes that have to or from types that are a pointer to the other"
68 declare_clippy_lint! {
69 /// **What it does:** Checks for transmutes from a pointer to a reference.
71 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
73 /// **Known problems:** None.
78 /// let _: &T = std::mem::transmute(p); // where p: *const T
81 /// // can be written:
84 pub TRANSMUTE_PTR_TO_REF,
86 "transmutes from a pointer to a reference type"
89 declare_clippy_lint! {
90 /// **What it does:** Checks for transmutes from an integer to a `char`.
92 /// **Why is this bad?** Not every integer is a Unicode scalar value.
94 /// **Known problems:**
95 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
96 /// as it needs to validate the input.
97 /// If you are certain that the input is always a valid Unicode scalar value,
98 /// use [`from_u32_unchecked`] which is as fast as `transmute`
99 /// but has a semantically meaningful name.
100 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
102 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
103 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
109 /// let _: char = std::mem::transmute(x); // where x: u32
113 /// let _ = std::char::from_u32(x).unwrap();
115 pub TRANSMUTE_INT_TO_CHAR,
117 "transmutes from an integer to a `char`"
120 declare_clippy_lint! {
121 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
123 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
125 /// **Known problems:**
126 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
127 /// as it needs to validate the input.
128 /// If you are certain that the input is always a valid UTF-8,
129 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
130 /// but has a semantically meaningful name.
131 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
133 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
134 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
138 /// let b: &[u8] = &[1_u8, 2_u8];
140 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
144 /// let _ = std::str::from_utf8(b).unwrap();
146 pub TRANSMUTE_BYTES_TO_STR,
148 "transmutes from a `&[u8]` to a `&str`"
151 declare_clippy_lint! {
152 /// **What it does:** Checks for transmutes from an integer to a `bool`.
154 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
156 /// **Known problems:** None.
162 /// let _: bool = std::mem::transmute(x); // where x: u8
166 /// let _: bool = x != 0;
168 pub TRANSMUTE_INT_TO_BOOL,
170 "transmutes from an integer to a `bool`"
173 declare_clippy_lint! {
174 /// **What it does:** Checks for transmutes from an integer to a float.
176 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
179 /// **Known problems:** None.
184 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
188 /// let _: f32 = f32::from_bits(1_u32);
190 pub TRANSMUTE_INT_TO_FLOAT,
192 "transmutes from an integer to a float"
195 declare_clippy_lint! {
196 /// **What it does:** Checks for transmutes from a float to an integer.
198 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
201 /// **Known problems:** None.
206 /// let _: u32 = std::mem::transmute(1f32);
210 /// let _: u32 = 1f32.to_bits();
212 pub TRANSMUTE_FLOAT_TO_INT,
214 "transmutes from a float to an integer"
217 declare_clippy_lint! {
218 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
219 /// from a reference to a reference.
221 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
222 /// written as casts.
224 /// **Known problems:** None.
228 /// let ptr = &1u32 as *const u32;
230 /// // pointer-to-pointer transmute
231 /// let _: *const f32 = std::mem::transmute(ptr);
232 /// // ref-ref transmute
233 /// let _: &f32 = std::mem::transmute(&1u32);
235 /// // These can be respectively written:
236 /// let _ = ptr as *const f32;
237 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
239 pub TRANSMUTE_PTR_TO_PTR,
241 "transmutes from a pointer to a pointer / a reference to a reference"
244 declare_clippy_lint! {
245 /// **What it does:** Checks for transmutes between collections whose
246 /// types have different ABI, size or alignment.
248 /// **Why is this bad?** This is undefined behavior.
250 /// **Known problems:** Currently, we cannot know whether a type is a
251 /// collection, so we just lint the ones that come with `std`.
255 /// // different size, therefore likely out-of-bounds memory access
256 /// // You absolutely do not want this in your code!
258 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
262 /// You must always iterate, map and collect the values:
265 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
267 pub UNSOUND_COLLECTION_TRANSMUTE,
269 "transmute between collections of layout-incompatible types"
271 declare_lint_pass!(Transmute => [
272 CROSSPOINTER_TRANSMUTE,
273 TRANSMUTE_PTR_TO_REF,
274 TRANSMUTE_PTR_TO_PTR,
277 TRANSMUTE_INT_TO_CHAR,
278 TRANSMUTE_BYTES_TO_STR,
279 TRANSMUTE_INT_TO_BOOL,
280 TRANSMUTE_INT_TO_FLOAT,
281 TRANSMUTE_FLOAT_TO_INT,
282 UNSOUND_COLLECTION_TRANSMUTE,
285 // used to check for UNSOUND_COLLECTION_TRANSMUTE
286 static COLLECTIONS: &[&[&str]] = &[
295 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
296 #[allow(clippy::similar_names, clippy::too_many_lines)]
297 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
299 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
300 if let ExprKind::Path(ref qpath) = path_expr.kind;
301 if let Some(def_id) = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id();
302 if match_def_path(cx, def_id, &paths::TRANSMUTE);
304 let from_ty = cx.tables.expr_ty(&args[0]);
305 let to_ty = cx.tables.expr_ty(e);
307 match (&from_ty.kind, &to_ty.kind) {
308 _ if from_ty == to_ty => span_lint(
312 &format!("transmute from a type (`{}`) to itself", from_ty),
314 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
318 "transmute from a reference to a pointer",
320 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
321 let rty_and_mut = ty::TypeAndMut {
326 let sugg = if ptr_ty == rty_and_mut {
329 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
332 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
336 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
340 "transmute from an integer to a pointer",
342 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
346 arg.as_ty(&to_ty.to_string()).to_string(),
347 Applicability::Unspecified,
352 (&ty::Float(_), &ty::Ref(..))
353 | (&ty::Float(_), &ty::RawPtr(_))
354 | (&ty::Char, &ty::Ref(..))
355 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
359 &format!("transmute from a `{}` to a pointer", from_ty),
361 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
363 CROSSPOINTER_TRANSMUTE,
366 "transmute from a type (`{}`) to the type that it points to (`{}`)",
370 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
372 CROSSPOINTER_TRANSMUTE,
375 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
379 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
381 TRANSMUTE_PTR_TO_REF,
384 "transmute from a pointer type (`{}`) to a reference type \
389 let arg = sugg::Sugg::hir(cx, &args[0], "..");
390 let (deref, cast) = if mutbl == Mutability::Mut {
396 let arg = if from_pty.ty == to_ref_ty {
399 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
405 sugg::make_unop(deref, arg).to_string(),
406 Applicability::Unspecified,
410 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
413 TRANSMUTE_INT_TO_CHAR,
415 &format!("transmute from a `{}` to a `char`", from_ty),
417 let arg = sugg::Sugg::hir(cx, &args[0], "..");
418 let arg = if let ty::Int(_) = from_ty.kind {
419 arg.as_ty(ast::UintTy::U32.name_str())
426 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
427 Applicability::Unspecified,
432 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
434 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind, &ty_to.kind);
435 if let ty::Uint(ast::UintTy::U8) = slice_ty.kind;
436 if from_mutbl == to_mutbl;
438 let postfix = if from_mutbl == Mutability::Mut {
446 TRANSMUTE_BYTES_TO_STR,
448 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
454 "std::str::from_utf8{}({}).unwrap()",
456 snippet(cx, args[0].span, ".."),
458 Applicability::Unspecified,
463 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
466 TRANSMUTE_PTR_TO_PTR,
468 "transmute from a reference to a reference",
469 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
470 let ty_from_and_mut = ty::TypeAndMut {
474 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
476 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
477 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
478 let sugg = if to_mutbl == Mutability::Mut {
479 sugg_paren.mut_addr_deref()
481 sugg_paren.addr_deref()
487 Applicability::Unspecified,
495 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
497 TRANSMUTE_PTR_TO_PTR,
499 "transmute from a pointer to a pointer",
501 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
502 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
503 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
507 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
510 TRANSMUTE_INT_TO_BOOL,
512 &format!("transmute from a `{}` to a `bool`", from_ty),
514 let arg = sugg::Sugg::hir(cx, &args[0], "..");
515 let zero = sugg::Sugg::NonParen(Cow::from("0"));
519 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
520 Applicability::Unspecified,
525 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
527 TRANSMUTE_INT_TO_FLOAT,
529 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
531 let arg = sugg::Sugg::hir(cx, &args[0], "..");
532 let arg = if let ty::Int(int_ty) = from_ty.kind {
535 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
543 format!("{}::from_bits({})", to_ty, arg.to_string()),
544 Applicability::Unspecified,
548 (&ty::Float(float_ty), &ty::Int(_)) | (&ty::Float(float_ty), &ty::Uint(_)) => span_lint_and_then(
550 TRANSMUTE_FLOAT_TO_INT,
552 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
554 let mut expr = &args[0];
555 let mut arg = sugg::Sugg::hir(cx, expr, "..");
557 if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
562 // if the expression is a float literal and it is unsuffixed then
563 // add a suffix so the suggestion is valid and unambiguous
564 let op = format!("{}{}", arg, float_ty.name_str()).into();
565 if let ExprKind::Lit(lit) = &expr.kind;
566 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
569 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
570 _ => arg = sugg::Sugg::NonParen(op)
575 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
577 // cast the result of `to_bits` if `to_ty` is signed
578 arg = if let ty::Int(int_ty) = to_ty.kind {
579 arg.as_ty(int_ty.name_str().to_string())
588 Applicability::Unspecified,
592 (&ty::Adt(ref from_adt, ref from_substs), &ty::Adt(ref to_adt, ref to_substs)) => {
593 if from_adt.did != to_adt.did ||
594 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
597 if from_substs.types().zip(to_substs.types())
598 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
601 UNSOUND_COLLECTION_TRANSMUTE,
604 "transmute from `{}` to `{}` with mismatched layout is unsound",
618 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
619 /// not available , use
620 /// the type's `ToString` implementation. In weird cases it could lead to types
621 /// with invalid `'_`
622 /// lifetime, but it should be rare.
623 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
624 let seg = last_path_segment(path);
626 if let Some(ref params) = seg.args;
627 if !params.parenthesized;
628 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
629 GenericArg::Type(ty) => Some(ty),
632 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
634 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
638 to_ref_ty.to_string()
641 // check if the component types of the transmuted collection and the result have different ABI,
643 fn is_layout_incompatible<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
644 let empty_param_env = ty::ParamEnv::empty();
645 // check if `from` and `to` are normalizable to avoid ICE (#4968)
646 if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
649 let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
650 let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
651 if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
652 from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
654 // no idea about layout, so don't lint