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