]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
Merge pull request #3207 from mikerite/fix-3206
[rust.git] / clippy_lints / src / transmute.rs
1 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use crate::rustc::{declare_tool_lint, lint_array};
3 use if_chain::if_chain;
4 use crate::rustc::ty::{self, Ty};
5 use crate::rustc::hir::*;
6 use std::borrow::Cow;
7 use crate::syntax::ast;
8 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
9 use crate::utils::{opt_def_id, sugg};
10 use crate::rustc_errors::Applicability;
11
12 /// **What it does:** Checks for transmutes that can't ever be correct on any
13 /// architecture.
14 ///
15 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
16 ///
17 /// **Known problems:** When accessing C, users might want to store pointer
18 /// sized objects in `extradata` arguments to save an allocation.
19 ///
20 /// **Example:**
21 /// ```rust
22 /// let ptr: *const T = core::intrinsics::transmute('x')
23 /// ```
24 declare_clippy_lint! {
25     pub WRONG_TRANSMUTE,
26     correctness,
27     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
28 }
29
30 /// **What it does:** Checks for transmutes to the original type of the object
31 /// and transmutes that could be a cast.
32 ///
33 /// **Why is this bad?** Readability. The code tricks people into thinking that
34 /// something complex is going on.
35 ///
36 /// **Known problems:** None.
37 ///
38 /// **Example:**
39 /// ```rust
40 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
41 /// ```
42 declare_clippy_lint! {
43     pub USELESS_TRANSMUTE,
44     complexity,
45     "transmutes that have the same to and from types or could be a cast/coercion"
46 }
47
48 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
49 ///
50 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
51 /// pointer to that type.
52 ///
53 /// **Known problems:** None.
54 ///
55 /// **Example:**
56 /// ```rust
57 /// core::intrinsics::transmute(t) // where the result type is the same as
58 /// // `*t` or `&t`'s
59 /// ```
60 declare_clippy_lint! {
61     pub CROSSPOINTER_TRANSMUTE,
62     complexity,
63     "transmutes that have to or from types that are a pointer to the other"
64 }
65
66 /// **What it does:** Checks for transmutes from a pointer to a reference.
67 ///
68 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
69 ///
70 /// **Known problems:** None.
71 ///
72 /// **Example:**
73 /// ```rust
74 /// let _: &T = std::mem::transmute(p); // where p: *const T
75 /// // can be written:
76 /// let _: &T = &*p;
77 /// ```
78 declare_clippy_lint! {
79     pub TRANSMUTE_PTR_TO_REF,
80     complexity,
81     "transmutes from a pointer to a reference type"
82 }
83
84 /// **What it does:** Checks for transmutes from an integer to a `char`.
85 ///
86 /// **Why is this bad?** Not every integer is a Unicode scalar value.
87 ///
88 /// **Known problems:**
89 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
90 /// as it needs to validate the input.
91 /// If you are certain that the input is always a valid Unicode scalar value,
92 /// use [`from_u32_unchecked`] which is as fast as `transmute`
93 /// but has a semantically meaningful name.
94 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
95 ///
96 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
97 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
98 ///
99 /// **Example:**
100 /// ```rust
101 /// let _: char = std::mem::transmute(x); // where x: u32
102 /// // should be:
103 /// let _ = std::char::from_u32(x).unwrap();
104 /// ```
105 declare_clippy_lint! {
106     pub TRANSMUTE_INT_TO_CHAR,
107     complexity,
108     "transmutes from an integer to a `char`"
109 }
110
111 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
112 ///
113 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
114 ///
115 /// **Known problems:**
116 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
117 /// as it needs to validate the input.
118 /// If you are certain that the input is always a valid UTF-8,
119 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
120 /// but has a semantically meaningful name.
121 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
122 ///
123 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
124 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
125 ///
126 /// **Example:**
127 /// ```rust
128 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
129 /// // should be:
130 /// let _ = std::str::from_utf8(b).unwrap();
131 /// ```
132 declare_clippy_lint! {
133     pub TRANSMUTE_BYTES_TO_STR,
134     complexity,
135     "transmutes from a `&[u8]` to a `&str`"
136 }
137
138 /// **What it does:** Checks for transmutes from an integer to a `bool`.
139 ///
140 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
141 ///
142 /// **Known problems:** None.
143 ///
144 /// **Example:**
145 /// ```rust
146 /// let _: bool = std::mem::transmute(x); // where x: u8
147 /// // should be:
148 /// let _: bool = x != 0;
149 /// ```
150 declare_clippy_lint! {
151     pub TRANSMUTE_INT_TO_BOOL,
152     complexity,
153     "transmutes from an integer to a `bool`"
154 }
155
156 /// **What it does:** Checks for transmutes from an integer to a float.
157 ///
158 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
159 ///
160 /// **Known problems:** None.
161 ///
162 /// **Example:**
163 /// ```rust
164 /// let _: f32 = std::mem::transmute(x); // where x: u32
165 /// // should be:
166 /// let _: f32 = f32::from_bits(x);
167 /// ```
168 declare_clippy_lint! {
169     pub TRANSMUTE_INT_TO_FLOAT,
170     complexity,
171     "transmutes from an integer to a float"
172 }
173
174 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
175 /// from a reference to a reference.
176 ///
177 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
178 /// written as casts.
179 ///
180 /// **Known problems:** None.
181 ///
182 /// **Example:**
183 /// ```rust
184 /// let ptr = &1u32 as *const u32;
185 /// unsafe {
186 ///     // pointer-to-pointer transmute
187 ///     let _: *const f32 = std::mem::transmute(ptr);
188 ///     // ref-ref transmute
189 ///     let _: &f32 = std::mem::transmute(&1u32);
190 /// }
191 /// // These can be respectively written:
192 /// let _ = ptr as *const f32
193 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
194 /// ```
195 declare_clippy_lint! {
196     pub TRANSMUTE_PTR_TO_PTR,
197     complexity,
198     "transmutes from a pointer to a pointer / a reference to a reference"
199 }
200
201 pub struct Transmute;
202
203 impl LintPass for Transmute {
204     fn get_lints(&self) -> LintArray {
205         lint_array!(
206             CROSSPOINTER_TRANSMUTE,
207             TRANSMUTE_PTR_TO_REF,
208             TRANSMUTE_PTR_TO_PTR,
209             USELESS_TRANSMUTE,
210             WRONG_TRANSMUTE,
211             TRANSMUTE_INT_TO_CHAR,
212             TRANSMUTE_BYTES_TO_STR,
213             TRANSMUTE_INT_TO_BOOL,
214             TRANSMUTE_INT_TO_FLOAT,
215         )
216     }
217 }
218
219 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
220     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
221         if let ExprKind::Call(ref path_expr, ref args) = e.node {
222             if let ExprKind::Path(ref qpath) = path_expr.node {
223                 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
224                     if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
225                         let from_ty = cx.tables.expr_ty(&args[0]);
226                         let to_ty = cx.tables.expr_ty(e);
227
228                         match (&from_ty.sty, &to_ty.sty) {
229                             _ if from_ty == to_ty => span_lint(
230                                 cx,
231                                 USELESS_TRANSMUTE,
232                                 e.span,
233                                 &format!("transmute from a type (`{}`) to itself", from_ty),
234                             ),
235                             (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
236                                 cx,
237                                 USELESS_TRANSMUTE,
238                                 e.span,
239                                 "transmute from a reference to a pointer",
240                                 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
241                                     let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
242
243                                     let sugg = if ptr_ty == rty_and_mut {
244                                         arg.as_ty(to_ty)
245                                     } else {
246                                         arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
247                                     };
248
249                                     db.span_suggestion_with_applicability(
250                                         e.span,
251                                         "try",
252                                         sugg.to_string(),
253                                         Applicability::Unspecified,
254                                     );
255                                 },
256                             ),
257                             (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => {
258                                 span_lint_and_then(
259                                     cx,
260                                     USELESS_TRANSMUTE,
261                                     e.span,
262                                     "transmute from an integer to a pointer",
263                                     |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
264                                         db.span_suggestion_with_applicability(
265                                             e.span,
266                                             "try",
267                                             arg.as_ty(&to_ty.to_string()).to_string(),
268                                             Applicability::Unspecified,
269                                         );
270                                     },
271                                 )
272                             },
273                             (&ty::Float(_), &ty::Ref(..)) |
274                             (&ty::Float(_), &ty::RawPtr(_)) |
275                             (&ty::Char, &ty::Ref(..)) |
276                             (&ty::Char, &ty::RawPtr(_)) => span_lint(
277                                 cx,
278                                 WRONG_TRANSMUTE,
279                                 e.span,
280                                 &format!("transmute from a `{}` to a pointer", from_ty),
281                             ),
282                             (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
283                                 cx,
284                                 CROSSPOINTER_TRANSMUTE,
285                                 e.span,
286                                 &format!(
287                                     "transmute from a type (`{}`) to the type that it points to (`{}`)",
288                                     from_ty,
289                                     to_ty
290                                 ),
291                             ),
292                             (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
293                                 cx,
294                                 CROSSPOINTER_TRANSMUTE,
295                                 e.span,
296                                 &format!(
297                                     "transmute from a type (`{}`) to a pointer to that type (`{}`)",
298                                     from_ty,
299                                     to_ty
300                                 ),
301                             ),
302                             (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
303                                 cx,
304                                 TRANSMUTE_PTR_TO_REF,
305                                 e.span,
306                                 &format!(
307                                     "transmute from a pointer type (`{}`) to a reference type \
308                                      (`{}`)",
309                                     from_ty,
310                                     to_ty
311                                 ),
312                                 |db| {
313                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
314                                     let (deref, cast) = if mutbl == Mutability::MutMutable {
315                                         ("&mut *", "*mut")
316                                     } else {
317                                         ("&*", "*const")
318                                     };
319
320                                     let arg = if from_pty.ty == to_ref_ty {
321                                         arg
322                                     } else {
323                                         arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
324                                     };
325
326                                     db.span_suggestion_with_applicability(
327                                         e.span,
328                                         "try",
329                                         sugg::make_unop(deref, arg).to_string(),
330                                         Applicability::Unspecified,
331                                     );
332                                 },
333                             ),
334                             (&ty::Int(ast::IntTy::I32), &ty::Char) |
335                             (&ty::Uint(ast::UintTy::U32), &ty::Char) => span_lint_and_then(
336                                 cx,
337                                 TRANSMUTE_INT_TO_CHAR,
338                                 e.span,
339                                 &format!("transmute from a `{}` to a `char`", from_ty),
340                                 |db| {
341                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
342                                     let arg = if let ty::Int(_) = from_ty.sty {
343                                         arg.as_ty(ty::Uint(ast::UintTy::U32))
344                                     } else {
345                                         arg
346                                     };
347                                     db.span_suggestion_with_applicability(
348                                         e.span,
349                                         "consider using",
350                                         format!("std::char::from_u32({}).unwrap()", arg.to_string()),
351                                         Applicability::Unspecified,
352                                     );
353                                 },
354                             ),
355                             (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
356                                 if_chain! {
357                                     if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.sty, &ty_to.sty);
358                                     if let ty::Uint(ast::UintTy::U8) = slice_ty.sty;
359                                     if from_mutbl == to_mutbl;
360                                     then {
361                                         let postfix = if from_mutbl == Mutability::MutMutable {
362                                             "_mut"
363                                         } else {
364                                             ""
365                                         };
366
367                                         span_lint_and_then(
368                                             cx,
369                                             TRANSMUTE_BYTES_TO_STR,
370                                             e.span,
371                                             &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
372                                             |db| {
373                                                 db.span_suggestion_with_applicability(
374                                                     e.span,
375                                                     "consider using",
376                                                     format!(
377                                                         "std::str::from_utf8{}({}).unwrap()",
378                                                         postfix,
379                                                         snippet(cx, args[0].span, ".."),
380                                                     ),
381                                                     Applicability::Unspecified,
382                                                 );
383                                             }
384                                         )
385                                     } else {
386                                         if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
387                                             span_lint_and_then(
388                                                 cx,
389                                                 TRANSMUTE_PTR_TO_PTR,
390                                                 e.span,
391                                                 "transmute from a reference to a reference",
392                                                 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
393                                                     let ty_from_and_mut = ty::TypeAndMut { ty: ty_from, mutbl: from_mutbl };
394                                                     let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
395                                                     let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
396                                                     let sugg = if to_mutbl == Mutability::MutMutable {
397                                                         sugg_paren.mut_addr_deref()
398                                                     } else {
399                                                         sugg_paren.addr_deref()
400                                                     };
401                                                     db.span_suggestion_with_applicability(
402                                                         e.span,
403                                                         "try",
404                                                         sugg.to_string(),
405                                                         Applicability::Unspecified,
406                                                     );
407                                                 },
408                                             )
409                                         }
410                                     }
411                                 }
412                             },
413                             (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
414                                 cx,
415                                 TRANSMUTE_PTR_TO_PTR,
416                                 e.span,
417                                 "transmute from a pointer to a pointer",
418                                 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
419                                     let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
420                                     db.span_suggestion_with_applicability(
421                                         e.span,
422                                         "try",
423                                         sugg.to_string(),
424                                         Applicability::Unspecified,
425                                     );
426                                 },
427                             ),
428                             (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
429                                 span_lint_and_then(
430                                     cx,
431                                     TRANSMUTE_INT_TO_BOOL,
432                                     e.span,
433                                     &format!("transmute from a `{}` to a `bool`", from_ty),
434                                     |db| {
435                                         let arg = sugg::Sugg::hir(cx, &args[0], "..");
436                                         let zero = sugg::Sugg::NonParen(Cow::from("0"));
437                                         db.span_suggestion_with_applicability(
438                                             e.span,
439                                             "consider using",
440                                             sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
441                                             Applicability::Unspecified,
442                                         );
443                                     },
444                                 )
445                             },
446                             (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => {
447                                 span_lint_and_then(
448                                     cx,
449                                     TRANSMUTE_INT_TO_FLOAT,
450                                     e.span,
451                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
452                                     |db| {
453                                         let arg = sugg::Sugg::hir(cx, &args[0], "..");
454                                         let arg = if let ty::Int(int_ty) = from_ty.sty {
455                                             arg.as_ty(format!(
456                                                 "u{}",
457                                                 int_ty
458                                                     .bit_width()
459                                                     .map_or_else(|| "size".to_string(), |v| v.to_string())
460                                             ))
461                                         } else {
462                                             arg
463                                         };
464                                         db.span_suggestion_with_applicability(
465                                             e.span,
466                                             "consider using",
467                                             format!("{}::from_bits({})", to_ty, arg.to_string()),
468                                             Applicability::Unspecified,
469                                         );
470                                     },
471                                 )
472                             },
473                             _ => return,
474                         };
475                     }
476                 }
477             }
478         }
479     }
480 }
481
482 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
483 /// not available , use
484 /// the type's `ToString` implementation. In weird cases it could lead to types
485 /// with invalid `'_`
486 /// lifetime, but it should be rare.
487 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
488     let seg = last_path_segment(path);
489     if_chain! {
490         if let Some(ref params) = seg.args;
491         if !params.parenthesized;
492         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
493             GenericArg::Type(ty) => Some(ty),
494             GenericArg::Lifetime(_) => None,
495         }).nth(1);
496         if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
497         then {
498             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
499         }
500     }
501
502     to_ref_ty.to_string()
503 }