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