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