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