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