]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
Merge commit '5034d47f721ff4c3a3ff2aca9ef2ef3e1d067f9f' into clippyup
[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 from/to bits and dereferencing raw pointers in const contexts.
335                 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
336                 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
337                 let const_context = in_constant(cx, e.hir_id);
338
339                 let from_ty = cx.typeck_results().expr_ty(&args[0]);
340                 let to_ty = cx.typeck_results().expr_ty(e);
341
342                 match (&from_ty.kind(), &to_ty.kind()) {
343                     _ if from_ty == to_ty => span_lint(
344                         cx,
345                         USELESS_TRANSMUTE,
346                         e.span,
347                         &format!("transmute from a type (`{}`) to itself", from_ty),
348                     ),
349                     (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
350                         cx,
351                         USELESS_TRANSMUTE,
352                         e.span,
353                         "transmute from a reference to a pointer",
354                         |diag| {
355                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
356                                 let rty_and_mut = ty::TypeAndMut {
357                                     ty: rty,
358                                     mutbl: *rty_mutbl,
359                                 };
360
361                                 let sugg = if *ptr_ty == rty_and_mut {
362                                     arg.as_ty(to_ty)
363                                 } else {
364                                     arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
365                                 };
366
367                                 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
368                             }
369                         },
370                     ),
371                     (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
372                         cx,
373                         USELESS_TRANSMUTE,
374                         e.span,
375                         "transmute from an integer to a pointer",
376                         |diag| {
377                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
378                                 diag.span_suggestion(
379                                     e.span,
380                                     "try",
381                                     arg.as_ty(&to_ty.to_string()).to_string(),
382                                     Applicability::Unspecified,
383                                 );
384                             }
385                         },
386                     ),
387                     (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
388                         cx,
389                         WRONG_TRANSMUTE,
390                         e.span,
391                         &format!("transmute from a `{}` to a pointer", from_ty),
392                     ),
393                     (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
394                         cx,
395                         CROSSPOINTER_TRANSMUTE,
396                         e.span,
397                         &format!(
398                             "transmute from a type (`{}`) to the type that it points to (`{}`)",
399                             from_ty, to_ty
400                         ),
401                     ),
402                     (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
403                         cx,
404                         CROSSPOINTER_TRANSMUTE,
405                         e.span,
406                         &format!(
407                             "transmute from a type (`{}`) to a pointer to that type (`{}`)",
408                             from_ty, to_ty
409                         ),
410                     ),
411                     (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
412                         cx,
413                         TRANSMUTE_PTR_TO_REF,
414                         e.span,
415                         &format!(
416                             "transmute from a pointer type (`{}`) to a reference type \
417                              (`{}`)",
418                             from_ty, to_ty
419                         ),
420                         |diag| {
421                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
422                             let (deref, cast) = if *mutbl == Mutability::Mut {
423                                 ("&mut *", "*mut")
424                             } else {
425                                 ("&*", "*const")
426                             };
427
428                             let arg = if from_pty.ty == *to_ref_ty {
429                                 arg
430                             } else {
431                                 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
432                             };
433
434                             diag.span_suggestion(
435                                 e.span,
436                                 "try",
437                                 sugg::make_unop(deref, arg).to_string(),
438                                 Applicability::Unspecified,
439                             );
440                         },
441                     ),
442                     (ty::Int(ast::IntTy::I32) | ty::Uint(ast::UintTy::U32), &ty::Char) => {
443                         span_lint_and_then(
444                             cx,
445                             TRANSMUTE_INT_TO_CHAR,
446                             e.span,
447                             &format!("transmute from a `{}` to a `char`", from_ty),
448                             |diag| {
449                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
450                                 let arg = if let ty::Int(_) = from_ty.kind() {
451                                     arg.as_ty(ast::UintTy::U32.name_str())
452                                 } else {
453                                     arg
454                                 };
455                                 diag.span_suggestion(
456                                     e.span,
457                                     "consider using",
458                                     format!("std::char::from_u32({}).unwrap()", arg.to_string()),
459                                     Applicability::Unspecified,
460                                 );
461                             },
462                         )
463                     },
464                     (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
465                         if_chain! {
466                             if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
467                             if let ty::Uint(ast::UintTy::U8) = slice_ty.kind();
468                             if from_mutbl == to_mutbl;
469                             then {
470                                 let postfix = if *from_mutbl == Mutability::Mut {
471                                     "_mut"
472                                 } else {
473                                     ""
474                                 };
475
476                                 span_lint_and_sugg(
477                                     cx,
478                                     TRANSMUTE_BYTES_TO_STR,
479                                     e.span,
480                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
481                                     "consider using",
482                                     format!(
483                                         "std::str::from_utf8{}({}).unwrap()",
484                                         postfix,
485                                         snippet(cx, args[0].span, ".."),
486                                     ),
487                                     Applicability::Unspecified,
488                                 );
489                             } else {
490                                 if (cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty))
491                                     && !const_context {
492                                     span_lint_and_then(
493                                         cx,
494                                         TRANSMUTE_PTR_TO_PTR,
495                                         e.span,
496                                         "transmute from a reference to a reference",
497                                         |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
498                                             let ty_from_and_mut = ty::TypeAndMut {
499                                                 ty: ty_from,
500                                                 mutbl: *from_mutbl
501                                             };
502                                             let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
503                                             let sugg_paren = arg
504                                                 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
505                                                 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
506                                             let sugg = if *to_mutbl == Mutability::Mut {
507                                                 sugg_paren.mut_addr_deref()
508                                             } else {
509                                                 sugg_paren.addr_deref()
510                                             };
511                                             diag.span_suggestion(
512                                                 e.span,
513                                                 "try",
514                                                 sugg.to_string(),
515                                                 Applicability::Unspecified,
516                                             );
517                                         },
518                                     )
519                                 }
520                             }
521                         }
522                     },
523                     (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
524                         cx,
525                         TRANSMUTE_PTR_TO_PTR,
526                         e.span,
527                         "transmute from a pointer to a pointer",
528                         |diag| {
529                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
530                                 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
531                                 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
532                             }
533                         },
534                     ),
535                     (ty::Int(ast::IntTy::I8) | ty::Uint(ast::UintTy::U8), ty::Bool) => {
536                         span_lint_and_then(
537                             cx,
538                             TRANSMUTE_INT_TO_BOOL,
539                             e.span,
540                             &format!("transmute from a `{}` to a `bool`", from_ty),
541                             |diag| {
542                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
543                                 let zero = sugg::Sugg::NonParen(Cow::from("0"));
544                                 diag.span_suggestion(
545                                     e.span,
546                                     "consider using",
547                                     sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
548                                     Applicability::Unspecified,
549                                 );
550                             },
551                         )
552                     },
553                     (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
554                         cx,
555                         TRANSMUTE_INT_TO_FLOAT,
556                         e.span,
557                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
558                         |diag| {
559                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
560                             let arg = if let ty::Int(int_ty) = from_ty.kind() {
561                                 arg.as_ty(format!(
562                                     "u{}",
563                                     int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
564                                 ))
565                             } else {
566                                 arg
567                             };
568                             diag.span_suggestion(
569                                 e.span,
570                                 "consider using",
571                                 format!("{}::from_bits({})", to_ty, arg.to_string()),
572                                 Applicability::Unspecified,
573                             );
574                         },
575                     ),
576                     (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
577                         cx,
578                         TRANSMUTE_FLOAT_TO_INT,
579                         e.span,
580                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
581                         |diag| {
582                             let mut expr = &args[0];
583                             let mut arg = sugg::Sugg::hir(cx, expr, "..");
584
585                             if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
586                                 expr = &inner_expr;
587                             }
588
589                             if_chain! {
590                                 // if the expression is a float literal and it is unsuffixed then
591                                 // add a suffix so the suggestion is valid and unambiguous
592                                 let op = format!("{}{}", arg, float_ty.name_str()).into();
593                                 if let ExprKind::Lit(lit) = &expr.kind;
594                                 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
595                                 then {
596                                     match arg {
597                                         sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
598                                         _ => arg = sugg::Sugg::NonParen(op)
599                                     }
600                                 }
601                             }
602
603                             arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
604
605                             // cast the result of `to_bits` if `to_ty` is signed
606                             arg = if let ty::Int(int_ty) = to_ty.kind() {
607                                 arg.as_ty(int_ty.name_str().to_string())
608                             } else {
609                                 arg
610                             };
611
612                             diag.span_suggestion(
613                                 e.span,
614                                 "consider using",
615                                 arg.to_string(),
616                                 Applicability::Unspecified,
617                             );
618                         },
619                     ),
620                     (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
621                         if from_adt.did != to_adt.did ||
622                                 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
623                             return;
624                         }
625                         if from_substs.types().zip(to_substs.types())
626                                               .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
627                             span_lint(
628                                 cx,
629                                 UNSOUND_COLLECTION_TRANSMUTE,
630                                 e.span,
631                                 &format!(
632                                     "transmute from `{}` to `{}` with mismatched layout is unsound",
633                                     from_ty,
634                                     to_ty
635                                 )
636                             );
637                         }
638                     },
639                     (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
640                         cx,
641                         TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
642                         e.span,
643                         &format!(
644                             "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
645                             from_ty,
646                             to_ty
647                         ),
648                         |diag| {
649                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
650                                 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
651                                 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);
652                             }
653                         }
654                     ),
655                     _ => {
656                         return;
657                     },
658                 }
659             }
660         }
661     }
662 }
663
664 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
665 /// not available , use
666 /// the type's `ToString` implementation. In weird cases it could lead to types
667 /// with invalid `'_`
668 /// lifetime, but it should be rare.
669 fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
670     let seg = last_path_segment(path);
671     if_chain! {
672         if let Some(ref params) = seg.args;
673         if !params.parenthesized;
674         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
675             GenericArg::Type(ty) => Some(ty),
676             _ => None,
677         }).nth(1);
678         if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
679         then {
680             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
681         }
682     }
683
684     to_ref_ty.to_string()
685 }
686
687 // check if the component types of the transmuted collection and the result have different ABI,
688 // size or alignment
689 fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
690     let empty_param_env = ty::ParamEnv::empty();
691     // check if `from` and `to` are normalizable to avoid ICE (#4968)
692     if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
693         return false;
694     }
695     let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
696     let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
697     if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
698         from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
699     } else {
700         // no idea about layout, so don't lint
701         false
702     }
703 }
704
705 /// Check if the type conversion can be expressed as a pointer cast, instead of
706 /// a transmute. In certain cases, including some invalid casts from array
707 /// references to pointers, this may cause additional errors to be emitted and/or
708 /// ICE error messages. This function will panic if that occurs.
709 fn can_be_expressed_as_pointer_cast<'tcx>(
710     cx: &LateContext<'tcx>,
711     e: &'tcx Expr<'_>,
712     from_ty: Ty<'tcx>,
713     to_ty: Ty<'tcx>,
714 ) -> bool {
715     use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
716     matches!(
717         check_cast(cx, e, from_ty, to_ty),
718         Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
719     )
720 }
721
722 /// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
723 /// the cast. In certain cases, including some invalid casts from array references
724 /// to pointers, this may cause additional errors to be emitted and/or ICE error
725 /// messages. This function will panic if that occurs.
726 fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option<CastKind> {
727     let hir_id = e.hir_id;
728     let local_def_id = hir_id.owner;
729
730     Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
731         let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id);
732
733         // If we already have errors, we can't be sure we can pointer cast.
734         assert!(
735             !fn_ctxt.errors_reported_since_creation(),
736             "Newly created FnCtxt contained errors"
737         );
738
739         if let Ok(check) = CastCheck::new(
740             &fn_ctxt, e, from_ty, to_ty,
741             // We won't show any error to the user, so we don't care what the span is here.
742             DUMMY_SP, DUMMY_SP,
743         ) {
744             let res = check.do_check(&fn_ctxt);
745
746             // do_check's documentation says that it might return Ok and create
747             // errors in the fcx instead of returing Err in some cases. Those cases
748             // should be filtered out before getting here.
749             assert!(
750                 !fn_ctxt.errors_reported_since_creation(),
751                 "`fn_ctxt` contained errors after cast check!"
752             );
753
754             res.ok()
755         } else {
756             None
757         }
758     })
759 }