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