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