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