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