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