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