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