]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/mod.rs
Auto merge of #86754 - estebank:use-multispans-more, r=varkor
[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 clippy_utils::in_constant;
16 use if_chain::if_chain;
17 use rustc_hir::{Expr, ExprKind};
18 use rustc_lint::{LateContext, LateLintPass};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use rustc_span::symbol::sym;
21
22 declare_clippy_lint! {
23     /// ### What it does
24     /// Checks for transmutes that can't ever be correct on any
25     /// architecture.
26     ///
27     /// ### Why is this bad?
28     /// It's basically guaranteed to be undefined behaviour.
29     ///
30     /// ### Known problems
31     /// 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
46     /// Checks for transmutes to the original type of the object
47     /// and transmutes that could be a cast.
48     ///
49     /// ### Why is this bad?
50     /// Readability. The code tricks people into thinking that
51     /// something complex is going on.
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
65     ///Checks for transmutes that could be a pointer cast.
66     ///
67     /// ### Why is this bad?
68     /// Readability. The code tricks people into thinking that
69     /// something complex is going on.
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
89     /// Checks for transmutes between a type `T` and `*T`.
90     ///
91     /// ### Why is this bad?
92     /// It's easy to mistakenly transmute between a type and a
93     /// pointer to that type.
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
107     /// Checks for transmutes from a pointer to a reference.
108     ///
109     /// ### Why is this bad?
110     /// This can always be rewritten with `&` and `*`.
111     ///
112     /// ### Known problems
113     /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
114     /// while dereferencing raw pointer is not stable yet.
115     /// If you need to do this in those places,
116     /// you would have to use `transmute` instead.
117     ///
118     /// ### Example
119     /// ```rust,ignore
120     /// unsafe {
121     ///     let _: &T = std::mem::transmute(p); // where p: *const T
122     /// }
123     ///
124     /// // can be written:
125     /// let _: &T = &*p;
126     /// ```
127     pub TRANSMUTE_PTR_TO_REF,
128     complexity,
129     "transmutes from a pointer to a reference type"
130 }
131
132 declare_clippy_lint! {
133     /// ### What it does
134     /// Checks for transmutes from an integer to a `char`.
135     ///
136     /// ### Why is this bad?
137     /// 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
167     /// Checks for transmutes from a `&[u8]` to a `&str`.
168     ///
169     /// ### Why is this bad?
170     /// Not every byte slice is a valid UTF-8 string.
171     ///
172     /// ### Known problems
173     /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
174     /// as it needs to validate the input.
175     /// If you are certain that the input is always a valid UTF-8,
176     /// use [`from_utf8_unchecked`] which is as fast as `transmute`
177     /// but has a semantically meaningful name.
178     /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
179     ///
180     /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
181     /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
182     ///
183     /// ### Example
184     /// ```rust
185     /// let b: &[u8] = &[1_u8, 2_u8];
186     /// unsafe {
187     ///     let _: &str = std::mem::transmute(b); // where b: &[u8]
188     /// }
189     ///
190     /// // should be:
191     /// let _ = std::str::from_utf8(b).unwrap();
192     /// ```
193     pub TRANSMUTE_BYTES_TO_STR,
194     complexity,
195     "transmutes from a `&[u8]` to a `&str`"
196 }
197
198 declare_clippy_lint! {
199     /// ### What it does
200     /// Checks for transmutes from an integer to a `bool`.
201     ///
202     /// ### Why is this bad?
203     /// This might result in an invalid in-memory representation of a `bool`.
204     ///
205     /// ### Example
206     /// ```rust
207     /// let x = 1_u8;
208     /// unsafe {
209     ///     let _: bool = std::mem::transmute(x); // where x: u8
210     /// }
211     ///
212     /// // should be:
213     /// let _: bool = x != 0;
214     /// ```
215     pub TRANSMUTE_INT_TO_BOOL,
216     complexity,
217     "transmutes from an integer to a `bool`"
218 }
219
220 declare_clippy_lint! {
221     /// ### What it does
222     /// Checks for transmutes from an integer to a float.
223     ///
224     /// ### Why is this bad?
225     /// Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
226     /// and safe.
227     ///
228     /// ### Example
229     /// ```rust
230     /// unsafe {
231     ///     let _: f32 = std::mem::transmute(1_u32); // where x: u32
232     /// }
233     ///
234     /// // should be:
235     /// let _: f32 = f32::from_bits(1_u32);
236     /// ```
237     pub TRANSMUTE_INT_TO_FLOAT,
238     complexity,
239     "transmutes from an integer to a float"
240 }
241
242 declare_clippy_lint! {
243     /// ### What it does
244     /// Checks for transmutes from a float to an integer.
245     ///
246     /// ### Why is this bad?
247     /// Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
248     /// and safe.
249     ///
250     /// ### Example
251     /// ```rust
252     /// unsafe {
253     ///     let _: u32 = std::mem::transmute(1f32);
254     /// }
255     ///
256     /// // should be:
257     /// let _: u32 = 1f32.to_bits();
258     /// ```
259     pub TRANSMUTE_FLOAT_TO_INT,
260     complexity,
261     "transmutes from a float to an integer"
262 }
263
264 declare_clippy_lint! {
265     /// ### What it does
266     /// Checks for transmutes from a pointer to a pointer, or
267     /// from a reference to a reference.
268     ///
269     /// ### Why is this bad?
270     /// Transmutes are dangerous, and these can instead be
271     /// written as casts.
272     ///
273     /// ### Example
274     /// ```rust
275     /// let ptr = &1u32 as *const u32;
276     /// unsafe {
277     ///     // pointer-to-pointer transmute
278     ///     let _: *const f32 = std::mem::transmute(ptr);
279     ///     // ref-ref transmute
280     ///     let _: &f32 = std::mem::transmute(&1u32);
281     /// }
282     /// // These can be respectively written:
283     /// let _ = ptr as *const f32;
284     /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
285     /// ```
286     pub TRANSMUTE_PTR_TO_PTR,
287     pedantic,
288     "transmutes from a pointer to a pointer / a reference to a reference"
289 }
290
291 declare_clippy_lint! {
292     /// ### What it does
293     /// Checks for transmutes between collections whose
294     /// types have different ABI, size or alignment.
295     ///
296     /// ### Why is this bad?
297     /// This is undefined behavior.
298     ///
299     /// ### Known problems
300     /// Currently, we cannot know whether a type is a
301     /// collection, so we just lint the ones that come with `std`.
302     ///
303     /// ### Example
304     /// ```rust
305     /// // different size, therefore likely out-of-bounds memory access
306     /// // You absolutely do not want this in your code!
307     /// unsafe {
308     ///     std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
309     /// };
310     /// ```
311     ///
312     /// You must always iterate, map and collect the values:
313     ///
314     /// ```rust
315     /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
316     /// ```
317     pub UNSOUND_COLLECTION_TRANSMUTE,
318     correctness,
319     "transmute between collections of layout-incompatible types"
320 }
321
322 declare_lint_pass!(Transmute => [
323     CROSSPOINTER_TRANSMUTE,
324     TRANSMUTE_PTR_TO_REF,
325     TRANSMUTE_PTR_TO_PTR,
326     USELESS_TRANSMUTE,
327     WRONG_TRANSMUTE,
328     TRANSMUTE_INT_TO_CHAR,
329     TRANSMUTE_BYTES_TO_STR,
330     TRANSMUTE_INT_TO_BOOL,
331     TRANSMUTE_INT_TO_FLOAT,
332     TRANSMUTE_FLOAT_TO_INT,
333     UNSOUND_COLLECTION_TRANSMUTE,
334     TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
335 ]);
336
337 impl<'tcx> LateLintPass<'tcx> for Transmute {
338     #[allow(clippy::similar_names, clippy::too_many_lines)]
339     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
340         if_chain! {
341             if let ExprKind::Call(path_expr, args) = e.kind;
342             if let ExprKind::Path(ref qpath) = path_expr.kind;
343             if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
344             if cx.tcx.is_diagnostic_item(sym::transmute, def_id);
345             then {
346                 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
347                 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
348                 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
349                 let const_context = in_constant(cx, e.hir_id);
350
351                 let from_ty = cx.typeck_results().expr_ty(&args[0]);
352                 let to_ty = cx.typeck_results().expr_ty(e);
353
354                 // If useless_transmute is triggered, the other lints can be skipped.
355                 if useless_transmute::check(cx, e, from_ty, to_ty, args) {
356                     return;
357                 }
358
359                 let mut linted = wrong_transmute::check(cx, e, from_ty, to_ty);
360                 linted |= crosspointer_transmute::check(cx, e, from_ty, to_ty);
361                 linted |= transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
362                 linted |= transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
363                 linted |= transmute_ref_to_ref::check(cx, e, from_ty, to_ty, args, const_context);
364                 linted |= transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, args);
365                 linted |= transmute_int_to_bool::check(cx, e, from_ty, to_ty, args);
366                 linted |= transmute_int_to_float::check(cx, e, from_ty, to_ty, args, const_context);
367                 linted |= transmute_float_to_int::check(cx, e, from_ty, to_ty, args, const_context);
368                 linted |= unsound_collection_transmute::check(cx, e, from_ty, to_ty);
369
370                 if !linted {
371                     transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, args);
372                 }
373             }
374         }
375     }
376 }