1 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then, sugg};
2 use if_chain::if_chain;
3 use rustc::declare_lint_pass;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty::{self, Ty};
7 use rustc_errors::Applicability;
8 use rustc_session::declare_tool_lint;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for transmutes that can't ever be correct on any
16 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
18 /// **Known problems:** When accessing C, users might want to store pointer
19 /// sized objects in `extradata` arguments to save an allocation.
23 /// let ptr: *const T = core::intrinsics::transmute('x')
27 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
30 declare_clippy_lint! {
31 /// **What it does:** Checks for transmutes to the original type of the object
32 /// and transmutes that could be a cast.
34 /// **Why is this bad?** Readability. The code tricks people into thinking that
35 /// something complex is going on.
37 /// **Known problems:** None.
41 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
43 pub USELESS_TRANSMUTE,
45 "transmutes that have the same to and from types or could be a cast/coercion"
48 declare_clippy_lint! {
49 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
51 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
52 /// pointer to that type.
54 /// **Known problems:** None.
58 /// core::intrinsics::transmute(t) // where the result type is the same as
61 pub CROSSPOINTER_TRANSMUTE,
63 "transmutes that have to or from types that are a pointer to the other"
66 declare_clippy_lint! {
67 /// **What it does:** Checks for transmutes from a pointer to a reference.
69 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
71 /// **Known problems:** None.
76 /// let _: &T = std::mem::transmute(p); // where p: *const T
79 /// // can be written:
82 pub TRANSMUTE_PTR_TO_REF,
84 "transmutes from a pointer to a reference type"
87 declare_clippy_lint! {
88 /// **What it does:** Checks for transmutes from an integer to a `char`.
90 /// **Why is this bad?** Not every integer is a Unicode scalar value.
92 /// **Known problems:**
93 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
94 /// as it needs to validate the input.
95 /// If you are certain that the input is always a valid Unicode scalar value,
96 /// use [`from_u32_unchecked`] which is as fast as `transmute`
97 /// but has a semantically meaningful name.
98 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
100 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
101 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
107 /// let _: char = std::mem::transmute(x); // where x: u32
111 /// let _ = std::char::from_u32(x).unwrap();
113 pub TRANSMUTE_INT_TO_CHAR,
115 "transmutes from an integer to a `char`"
118 declare_clippy_lint! {
119 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
121 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
123 /// **Known problems:**
124 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
125 /// as it needs to validate the input.
126 /// If you are certain that the input is always a valid UTF-8,
127 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
128 /// but has a semantically meaningful name.
129 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
131 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
132 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
136 /// let b: &[u8] = &[1_u8, 2_u8];
138 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
142 /// let _ = std::str::from_utf8(b).unwrap();
144 pub TRANSMUTE_BYTES_TO_STR,
146 "transmutes from a `&[u8]` to a `&str`"
149 declare_clippy_lint! {
150 /// **What it does:** Checks for transmutes from an integer to a `bool`.
152 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
154 /// **Known problems:** None.
160 /// let _: bool = std::mem::transmute(x); // where x: u8
164 /// let _: bool = x != 0;
166 pub TRANSMUTE_INT_TO_BOOL,
168 "transmutes from an integer to a `bool`"
171 declare_clippy_lint! {
172 /// **What it does:** Checks for transmutes from an integer to a float.
174 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
177 /// **Known problems:** None.
182 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
186 /// let _: f32 = f32::from_bits(1_u32);
188 pub TRANSMUTE_INT_TO_FLOAT,
190 "transmutes from an integer to a float"
193 declare_clippy_lint! {
194 /// **What it does:** Checks for transmutes from a float to an integer.
196 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
199 /// **Known problems:** None.
204 /// let _: u32 = std::mem::transmute(1f32);
208 /// let _: u32 = 1f32.to_bits();
210 pub TRANSMUTE_FLOAT_TO_INT,
212 "transmutes from a float to an integer"
215 declare_clippy_lint! {
216 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
217 /// from a reference to a reference.
219 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
220 /// written as casts.
222 /// **Known problems:** None.
226 /// let ptr = &1u32 as *const u32;
228 /// // pointer-to-pointer transmute
229 /// let _: *const f32 = std::mem::transmute(ptr);
230 /// // ref-ref transmute
231 /// let _: &f32 = std::mem::transmute(&1u32);
233 /// // These can be respectively written:
234 /// let _ = ptr as *const f32;
235 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
237 pub TRANSMUTE_PTR_TO_PTR,
239 "transmutes from a pointer to a pointer / a reference to a reference"
242 declare_clippy_lint! {
243 /// **What it does:** Checks for transmutes between collections whose
244 /// types have different ABI, size or alignment.
246 /// **Why is this bad?** This is undefined behavior.
248 /// **Known problems:** Currently, we cannot know whether a type is a
249 /// collection, so we just lint the ones that come with `std`.
253 /// // different size, therefore likely out-of-bounds memory access
254 /// // You absolutely do not want this in your code!
256 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
260 /// You must always iterate, map and collect the values:
263 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
265 pub UNSOUND_COLLECTION_TRANSMUTE,
267 "transmute between collections of layout-incompatible types"
269 declare_lint_pass!(Transmute => [
270 CROSSPOINTER_TRANSMUTE,
271 TRANSMUTE_PTR_TO_REF,
272 TRANSMUTE_PTR_TO_PTR,
275 TRANSMUTE_INT_TO_CHAR,
276 TRANSMUTE_BYTES_TO_STR,
277 TRANSMUTE_INT_TO_BOOL,
278 TRANSMUTE_INT_TO_FLOAT,
279 TRANSMUTE_FLOAT_TO_INT,
280 UNSOUND_COLLECTION_TRANSMUTE,
283 // used to check for UNSOUND_COLLECTION_TRANSMUTE
284 static COLLECTIONS: &[&[&str]] = &[
293 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
294 #[allow(clippy::similar_names, clippy::too_many_lines)]
295 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
297 if let ExprKind::Call(ref path_expr, ref args) = e.kind;
298 if let ExprKind::Path(ref qpath) = path_expr.kind;
299 if let Some(def_id) = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id();
300 if match_def_path(cx, def_id, &paths::TRANSMUTE);
302 let from_ty = cx.tables.expr_ty(&args[0]);
303 let to_ty = cx.tables.expr_ty(e);
305 match (&from_ty.kind, &to_ty.kind) {
306 _ if from_ty == to_ty => span_lint(
310 &format!("transmute from a type (`{}`) to itself", from_ty),
312 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
316 "transmute from a reference to a pointer",
318 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
319 let rty_and_mut = ty::TypeAndMut {
324 let sugg = if ptr_ty == rty_and_mut {
327 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
330 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
334 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
338 "transmute from an integer to a pointer",
340 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
344 arg.as_ty(&to_ty.to_string()).to_string(),
345 Applicability::Unspecified,
350 (&ty::Float(_), &ty::Ref(..))
351 | (&ty::Float(_), &ty::RawPtr(_))
352 | (&ty::Char, &ty::Ref(..))
353 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
357 &format!("transmute from a `{}` to a pointer", from_ty),
359 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
361 CROSSPOINTER_TRANSMUTE,
364 "transmute from a type (`{}`) to the type that it points to (`{}`)",
368 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
370 CROSSPOINTER_TRANSMUTE,
373 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
377 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
379 TRANSMUTE_PTR_TO_REF,
382 "transmute from a pointer type (`{}`) to a reference type \
387 let arg = sugg::Sugg::hir(cx, &args[0], "..");
388 let (deref, cast) = if mutbl == Mutability::Mutable {
394 let arg = if from_pty.ty == to_ref_ty {
397 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
403 sugg::make_unop(deref, arg).to_string(),
404 Applicability::Unspecified,
408 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
411 TRANSMUTE_INT_TO_CHAR,
413 &format!("transmute from a `{}` to a `char`", from_ty),
415 let arg = sugg::Sugg::hir(cx, &args[0], "..");
416 let arg = if let ty::Int(_) = from_ty.kind {
417 arg.as_ty(ast::UintTy::U32.name_str())
424 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
425 Applicability::Unspecified,
430 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
432 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind, &ty_to.kind);
433 if let ty::Uint(ast::UintTy::U8) = slice_ty.kind;
434 if from_mutbl == to_mutbl;
436 let postfix = if from_mutbl == Mutability::Mutable {
444 TRANSMUTE_BYTES_TO_STR,
446 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
452 "std::str::from_utf8{}({}).unwrap()",
454 snippet(cx, args[0].span, ".."),
456 Applicability::Unspecified,
461 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
464 TRANSMUTE_PTR_TO_PTR,
466 "transmute from a reference to a reference",
467 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
468 let ty_from_and_mut = ty::TypeAndMut {
472 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
474 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
475 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
476 let sugg = if to_mutbl == Mutability::Mutable {
477 sugg_paren.mut_addr_deref()
479 sugg_paren.addr_deref()
485 Applicability::Unspecified,
493 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
495 TRANSMUTE_PTR_TO_PTR,
497 "transmute from a pointer to a pointer",
499 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
500 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
501 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
505 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
508 TRANSMUTE_INT_TO_BOOL,
510 &format!("transmute from a `{}` to a `bool`", from_ty),
512 let arg = sugg::Sugg::hir(cx, &args[0], "..");
513 let zero = sugg::Sugg::NonParen(Cow::from("0"));
517 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
518 Applicability::Unspecified,
523 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
525 TRANSMUTE_INT_TO_FLOAT,
527 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
529 let arg = sugg::Sugg::hir(cx, &args[0], "..");
530 let arg = if let ty::Int(int_ty) = from_ty.kind {
533 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
541 format!("{}::from_bits({})", to_ty, arg.to_string()),
542 Applicability::Unspecified,
546 (&ty::Float(float_ty), &ty::Int(_)) | (&ty::Float(float_ty), &ty::Uint(_)) => span_lint_and_then(
548 TRANSMUTE_FLOAT_TO_INT,
550 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
552 let mut expr = &args[0];
553 let mut arg = sugg::Sugg::hir(cx, expr, "..");
555 if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
560 // if the expression is a float literal and it is unsuffixed then
561 // add a suffix so the suggestion is valid and unambiguous
562 let op = format!("{}{}", arg, float_ty.name_str()).into();
563 if let ExprKind::Lit(lit) = &expr.kind;
564 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
567 sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
568 _ => arg = sugg::Sugg::NonParen(op)
573 arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
575 // cast the result of `to_bits` if `to_ty` is signed
576 arg = if let ty::Int(int_ty) = to_ty.kind {
577 arg.as_ty(int_ty.name_str().to_string())
586 Applicability::Unspecified,
590 (&ty::Adt(ref from_adt, ref from_substs), &ty::Adt(ref to_adt, ref to_substs)) => {
591 if from_adt.did != to_adt.did ||
592 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
595 if from_substs.types().zip(to_substs.types())
596 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
599 UNSOUND_COLLECTION_TRANSMUTE,
602 "transmute from `{}` to `{}` with mismatched layout is unsound",
616 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
617 /// not available , use
618 /// the type's `ToString` implementation. In weird cases it could lead to types
619 /// with invalid `'_`
620 /// lifetime, but it should be rare.
621 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
622 let seg = last_path_segment(path);
624 if let Some(ref params) = seg.args;
625 if !params.parenthesized;
626 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
627 GenericArg::Type(ty) => Some(ty),
630 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
632 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
636 to_ref_ty.to_string()
639 // check if the component types of the transmuted collection and the result have different ABI,
641 fn is_layout_incompatible<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
642 let from_ty_layout = cx.tcx.layout_of(ty::ParamEnv::empty().and(from));
643 let to_ty_layout = cx.tcx.layout_of(ty::ParamEnv::empty().and(to));
644 if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
645 from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
647 // no idea about layout, so don't lint