]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
Merge pull request #3303 from shssoichiro/3069-unnecessary-fold-pattern-guard
[rust.git] / clippy_lints / src / transmute.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
14 use crate::rustc::ty::{self, Ty};
15 use crate::rustc::hir::*;
16 use std::borrow::Cow;
17 use crate::syntax::ast;
18 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
19 use crate::utils::{opt_def_id, sugg};
20 use crate::rustc_errors::Applicability;
21
22 /// **What it does:** Checks for transmutes that can't ever be correct on any
23 /// architecture.
24 ///
25 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
26 ///
27 /// **Known problems:** When accessing C, users might want to store pointer
28 /// sized objects in `extradata` arguments to save an allocation.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// let ptr: *const T = core::intrinsics::transmute('x')
33 /// ```
34 declare_clippy_lint! {
35     pub WRONG_TRANSMUTE,
36     correctness,
37     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
38 }
39
40 /// **What it does:** Checks for transmutes to the original type of the object
41 /// and transmutes that could be a cast.
42 ///
43 /// **Why is this bad?** Readability. The code tricks people into thinking that
44 /// something complex is going on.
45 ///
46 /// **Known problems:** None.
47 ///
48 /// **Example:**
49 /// ```rust
50 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
51 /// ```
52 declare_clippy_lint! {
53     pub USELESS_TRANSMUTE,
54     complexity,
55     "transmutes that have the same to and from types or could be a cast/coercion"
56 }
57
58 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
59 ///
60 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
61 /// pointer to that type.
62 ///
63 /// **Known problems:** None.
64 ///
65 /// **Example:**
66 /// ```rust
67 /// core::intrinsics::transmute(t) // where the result type is the same as
68 /// // `*t` or `&t`'s
69 /// ```
70 declare_clippy_lint! {
71     pub CROSSPOINTER_TRANSMUTE,
72     complexity,
73     "transmutes that have to or from types that are a pointer to the other"
74 }
75
76 /// **What it does:** Checks for transmutes from a pointer to a reference.
77 ///
78 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
79 ///
80 /// **Known problems:** None.
81 ///
82 /// **Example:**
83 /// ```rust
84 /// let _: &T = std::mem::transmute(p); // where p: *const T
85 /// // can be written:
86 /// let _: &T = &*p;
87 /// ```
88 declare_clippy_lint! {
89     pub TRANSMUTE_PTR_TO_REF,
90     complexity,
91     "transmutes from a pointer to a reference type"
92 }
93
94 /// **What it does:** Checks for transmutes from an integer to a `char`.
95 ///
96 /// **Why is this bad?** Not every integer is a Unicode scalar value.
97 ///
98 /// **Known problems:**
99 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
100 /// as it needs to validate the input.
101 /// If you are certain that the input is always a valid Unicode scalar value,
102 /// use [`from_u32_unchecked`] which is as fast as `transmute`
103 /// but has a semantically meaningful name.
104 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
105 ///
106 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
107 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
108 ///
109 /// **Example:**
110 /// ```rust
111 /// let _: char = std::mem::transmute(x); // where x: u32
112 /// // should be:
113 /// let _ = std::char::from_u32(x).unwrap();
114 /// ```
115 declare_clippy_lint! {
116     pub TRANSMUTE_INT_TO_CHAR,
117     complexity,
118     "transmutes from an integer to a `char`"
119 }
120
121 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
122 ///
123 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
124 ///
125 /// **Known problems:**
126 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
127 /// as it needs to validate the input.
128 /// If you are certain that the input is always a valid UTF-8,
129 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
130 /// but has a semantically meaningful name.
131 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
132 ///
133 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
134 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
135 ///
136 /// **Example:**
137 /// ```rust
138 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
139 /// // should be:
140 /// let _ = std::str::from_utf8(b).unwrap();
141 /// ```
142 declare_clippy_lint! {
143     pub TRANSMUTE_BYTES_TO_STR,
144     complexity,
145     "transmutes from a `&[u8]` to a `&str`"
146 }
147
148 /// **What it does:** Checks for transmutes from an integer to a `bool`.
149 ///
150 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
151 ///
152 /// **Known problems:** None.
153 ///
154 /// **Example:**
155 /// ```rust
156 /// let _: bool = std::mem::transmute(x); // where x: u8
157 /// // should be:
158 /// let _: bool = x != 0;
159 /// ```
160 declare_clippy_lint! {
161     pub TRANSMUTE_INT_TO_BOOL,
162     complexity,
163     "transmutes from an integer to a `bool`"
164 }
165
166 /// **What it does:** Checks for transmutes from an integer to a float.
167 ///
168 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
169 ///
170 /// **Known problems:** None.
171 ///
172 /// **Example:**
173 /// ```rust
174 /// let _: f32 = std::mem::transmute(x); // where x: u32
175 /// // should be:
176 /// let _: f32 = f32::from_bits(x);
177 /// ```
178 declare_clippy_lint! {
179     pub TRANSMUTE_INT_TO_FLOAT,
180     complexity,
181     "transmutes from an integer to a float"
182 }
183
184 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
185 /// from a reference to a reference.
186 ///
187 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
188 /// written as casts.
189 ///
190 /// **Known problems:** None.
191 ///
192 /// **Example:**
193 /// ```rust
194 /// let ptr = &1u32 as *const u32;
195 /// unsafe {
196 ///     // pointer-to-pointer transmute
197 ///     let _: *const f32 = std::mem::transmute(ptr);
198 ///     // ref-ref transmute
199 ///     let _: &f32 = std::mem::transmute(&1u32);
200 /// }
201 /// // These can be respectively written:
202 /// let _ = ptr as *const f32
203 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
204 /// ```
205 declare_clippy_lint! {
206     pub TRANSMUTE_PTR_TO_PTR,
207     complexity,
208     "transmutes from a pointer to a pointer / a reference to a reference"
209 }
210
211 pub struct Transmute;
212
213 impl LintPass for Transmute {
214     fn get_lints(&self) -> LintArray {
215         lint_array!(
216             CROSSPOINTER_TRANSMUTE,
217             TRANSMUTE_PTR_TO_REF,
218             TRANSMUTE_PTR_TO_PTR,
219             USELESS_TRANSMUTE,
220             WRONG_TRANSMUTE,
221             TRANSMUTE_INT_TO_CHAR,
222             TRANSMUTE_BYTES_TO_STR,
223             TRANSMUTE_INT_TO_BOOL,
224             TRANSMUTE_INT_TO_FLOAT,
225         )
226     }
227 }
228
229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
230     #[allow(clippy::similar_names)]
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| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
252                                     let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
253
254                                     let sugg = if ptr_ty == rty_and_mut {
255                                         arg.as_ty(to_ty)
256                                     } else {
257                                         arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
258                                     };
259
260                                     db.span_suggestion_with_applicability(
261                                         e.span,
262                                         "try",
263                                         sugg.to_string(),
264                                         Applicability::Unspecified,
265                                     );
266                                 },
267                             ),
268                             (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => {
269                                 span_lint_and_then(
270                                     cx,
271                                     USELESS_TRANSMUTE,
272                                     e.span,
273                                     "transmute from an integer to a pointer",
274                                     |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
275                                         db.span_suggestion_with_applicability(
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,
300                                     to_ty
301                                 ),
302                             ),
303                             (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
304                                 cx,
305                                 CROSSPOINTER_TRANSMUTE,
306                                 e.span,
307                                 &format!(
308                                     "transmute from a type (`{}`) to a pointer to that type (`{}`)",
309                                     from_ty,
310                                     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,
321                                     to_ty
322                                 ),
323                                 |db| {
324                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
325                                     let (deref, cast) = if mutbl == Mutability::MutMutable {
326                                         ("&mut *", "*mut")
327                                     } else {
328                                         ("&*", "*const")
329                                     };
330
331                                     let arg = if from_pty.ty == to_ref_ty {
332                                         arg
333                                     } else {
334                                         arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
335                                     };
336
337                                     db.span_suggestion_with_applicability(
338                                         e.span,
339                                         "try",
340                                         sugg::make_unop(deref, arg).to_string(),
341                                         Applicability::Unspecified,
342                                     );
343                                 },
344                             ),
345                             (&ty::Int(ast::IntTy::I32), &ty::Char) |
346                             (&ty::Uint(ast::UintTy::U32), &ty::Char) => span_lint_and_then(
347                                 cx,
348                                 TRANSMUTE_INT_TO_CHAR,
349                                 e.span,
350                                 &format!("transmute from a `{}` to a `char`", from_ty),
351                                 |db| {
352                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
353                                     let arg = if let ty::Int(_) = from_ty.sty {
354                                         arg.as_ty(ty::Uint(ast::UintTy::U32))
355                                     } else {
356                                         arg
357                                     };
358                                     db.span_suggestion_with_applicability(
359                                         e.span,
360                                         "consider using",
361                                         format!("std::char::from_u32({}).unwrap()", arg.to_string()),
362                                         Applicability::Unspecified,
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_with_applicability(
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 { ty: ty_from, mutbl: from_mutbl };
405                                                     let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
406                                                     let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
407                                                     let sugg = if to_mutbl == Mutability::MutMutable {
408                                                         sugg_paren.mut_addr_deref()
409                                                     } else {
410                                                         sugg_paren.addr_deref()
411                                                     };
412                                                     db.span_suggestion_with_applicability(
413                                                         e.span,
414                                                         "try",
415                                                         sugg.to_string(),
416                                                         Applicability::Unspecified,
417                                                     );
418                                                 },
419                                             )
420                                         }
421                                     }
422                                 }
423                             },
424                             (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
425                                 cx,
426                                 TRANSMUTE_PTR_TO_PTR,
427                                 e.span,
428                                 "transmute from a pointer to a pointer",
429                                 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
430                                     let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
431                                     db.span_suggestion_with_applicability(
432                                         e.span,
433                                         "try",
434                                         sugg.to_string(),
435                                         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_with_applicability(
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(_)) => {
458                                 span_lint_and_then(
459                                     cx,
460                                     TRANSMUTE_INT_TO_FLOAT,
461                                     e.span,
462                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
463                                     |db| {
464                                         let arg = sugg::Sugg::hir(cx, &args[0], "..");
465                                         let arg = if let ty::Int(int_ty) = from_ty.sty {
466                                             arg.as_ty(format!(
467                                                 "u{}",
468                                                 int_ty
469                                                     .bit_width()
470                                                     .map_or_else(|| "size".to_string(), |v| v.to_string())
471                                             ))
472                                         } else {
473                                             arg
474                                         };
475                                         db.span_suggestion_with_applicability(
476                                             e.span,
477                                             "consider using",
478                                             format!("{}::from_bits({})", to_ty, arg.to_string()),
479                                             Applicability::Unspecified,
480                                         );
481                                     },
482                                 )
483                             },
484                             _ => return,
485                         };
486                     }
487                 }
488             }
489         }
490     }
491 }
492
493 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
494 /// not available , use
495 /// the type's `ToString` implementation. In weird cases it could lead to types
496 /// with invalid `'_`
497 /// lifetime, but it should be rare.
498 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
499     let seg = last_path_segment(path);
500     if_chain! {
501         if let Some(ref params) = seg.args;
502         if !params.parenthesized;
503         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
504             GenericArg::Type(ty) => Some(ty),
505             GenericArg::Lifetime(_) => None,
506         }).nth(1);
507         if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
508         then {
509             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
510         }
511     }
512
513     to_ref_ty.to_string()
514 }