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