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