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