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