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