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