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