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