]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
transmute: avoid suggesting from/to bits in const
[rust.git] / clippy_lints / src / transmute.rs
1 use crate::utils::{
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,
4 };
5 use if_chain::if_chain;
6 use rustc_ast as ast;
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};
14 use std::borrow::Cow;
15
16 declare_clippy_lint! {
17     /// **What it does:** Checks for transmutes that can't ever be correct on any
18     /// architecture.
19     ///
20     /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
21     ///
22     /// **Known problems:** When accessing C, users might want to store pointer
23     /// sized objects in `extradata` arguments to save an allocation.
24     ///
25     /// **Example:**
26     /// ```ignore
27     /// let ptr: *const T = core::intrinsics::transmute('x')
28     /// ```
29     pub WRONG_TRANSMUTE,
30     correctness,
31     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
32 }
33
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.
38     ///
39     /// **Why is this bad?** Readability. The code tricks people into thinking that
40     /// something complex is going on.
41     ///
42     /// **Known problems:** None.
43     ///
44     /// **Example:**
45     /// ```rust,ignore
46     /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
47     /// ```
48     pub USELESS_TRANSMUTE,
49     nursery,
50     "transmutes that have the same to and from types or could be a cast/coercion"
51 }
52
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.
56     ///
57     /// **Why is this bad?** Readability. The code tricks people into thinking that
58     /// something complex is going on.
59     ///
60     /// **Known problems:** None.
61     ///
62     /// **Example:**
63     ///
64     /// ```rust
65     /// # let p: *const [i32] = &[];
66     /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
67     /// ```
68     /// Use instead:
69     /// ```rust
70     /// # let p: *const [i32] = &[];
71     /// p as *const [u16];
72     /// ```
73     pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
74     complexity,
75     "transmutes that could be a pointer cast"
76 }
77
78 declare_clippy_lint! {
79     /// **What it does:** Checks for transmutes between a type `T` and `*T`.
80     ///
81     /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
82     /// pointer to that type.
83     ///
84     /// **Known problems:** None.
85     ///
86     /// **Example:**
87     /// ```rust,ignore
88     /// core::intrinsics::transmute(t) // where the result type is the same as
89     ///                                // `*t` or `&t`'s
90     /// ```
91     pub CROSSPOINTER_TRANSMUTE,
92     complexity,
93     "transmutes that have to or from types that are a pointer to the other"
94 }
95
96 declare_clippy_lint! {
97     /// **What it does:** Checks for transmutes from a pointer to a reference.
98     ///
99     /// **Why is this bad?** This can always be rewritten with `&` and `*`.
100     ///
101     /// **Known problems:** None.
102     ///
103     /// **Example:**
104     /// ```rust,ignore
105     /// unsafe {
106     ///     let _: &T = std::mem::transmute(p); // where p: *const T
107     /// }
108     ///
109     /// // can be written:
110     /// let _: &T = &*p;
111     /// ```
112     pub TRANSMUTE_PTR_TO_REF,
113     complexity,
114     "transmutes from a pointer to a reference type"
115 }
116
117 declare_clippy_lint! {
118     /// **What it does:** Checks for transmutes from an integer to a `char`.
119     ///
120     /// **Why is this bad?** Not every integer is a Unicode scalar value.
121     ///
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`.
129     ///
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
132     ///
133     /// **Example:**
134     /// ```rust
135     /// let x = 1_u32;
136     /// unsafe {
137     ///     let _: char = std::mem::transmute(x); // where x: u32
138     /// }
139     ///
140     /// // should be:
141     /// let _ = std::char::from_u32(x).unwrap();
142     /// ```
143     pub TRANSMUTE_INT_TO_CHAR,
144     complexity,
145     "transmutes from an integer to a `char`"
146 }
147
148 declare_clippy_lint! {
149     /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
150     ///
151     /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
152     ///
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`.
160     ///
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
163     ///
164     /// **Example:**
165     /// ```rust
166     /// let b: &[u8] = &[1_u8, 2_u8];
167     /// unsafe {
168     ///     let _: &str = std::mem::transmute(b); // where b: &[u8]
169     /// }
170     ///
171     /// // should be:
172     /// let _ = std::str::from_utf8(b).unwrap();
173     /// ```
174     pub TRANSMUTE_BYTES_TO_STR,
175     complexity,
176     "transmutes from a `&[u8]` to a `&str`"
177 }
178
179 declare_clippy_lint! {
180     /// **What it does:** Checks for transmutes from an integer to a `bool`.
181     ///
182     /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
183     ///
184     /// **Known problems:** None.
185     ///
186     /// **Example:**
187     /// ```rust
188     /// let x = 1_u8;
189     /// unsafe {
190     ///     let _: bool = std::mem::transmute(x); // where x: u8
191     /// }
192     ///
193     /// // should be:
194     /// let _: bool = x != 0;
195     /// ```
196     pub TRANSMUTE_INT_TO_BOOL,
197     complexity,
198     "transmutes from an integer to a `bool`"
199 }
200
201 declare_clippy_lint! {
202     /// **What it does:** Checks for transmutes from an integer to a float.
203     ///
204     /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
205     /// and safe.
206     ///
207     /// **Known problems:** None.
208     ///
209     /// **Example:**
210     /// ```rust
211     /// unsafe {
212     ///     let _: f32 = std::mem::transmute(1_u32); // where x: u32
213     /// }
214     ///
215     /// // should be:
216     /// let _: f32 = f32::from_bits(1_u32);
217     /// ```
218     pub TRANSMUTE_INT_TO_FLOAT,
219     complexity,
220     "transmutes from an integer to a float"
221 }
222
223 declare_clippy_lint! {
224     /// **What it does:** Checks for transmutes from a float to an integer.
225     ///
226     /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
227     /// and safe.
228     ///
229     /// **Known problems:** None.
230     ///
231     /// **Example:**
232     /// ```rust
233     /// unsafe {
234     ///     let _: u32 = std::mem::transmute(1f32);
235     /// }
236     ///
237     /// // should be:
238     /// let _: u32 = 1f32.to_bits();
239     /// ```
240     pub TRANSMUTE_FLOAT_TO_INT,
241     complexity,
242     "transmutes from a float to an integer"
243 }
244
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.
248     ///
249     /// **Why is this bad?** Transmutes are dangerous, and these can instead be
250     /// written as casts.
251     ///
252     /// **Known problems:** None.
253     ///
254     /// **Example:**
255     /// ```rust
256     /// let ptr = &1u32 as *const u32;
257     /// unsafe {
258     ///     // pointer-to-pointer transmute
259     ///     let _: *const f32 = std::mem::transmute(ptr);
260     ///     // ref-ref transmute
261     ///     let _: &f32 = std::mem::transmute(&1u32);
262     /// }
263     /// // These can be respectively written:
264     /// let _ = ptr as *const f32;
265     /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
266     /// ```
267     pub TRANSMUTE_PTR_TO_PTR,
268     complexity,
269     "transmutes from a pointer to a pointer / a reference to a reference"
270 }
271
272 declare_clippy_lint! {
273     /// **What it does:** Checks for transmutes between collections whose
274     /// types have different ABI, size or alignment.
275     ///
276     /// **Why is this bad?** This is undefined behavior.
277     ///
278     /// **Known problems:** Currently, we cannot know whether a type is a
279     /// collection, so we just lint the ones that come with `std`.
280     ///
281     /// **Example:**
282     /// ```rust
283     /// // different size, therefore likely out-of-bounds memory access
284     /// // You absolutely do not want this in your code!
285     /// unsafe {
286     ///     std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
287     /// };
288     /// ```
289     ///
290     /// You must always iterate, map and collect the values:
291     ///
292     /// ```rust
293     /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
294     /// ```
295     pub UNSOUND_COLLECTION_TRANSMUTE,
296     correctness,
297     "transmute between collections of layout-incompatible types"
298 }
299
300 declare_lint_pass!(Transmute => [
301     CROSSPOINTER_TRANSMUTE,
302     TRANSMUTE_PTR_TO_REF,
303     TRANSMUTE_PTR_TO_PTR,
304     USELESS_TRANSMUTE,
305     WRONG_TRANSMUTE,
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,
313 ]);
314
315 // used to check for UNSOUND_COLLECTION_TRANSMUTE
316 static COLLECTIONS: &[&[&str]] = &[
317     &paths::VEC,
318     &paths::VEC_DEQUE,
319     &paths::BINARY_HEAP,
320     &paths::BTREESET,
321     &paths::BTREEMAP,
322     &paths::HASHSET,
323     &paths::HASHMAP,
324 ];
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<'_>) {
328         if_chain! {
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);
333             then {
334                 // Avoid suggesting f32::(from|to)_bits in const contexts.
335                 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
336                 let const_context = in_constant(cx, e.hir_id);
337
338                 let from_ty = cx.typeck_results().expr_ty(&args[0]);
339                 let to_ty = cx.typeck_results().expr_ty(e);
340
341                 match (&from_ty.kind, &to_ty.kind) {
342                     _ if from_ty == to_ty => span_lint(
343                         cx,
344                         USELESS_TRANSMUTE,
345                         e.span,
346                         &format!("transmute from a type (`{}`) to itself", from_ty),
347                     ),
348                     (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
349                         cx,
350                         USELESS_TRANSMUTE,
351                         e.span,
352                         "transmute from a reference to a pointer",
353                         |diag| {
354                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
355                                 let rty_and_mut = ty::TypeAndMut {
356                                     ty: rty,
357                                     mutbl: *rty_mutbl,
358                                 };
359
360                                 let sugg = if *ptr_ty == rty_and_mut {
361                                     arg.as_ty(to_ty)
362                                 } else {
363                                     arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
364                                 };
365
366                                 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
367                             }
368                         },
369                     ),
370                     (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
371                         cx,
372                         USELESS_TRANSMUTE,
373                         e.span,
374                         "transmute from an integer to a pointer",
375                         |diag| {
376                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
377                                 diag.span_suggestion(
378                                     e.span,
379                                     "try",
380                                     arg.as_ty(&to_ty.to_string()).to_string(),
381                                     Applicability::Unspecified,
382                                 );
383                             }
384                         },
385                     ),
386                     (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
387                         cx,
388                         WRONG_TRANSMUTE,
389                         e.span,
390                         &format!("transmute from a `{}` to a pointer", from_ty),
391                     ),
392                     (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
393                         cx,
394                         CROSSPOINTER_TRANSMUTE,
395                         e.span,
396                         &format!(
397                             "transmute from a type (`{}`) to the type that it points to (`{}`)",
398                             from_ty, to_ty
399                         ),
400                     ),
401                     (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
402                         cx,
403                         CROSSPOINTER_TRANSMUTE,
404                         e.span,
405                         &format!(
406                             "transmute from a type (`{}`) to a pointer to that type (`{}`)",
407                             from_ty, to_ty
408                         ),
409                     ),
410                     (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
411                         cx,
412                         TRANSMUTE_PTR_TO_REF,
413                         e.span,
414                         &format!(
415                             "transmute from a pointer type (`{}`) to a reference type \
416                              (`{}`)",
417                             from_ty, to_ty
418                         ),
419                         |diag| {
420                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
421                             let (deref, cast) = if *mutbl == Mutability::Mut {
422                                 ("&mut *", "*mut")
423                             } else {
424                                 ("&*", "*const")
425                             };
426
427                             let arg = if from_pty.ty == *to_ref_ty {
428                                 arg
429                             } else {
430                                 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
431                             };
432
433                             diag.span_suggestion(
434                                 e.span,
435                                 "try",
436                                 sugg::make_unop(deref, arg).to_string(),
437                                 Applicability::Unspecified,
438                             );
439                         },
440                     ),
441                     (ty::Int(ast::IntTy::I32) | ty::Uint(ast::UintTy::U32), &ty::Char) => {
442                         span_lint_and_then(
443                             cx,
444                             TRANSMUTE_INT_TO_CHAR,
445                             e.span,
446                             &format!("transmute from a `{}` to a `char`", from_ty),
447                             |diag| {
448                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
449                                 let arg = if let ty::Int(_) = from_ty.kind {
450                                     arg.as_ty(ast::UintTy::U32.name_str())
451                                 } else {
452                                     arg
453                                 };
454                                 diag.span_suggestion(
455                                     e.span,
456                                     "consider using",
457                                     format!("std::char::from_u32({}).unwrap()", arg.to_string()),
458                                     Applicability::Unspecified,
459                                 );
460                             },
461                         )
462                     },
463                     (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
464                         if_chain! {
465                             if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind, &ty_to.kind);
466                             if let ty::Uint(ast::UintTy::U8) = slice_ty.kind;
467                             if from_mutbl == to_mutbl;
468                             then {
469                                 let postfix = if *from_mutbl == Mutability::Mut {
470                                     "_mut"
471                                 } else {
472                                     ""
473                                 };
474
475                                 span_lint_and_sugg(
476                                     cx,
477                                     TRANSMUTE_BYTES_TO_STR,
478                                     e.span,
479                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
480                                     "consider using",
481                                     format!(
482                                         "std::str::from_utf8{}({}).unwrap()",
483                                         postfix,
484                                         snippet(cx, args[0].span, ".."),
485                                     ),
486                                     Applicability::Unspecified,
487                                 );
488                             } else {
489                                 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
490                                     span_lint_and_then(
491                                         cx,
492                                         TRANSMUTE_PTR_TO_PTR,
493                                         e.span,
494                                         "transmute from a reference to a reference",
495                                         |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
496                                             let ty_from_and_mut = ty::TypeAndMut {
497                                                 ty: ty_from,
498                                                 mutbl: *from_mutbl
499                                             };
500                                             let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
501                                             let sugg_paren = arg
502                                                 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
503                                                 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
504                                             let sugg = if *to_mutbl == Mutability::Mut {
505                                                 sugg_paren.mut_addr_deref()
506                                             } else {
507                                                 sugg_paren.addr_deref()
508                                             };
509                                             diag.span_suggestion(
510                                                 e.span,
511                                                 "try",
512                                                 sugg.to_string(),
513                                                 Applicability::Unspecified,
514                                             );
515                                         },
516                                     )
517                                 }
518                             }
519                         }
520                     },
521                     (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
522                         cx,
523                         TRANSMUTE_PTR_TO_PTR,
524                         e.span,
525                         "transmute from a pointer to a pointer",
526                         |diag| {
527                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
528                                 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
529                                 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
530                             }
531                         },
532                     ),
533                     (ty::Int(ast::IntTy::I8) | ty::Uint(ast::UintTy::U8), ty::Bool) => {
534                         span_lint_and_then(
535                             cx,
536                             TRANSMUTE_INT_TO_BOOL,
537                             e.span,
538                             &format!("transmute from a `{}` to a `bool`", from_ty),
539                             |diag| {
540                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
541                                 let zero = sugg::Sugg::NonParen(Cow::from("0"));
542                                 diag.span_suggestion(
543                                     e.span,
544                                     "consider using",
545                                     sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
546                                     Applicability::Unspecified,
547                                 );
548                             },
549                         )
550                     },
551                     (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
552                         cx,
553                         TRANSMUTE_INT_TO_FLOAT,
554                         e.span,
555                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
556                         |diag| {
557                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
558                             let arg = if let ty::Int(int_ty) = from_ty.kind {
559                                 arg.as_ty(format!(
560                                     "u{}",
561                                     int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
562                                 ))
563                             } else {
564                                 arg
565                             };
566                             diag.span_suggestion(
567                                 e.span,
568                                 "consider using",
569                                 format!("{}::from_bits({})", to_ty, arg.to_string()),
570                                 Applicability::Unspecified,
571                             );
572                         },
573                     ),
574                     (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
575                         cx,
576                         TRANSMUTE_FLOAT_TO_INT,
577                         e.span,
578                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
579                         |diag| {
580                             let mut expr = &args[0];
581                             let mut arg = sugg::Sugg::hir(cx, expr, "..");
582
583                             if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
584                                 expr = &inner_expr;
585                             }
586
587                             if_chain! {
588                                 // if the expression is a float literal and it is unsuffixed then
589                                 // add a suffix so the suggestion is valid and unambiguous
590                                 let op = format!("{}{}", arg, float_ty.name_str()).into();
591                                 if let ExprKind::Lit(lit) = &expr.kind;
592                                 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
593                                 then {
594                                     match arg {
595                                         sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
596                                         _ => arg = sugg::Sugg::NonParen(op)
597                                     }
598                                 }
599                             }
600
601                             arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
602
603                             // cast the result of `to_bits` if `to_ty` is signed
604                             arg = if let ty::Int(int_ty) = to_ty.kind {
605                                 arg.as_ty(int_ty.name_str().to_string())
606                             } else {
607                                 arg
608                             };
609
610                             diag.span_suggestion(
611                                 e.span,
612                                 "consider using",
613                                 arg.to_string(),
614                                 Applicability::Unspecified,
615                             );
616                         },
617                     ),
618                     (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
619                         if from_adt.did != to_adt.did ||
620                                 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
621                             return;
622                         }
623                         if from_substs.types().zip(to_substs.types())
624                                               .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
625                             span_lint(
626                                 cx,
627                                 UNSOUND_COLLECTION_TRANSMUTE,
628                                 e.span,
629                                 &format!(
630                                     "transmute from `{}` to `{}` with mismatched layout is unsound",
631                                     from_ty,
632                                     to_ty
633                                 )
634                             );
635                         }
636                     },
637                     (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
638                         cx,
639                         TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
640                         e.span,
641                         &format!(
642                             "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
643                             from_ty,
644                             to_ty
645                         ),
646                         |diag| {
647                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
648                                 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
649                                 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);
650                             }
651                         }
652                     ),
653                     _ => {
654                         return;
655                     },
656                 }
657             }
658         }
659     }
660 }
661
662 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
663 /// not available , use
664 /// the type's `ToString` implementation. In weird cases it could lead to types
665 /// with invalid `'_`
666 /// lifetime, but it should be rare.
667 fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
668     let seg = last_path_segment(path);
669     if_chain! {
670         if let Some(ref params) = seg.args;
671         if !params.parenthesized;
672         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
673             GenericArg::Type(ty) => Some(ty),
674             _ => None,
675         }).nth(1);
676         if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
677         then {
678             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
679         }
680     }
681
682     to_ref_ty.to_string()
683 }
684
685 // check if the component types of the transmuted collection and the result have different ABI,
686 // size or alignment
687 fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
688     let empty_param_env = ty::ParamEnv::empty();
689     // check if `from` and `to` are normalizable to avoid ICE (#4968)
690     if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
691         return false;
692     }
693     let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
694     let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
695     if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
696         from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
697     } else {
698         // no idea about layout, so don't lint
699         false
700     }
701 }
702
703 /// Check if the type conversion can be expressed as a pointer cast, instead of
704 /// a transmute. In certain cases, including some invalid casts from array
705 /// references to pointers, this may cause additional errors to be emitted and/or
706 /// ICE error messages. This function will panic if that occurs.
707 fn can_be_expressed_as_pointer_cast<'tcx>(
708     cx: &LateContext<'tcx>,
709     e: &'tcx Expr<'_>,
710     from_ty: Ty<'tcx>,
711     to_ty: Ty<'tcx>,
712 ) -> bool {
713     use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
714     matches!(
715         check_cast(cx, e, from_ty, to_ty),
716         Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
717     )
718 }
719
720 /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
721 /// the cast. In certain cases, including some invalid casts from array references
722 /// to pointers, this may cause additional errors to be emitted and/or ICE error
723 /// messages. This function will panic if that occurs.
724 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
725     let hir_id = e.hir_id;
726     let local_def_id = hir_id.owner;
727
728     Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
729         let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id);
730
731         // If we already have errors, we can't be sure we can pointer cast.
732         assert!(
733             !fn_ctxt.errors_reported_since_creation(),
734             "Newly created FnCtxt contained errors"
735         );
736
737         if let Ok(check) = CastCheck::new(
738             &fn_ctxt, e, from_ty, to_ty,
739             // We won't show any error to the user, so we don't care what the span is here.
740             DUMMY_SP, DUMMY_SP,
741         ) {
742             let res = check.do_check(&fn_ctxt);
743
744             // do_check's documentation says that it might return Ok and create
745             // errors in the fcx instead of returing Err in some cases. Those cases
746             // should be filtered out before getting here.
747             assert!(
748                 !fn_ctxt.errors_reported_since_creation(),
749                 "`fn_ctxt` contained errors after cast check!"
750             );
751
752             res.ok()
753         } else {
754             None
755         }
756     })
757 }