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