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