]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/mod.rs
Move transmute_int_to_char to its own module
[rust.git] / clippy_lints / src / transmute / mod.rs
1 mod crosspointer_transmute;
2 mod transmute_int_to_char;
3 mod transmute_ptr_to_ref;
4 mod useless_transmute;
5 mod utils;
6 mod wrong_transmute;
7
8 use utils::*;
9
10 use crate::utils::{
11     in_constant, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, span_lint_and_then, sugg,
12 };
13 use if_chain::if_chain;
14 use rustc_ast as ast;
15 use rustc_errors::Applicability;
16 use rustc_hir::{Expr, ExprKind, Mutability, UnOp};
17 use rustc_lint::{LateContext, LateLintPass};
18 use rustc_middle::ty;
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use std::borrow::Cow;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for transmutes that can't ever be correct on any
24     /// architecture.
25     ///
26     /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
27     ///
28     /// **Known problems:** When accessing C, users might want to store pointer
29     /// sized objects in `extradata` arguments to save an allocation.
30     ///
31     /// **Example:**
32     /// ```ignore
33     /// let ptr: *const T = core::intrinsics::transmute('x')
34     /// ```
35     pub WRONG_TRANSMUTE,
36     correctness,
37     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
38 }
39
40 // FIXME: Move this to `complexity` again, after #5343 is fixed
41 declare_clippy_lint! {
42     /// **What it does:** Checks for transmutes to the original type of the object
43     /// and transmutes that could be a cast.
44     ///
45     /// **Why is this bad?** Readability. The code tricks people into thinking that
46     /// something complex is going on.
47     ///
48     /// **Known problems:** None.
49     ///
50     /// **Example:**
51     /// ```rust,ignore
52     /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
53     /// ```
54     pub USELESS_TRANSMUTE,
55     nursery,
56     "transmutes that have the same to and from types or could be a cast/coercion"
57 }
58
59 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
60 declare_clippy_lint! {
61     /// **What it does:**Checks for transmutes that could be a pointer cast.
62     ///
63     /// **Why is this bad?** Readability. The code tricks people into thinking that
64     /// something complex is going on.
65     ///
66     /// **Known problems:** None.
67     ///
68     /// **Example:**
69     ///
70     /// ```rust
71     /// # let p: *const [i32] = &[];
72     /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
73     /// ```
74     /// Use instead:
75     /// ```rust
76     /// # let p: *const [i32] = &[];
77     /// p as *const [u16];
78     /// ```
79     pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
80     complexity,
81     "transmutes that could be a pointer cast"
82 }
83
84 declare_clippy_lint! {
85     /// **What it does:** Checks for transmutes between a type `T` and `*T`.
86     ///
87     /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
88     /// pointer to that type.
89     ///
90     /// **Known problems:** None.
91     ///
92     /// **Example:**
93     /// ```rust,ignore
94     /// core::intrinsics::transmute(t) // where the result type is the same as
95     ///                                // `*t` or `&t`'s
96     /// ```
97     pub CROSSPOINTER_TRANSMUTE,
98     complexity,
99     "transmutes that have to or from types that are a pointer to the other"
100 }
101
102 declare_clippy_lint! {
103     /// **What it does:** Checks for transmutes from a pointer to a reference.
104     ///
105     /// **Why is this bad?** This can always be rewritten with `&` and `*`.
106     ///
107     /// **Known problems:**
108     /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
109     /// while dereferencing raw pointer is not stable yet.
110     /// If you need to do this in those places,
111     /// you would have to use `transmute` instead.
112     ///
113     /// **Example:**
114     /// ```rust,ignore
115     /// unsafe {
116     ///     let _: &T = std::mem::transmute(p); // where p: *const T
117     /// }
118     ///
119     /// // can be written:
120     /// let _: &T = &*p;
121     /// ```
122     pub TRANSMUTE_PTR_TO_REF,
123     complexity,
124     "transmutes from a pointer to a reference type"
125 }
126
127 declare_clippy_lint! {
128     /// **What it does:** Checks for transmutes from an integer to a `char`.
129     ///
130     /// **Why is this bad?** Not every integer is a Unicode scalar value.
131     ///
132     /// **Known problems:**
133     /// - [`from_u32`] which this lint suggests using is slower than `transmute`
134     /// as it needs to validate the input.
135     /// If you are certain that the input is always a valid Unicode scalar value,
136     /// use [`from_u32_unchecked`] which is as fast as `transmute`
137     /// but has a semantically meaningful name.
138     /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
139     ///
140     /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
141     /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
142     ///
143     /// **Example:**
144     /// ```rust
145     /// let x = 1_u32;
146     /// unsafe {
147     ///     let _: char = std::mem::transmute(x); // where x: u32
148     /// }
149     ///
150     /// // should be:
151     /// let _ = std::char::from_u32(x).unwrap();
152     /// ```
153     pub TRANSMUTE_INT_TO_CHAR,
154     complexity,
155     "transmutes from an integer to a `char`"
156 }
157
158 declare_clippy_lint! {
159     /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
160     ///
161     /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
162     ///
163     /// **Known problems:**
164     /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
165     /// as it needs to validate the input.
166     /// If you are certain that the input is always a valid UTF-8,
167     /// use [`from_utf8_unchecked`] which is as fast as `transmute`
168     /// but has a semantically meaningful name.
169     /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
170     ///
171     /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
172     /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
173     ///
174     /// **Example:**
175     /// ```rust
176     /// let b: &[u8] = &[1_u8, 2_u8];
177     /// unsafe {
178     ///     let _: &str = std::mem::transmute(b); // where b: &[u8]
179     /// }
180     ///
181     /// // should be:
182     /// let _ = std::str::from_utf8(b).unwrap();
183     /// ```
184     pub TRANSMUTE_BYTES_TO_STR,
185     complexity,
186     "transmutes from a `&[u8]` to a `&str`"
187 }
188
189 declare_clippy_lint! {
190     /// **What it does:** Checks for transmutes from an integer to a `bool`.
191     ///
192     /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
193     ///
194     /// **Known problems:** None.
195     ///
196     /// **Example:**
197     /// ```rust
198     /// let x = 1_u8;
199     /// unsafe {
200     ///     let _: bool = std::mem::transmute(x); // where x: u8
201     /// }
202     ///
203     /// // should be:
204     /// let _: bool = x != 0;
205     /// ```
206     pub TRANSMUTE_INT_TO_BOOL,
207     complexity,
208     "transmutes from an integer to a `bool`"
209 }
210
211 declare_clippy_lint! {
212     /// **What it does:** Checks for transmutes from an integer to a float.
213     ///
214     /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
215     /// and safe.
216     ///
217     /// **Known problems:** None.
218     ///
219     /// **Example:**
220     /// ```rust
221     /// unsafe {
222     ///     let _: f32 = std::mem::transmute(1_u32); // where x: u32
223     /// }
224     ///
225     /// // should be:
226     /// let _: f32 = f32::from_bits(1_u32);
227     /// ```
228     pub TRANSMUTE_INT_TO_FLOAT,
229     complexity,
230     "transmutes from an integer to a float"
231 }
232
233 declare_clippy_lint! {
234     /// **What it does:** Checks for transmutes from a float to an integer.
235     ///
236     /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
237     /// and safe.
238     ///
239     /// **Known problems:** None.
240     ///
241     /// **Example:**
242     /// ```rust
243     /// unsafe {
244     ///     let _: u32 = std::mem::transmute(1f32);
245     /// }
246     ///
247     /// // should be:
248     /// let _: u32 = 1f32.to_bits();
249     /// ```
250     pub TRANSMUTE_FLOAT_TO_INT,
251     complexity,
252     "transmutes from a float to an integer"
253 }
254
255 declare_clippy_lint! {
256     /// **What it does:** Checks for transmutes from a pointer to a pointer, or
257     /// from a reference to a reference.
258     ///
259     /// **Why is this bad?** Transmutes are dangerous, and these can instead be
260     /// written as casts.
261     ///
262     /// **Known problems:** None.
263     ///
264     /// **Example:**
265     /// ```rust
266     /// let ptr = &1u32 as *const u32;
267     /// unsafe {
268     ///     // pointer-to-pointer transmute
269     ///     let _: *const f32 = std::mem::transmute(ptr);
270     ///     // ref-ref transmute
271     ///     let _: &f32 = std::mem::transmute(&1u32);
272     /// }
273     /// // These can be respectively written:
274     /// let _ = ptr as *const f32;
275     /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
276     /// ```
277     pub TRANSMUTE_PTR_TO_PTR,
278     complexity,
279     "transmutes from a pointer to a pointer / a reference to a reference"
280 }
281
282 declare_clippy_lint! {
283     /// **What it does:** Checks for transmutes between collections whose
284     /// types have different ABI, size or alignment.
285     ///
286     /// **Why is this bad?** This is undefined behavior.
287     ///
288     /// **Known problems:** Currently, we cannot know whether a type is a
289     /// collection, so we just lint the ones that come with `std`.
290     ///
291     /// **Example:**
292     /// ```rust
293     /// // different size, therefore likely out-of-bounds memory access
294     /// // You absolutely do not want this in your code!
295     /// unsafe {
296     ///     std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
297     /// };
298     /// ```
299     ///
300     /// You must always iterate, map and collect the values:
301     ///
302     /// ```rust
303     /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
304     /// ```
305     pub UNSOUND_COLLECTION_TRANSMUTE,
306     correctness,
307     "transmute between collections of layout-incompatible types"
308 }
309
310 declare_lint_pass!(Transmute => [
311     CROSSPOINTER_TRANSMUTE,
312     TRANSMUTE_PTR_TO_REF,
313     TRANSMUTE_PTR_TO_PTR,
314     USELESS_TRANSMUTE,
315     WRONG_TRANSMUTE,
316     TRANSMUTE_INT_TO_CHAR,
317     TRANSMUTE_BYTES_TO_STR,
318     TRANSMUTE_INT_TO_BOOL,
319     TRANSMUTE_INT_TO_FLOAT,
320     TRANSMUTE_FLOAT_TO_INT,
321     UNSOUND_COLLECTION_TRANSMUTE,
322     TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
323 ]);
324
325 // used to check for UNSOUND_COLLECTION_TRANSMUTE
326 static COLLECTIONS: &[&[&str]] = &[
327     &paths::VEC,
328     &paths::VEC_DEQUE,
329     &paths::BINARY_HEAP,
330     &paths::BTREESET,
331     &paths::BTREEMAP,
332     &paths::HASHSET,
333     &paths::HASHMAP,
334 ];
335
336 impl<'tcx> LateLintPass<'tcx> for Transmute {
337     #[allow(clippy::similar_names, clippy::too_many_lines)]
338     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
339         if_chain! {
340             if let ExprKind::Call(ref path_expr, ref args) = e.kind;
341             if let ExprKind::Path(ref qpath) = path_expr.kind;
342             if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
343             if match_def_path(cx, def_id, &paths::TRANSMUTE);
344             then {
345                 // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
346                 // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
347                 // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
348                 let const_context = in_constant(cx, e.hir_id);
349
350                 let from_ty = cx.typeck_results().expr_ty(&args[0]);
351                 let to_ty = cx.typeck_results().expr_ty(e);
352
353                 let triggered = useless_transmute::check(cx, e, from_ty, to_ty, args);
354                 if triggered {
355                     return;
356                 }
357                 let triggered = wrong_transmute::check(cx, e, from_ty, to_ty);
358                 if triggered {
359                     return;
360                 }
361                 let triggered = crosspointer_transmute::check(cx, e, from_ty, to_ty);
362                 if triggered {
363                     return;
364                 }
365                 let triggered = transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, args, qpath);
366                 if triggered {
367                     return;
368                 }
369                 let triggered = transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
370                 if triggered {
371                     return;
372                 }
373
374                 match (&from_ty.kind(), &to_ty.kind()) {
375                     (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
376                         if_chain! {
377                             if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
378                             if let ty::Uint(ty::UintTy::U8) = slice_ty.kind();
379                             if from_mutbl == to_mutbl;
380                             then {
381                                 let postfix = if *from_mutbl == Mutability::Mut {
382                                     "_mut"
383                                 } else {
384                                     ""
385                                 };
386
387                                 span_lint_and_sugg(
388                                     cx,
389                                     TRANSMUTE_BYTES_TO_STR,
390                                     e.span,
391                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
392                                     "consider using",
393                                     format!(
394                                         "std::str::from_utf8{}({}).unwrap()",
395                                         postfix,
396                                         snippet(cx, args[0].span, ".."),
397                                     ),
398                                     Applicability::Unspecified,
399                                 );
400                             } else {
401                                 if (cx.tcx.erase_regions(from_ty) != cx.tcx.erase_regions(to_ty))
402                                     && !const_context {
403                                     span_lint_and_then(
404                                         cx,
405                                         TRANSMUTE_PTR_TO_PTR,
406                                         e.span,
407                                         "transmute from a reference to a reference",
408                                         |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
409                                             let ty_from_and_mut = ty::TypeAndMut {
410                                                 ty: ty_from,
411                                                 mutbl: *from_mutbl
412                                             };
413                                             let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
414                                             let sugg_paren = arg
415                                                 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
416                                                 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
417                                             let sugg = if *to_mutbl == Mutability::Mut {
418                                                 sugg_paren.mut_addr_deref()
419                                             } else {
420                                                 sugg_paren.addr_deref()
421                                             };
422                                             diag.span_suggestion(
423                                                 e.span,
424                                                 "try",
425                                                 sugg.to_string(),
426                                                 Applicability::Unspecified,
427                                             );
428                                         },
429                                     )
430                                 }
431                             }
432                         }
433                     },
434                     (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
435                         cx,
436                         TRANSMUTE_PTR_TO_PTR,
437                         e.span,
438                         "transmute from a pointer to a pointer",
439                         |diag| {
440                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
441                                 let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
442                                 diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
443                             }
444                         },
445                     ),
446                     (ty::Int(ty::IntTy::I8) | ty::Uint(ty::UintTy::U8), ty::Bool) => {
447                         span_lint_and_then(
448                             cx,
449                             TRANSMUTE_INT_TO_BOOL,
450                             e.span,
451                             &format!("transmute from a `{}` to a `bool`", from_ty),
452                             |diag| {
453                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
454                                 let zero = sugg::Sugg::NonParen(Cow::from("0"));
455                                 diag.span_suggestion(
456                                     e.span,
457                                     "consider using",
458                                     sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
459                                     Applicability::Unspecified,
460                                 );
461                             },
462                         )
463                     },
464                     (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
465                         cx,
466                         TRANSMUTE_INT_TO_FLOAT,
467                         e.span,
468                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
469                         |diag| {
470                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
471                             let arg = if let ty::Int(int_ty) = from_ty.kind() {
472                                 arg.as_ty(format!(
473                                     "u{}",
474                                     int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
475                                 ))
476                             } else {
477                                 arg
478                             };
479                             diag.span_suggestion(
480                                 e.span,
481                                 "consider using",
482                                 format!("{}::from_bits({})", to_ty, arg.to_string()),
483                                 Applicability::Unspecified,
484                             );
485                         },
486                     ),
487                     (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
488                         cx,
489                         TRANSMUTE_FLOAT_TO_INT,
490                         e.span,
491                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
492                         |diag| {
493                             let mut expr = &args[0];
494                             let mut arg = sugg::Sugg::hir(cx, expr, "..");
495
496                             if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
497                                 expr = &inner_expr;
498                             }
499
500                             if_chain! {
501                                 // if the expression is a float literal and it is unsuffixed then
502                                 // add a suffix so the suggestion is valid and unambiguous
503                                 let op = format!("{}{}", arg, float_ty.name_str()).into();
504                                 if let ExprKind::Lit(lit) = &expr.kind;
505                                 if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
506                                 then {
507                                     match arg {
508                                         sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
509                                         _ => arg = sugg::Sugg::NonParen(op)
510                                     }
511                                 }
512                             }
513
514                             arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
515
516                             // cast the result of `to_bits` if `to_ty` is signed
517                             arg = if let ty::Int(int_ty) = to_ty.kind() {
518                                 arg.as_ty(int_ty.name_str().to_string())
519                             } else {
520                                 arg
521                             };
522
523                             diag.span_suggestion(
524                                 e.span,
525                                 "consider using",
526                                 arg.to_string(),
527                                 Applicability::Unspecified,
528                             );
529                         },
530                     ),
531                     (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
532                         if from_adt.did != to_adt.did ||
533                                 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
534                             return;
535                         }
536                         if from_substs.types().zip(to_substs.types())
537                                               .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
538                             span_lint(
539                                 cx,
540                                 UNSOUND_COLLECTION_TRANSMUTE,
541                                 e.span,
542                                 &format!(
543                                     "transmute from `{}` to `{}` with mismatched layout is unsound",
544                                     from_ty,
545                                     to_ty
546                                 )
547                             );
548                         }
549                     },
550                     (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
551                         cx,
552                         TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
553                         e.span,
554                         &format!(
555                             "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
556                             from_ty,
557                             to_ty
558                         ),
559                         |diag| {
560                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
561                                 let sugg = arg.as_ty(&to_ty.to_string()).to_string();
562                                 diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);
563                             }
564                         }
565                     ),
566                     _ => {
567                         return;
568                     },
569                 }
570             }
571         }
572     }
573 }