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