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