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