]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
Merge pull request #2202 from topecongiro/format
[rust.git] / clippy_lints / src / transmute.rs
1 use rustc::lint::*;
2 use rustc::ty::{self, Ty};
3 use rustc::hir::*;
4 use std::borrow::Cow;
5 use syntax::ast;
6 use utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
7 use utils::{opt_def_id, sugg};
8
9 /// **What it does:** Checks for transmutes that can't ever be correct on any
10 /// architecture.
11 ///
12 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
13 ///
14 /// **Known problems:** When accessing C, users might want to store pointer
15 /// sized objects in `extradata` arguments to save an allocation.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// let ptr: *const T = core::intrinsics::transmute('x')`
20 /// ```
21 declare_lint! {
22     pub WRONG_TRANSMUTE,
23     Warn,
24     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
25 }
26
27 /// **What it does:** Checks for transmutes to the original type of the object
28 /// and transmutes that could be a cast.
29 ///
30 /// **Why is this bad?** Readability. The code tricks people into thinking that
31 /// something complex is going on.
32 ///
33 /// **Known problems:** None.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
38 /// ```
39 declare_lint! {
40     pub USELESS_TRANSMUTE,
41     Warn,
42     "transmutes that have the same to and from types or could be a cast/coercion"
43 }
44
45 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
46 ///
47 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
48 /// pointer to that type.
49 ///
50 /// **Known problems:** None.
51 ///
52 /// **Example:**
53 /// ```rust
54 /// core::intrinsics::transmute(t)` // where the result type is the same as
55 /// `*t` or `&t`'s
56 /// ```
57 declare_lint! {
58     pub CROSSPOINTER_TRANSMUTE,
59     Warn,
60     "transmutes that have to or from types that are a pointer to the other"
61 }
62
63 /// **What it does:** Checks for transmutes from a pointer to a reference.
64 ///
65 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
66 ///
67 /// **Known problems:** None.
68 ///
69 /// **Example:**
70 /// ```rust
71 /// let _: &T = std::mem::transmute(p); // where p: *const T
72 /// // can be written:
73 /// let _: &T = &*p;
74 /// ```
75 declare_lint! {
76     pub TRANSMUTE_PTR_TO_REF,
77     Warn,
78     "transmutes from a pointer to a reference type"
79 }
80
81 /// **What it does:** Checks for transmutes from an integer to a `char`.
82 ///
83 /// **Why is this bad?** Not every integer is a Unicode scalar value.
84 ///
85 /// **Known problems:**
86 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
87 /// as it needs to validate the input.
88 /// If you are certain that the input is always a valid Unicode scalar value,
89 /// use [`from_u32_unchecked`] which is as fast as `transmute`
90 /// but has a semantically meaningful name.
91 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
92 ///
93 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
94 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
95 ///
96 /// **Example:**
97 /// ```rust
98 /// let _: char = std::mem::transmute(x); // where x: u32
99 /// // should be:
100 /// let _ = std::char::from_u32(x).unwrap();
101 /// ```
102 declare_lint! {
103     pub TRANSMUTE_INT_TO_CHAR,
104     Warn,
105     "transmutes from an integer to a `char`"
106 }
107
108 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
109 ///
110 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
111 ///
112 /// **Known problems:**
113 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
114 /// as it needs to validate the input.
115 /// If you are certain that the input is always a valid UTF-8,
116 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
117 /// but has a semantically meaningful name.
118 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
119 ///
120 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
121 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
122 ///
123 /// **Example:**
124 /// ```rust
125 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
126 /// // should be:
127 /// let _ = std::str::from_utf8(b).unwrap();
128 /// ```
129 declare_lint! {
130     pub TRANSMUTE_BYTES_TO_STR,
131     Warn,
132     "transmutes from a `&[u8]` to a `&str`"
133 }
134
135 /// **What it does:** Checks for transmutes from an integer to a `bool`.
136 ///
137 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
138 ///
139 /// **Known problems:** None.
140 ///
141 /// **Example:**
142 /// ```rust
143 /// let _: bool = std::mem::transmute(x); // where x: u8
144 /// // should be:
145 /// let _: bool = x != 0;
146 /// ```
147 declare_lint! {
148     pub TRANSMUTE_INT_TO_BOOL,
149     Warn,
150     "transmutes from an integer to a `bool`"
151 }
152
153 /// **What it does:** Checks for transmutes from an integer to a float.
154 ///
155 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
156 ///
157 /// **Known problems:** None.
158 ///
159 /// **Example:**
160 /// ```rust
161 /// let _: f32 = std::mem::transmute(x); // where x: u32
162 /// // should be:
163 /// let _: f32 = f32::from_bits(x);
164 /// ```
165 declare_lint! {
166     pub TRANSMUTE_INT_TO_FLOAT,
167     Warn,
168     "transmutes from an integer to a float"
169 }
170
171 pub struct Transmute;
172
173 impl LintPass for Transmute {
174     fn get_lints(&self) -> LintArray {
175         lint_array!(
176             CROSSPOINTER_TRANSMUTE,
177             TRANSMUTE_PTR_TO_REF,
178             USELESS_TRANSMUTE,
179             WRONG_TRANSMUTE,
180             TRANSMUTE_INT_TO_CHAR,
181             TRANSMUTE_BYTES_TO_STR,
182             TRANSMUTE_INT_TO_BOOL,
183             TRANSMUTE_INT_TO_FLOAT
184         )
185     }
186 }
187
188 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
189     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
190         if let ExprCall(ref path_expr, ref args) = e.node {
191             if let ExprPath(ref qpath) = path_expr.node {
192                 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
193                     if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
194                         let from_ty = cx.tables.expr_ty(&args[0]);
195                         let to_ty = cx.tables.expr_ty(e);
196
197                         match (&from_ty.sty, &to_ty.sty) {
198                             _ if from_ty == to_ty => span_lint(
199                                 cx,
200                                 USELESS_TRANSMUTE,
201                                 e.span,
202                                 &format!("transmute from a type (`{}`) to itself", from_ty),
203                             ),
204                             (&ty::TyRef(_, rty), &ty::TyRawPtr(ptr_ty)) => span_lint_and_then(
205                                 cx,
206                                 USELESS_TRANSMUTE,
207                                 e.span,
208                                 "transmute from a reference to a pointer",
209                                 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
210                                     let sugg = if ptr_ty == rty {
211                                         arg.as_ty(to_ty)
212                                     } else {
213                                         arg.as_ty(cx.tcx.mk_ptr(rty)).as_ty(to_ty)
214                                     };
215
216                                     db.span_suggestion(e.span, "try", sugg.to_string());
217                                 },
218                             ),
219                             (&ty::TyInt(_), &ty::TyRawPtr(_)) | (&ty::TyUint(_), &ty::TyRawPtr(_)) => {
220                                 span_lint_and_then(
221                                     cx,
222                                     USELESS_TRANSMUTE,
223                                     e.span,
224                                     "transmute from an integer to a pointer",
225                                     |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
226                                         db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
227                                     },
228                                 )
229                             },
230                             (&ty::TyFloat(_), &ty::TyRef(..)) |
231                             (&ty::TyFloat(_), &ty::TyRawPtr(_)) |
232                             (&ty::TyChar, &ty::TyRef(..)) |
233                             (&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
234                                 cx,
235                                 WRONG_TRANSMUTE,
236                                 e.span,
237                                 &format!("transmute from a `{}` to a pointer", from_ty),
238                             ),
239                             (&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
240                                 cx,
241                                 CROSSPOINTER_TRANSMUTE,
242                                 e.span,
243                                 &format!(
244                                     "transmute from a type (`{}`) to the type that it points to (`{}`)",
245                                     from_ty,
246                                     to_ty
247                                 ),
248                             ),
249                             (_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
250                                 cx,
251                                 CROSSPOINTER_TRANSMUTE,
252                                 e.span,
253                                 &format!(
254                                     "transmute from a type (`{}`) to a pointer to that type (`{}`)",
255                                     from_ty,
256                                     to_ty
257                                 ),
258                             ),
259                             (&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_ref_ty)) => span_lint_and_then(
260                                 cx,
261                                 TRANSMUTE_PTR_TO_REF,
262                                 e.span,
263                                 &format!(
264                                     "transmute from a pointer type (`{}`) to a reference type \
265                                      (`{}`)",
266                                     from_ty,
267                                     to_ty
268                                 ),
269                                 |db| {
270                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
271                                     let (deref, cast) = if to_ref_ty.mutbl == Mutability::MutMutable {
272                                         ("&mut *", "*mut")
273                                     } else {
274                                         ("&*", "*const")
275                                     };
276
277                                     let arg = if from_pty.ty == to_ref_ty.ty {
278                                         arg
279                                     } else {
280                                         arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty.ty)))
281                                     };
282
283                                     db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
284                                 },
285                             ),
286                             (&ty::TyInt(ast::IntTy::I32), &ty::TyChar) |
287                             (&ty::TyUint(ast::UintTy::U32), &ty::TyChar) => span_lint_and_then(
288                                 cx,
289                                 TRANSMUTE_INT_TO_CHAR,
290                                 e.span,
291                                 &format!("transmute from a `{}` to a `char`", from_ty),
292                                 |db| {
293                                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
294                                     let arg = if let ty::TyInt(_) = from_ty.sty {
295                                         arg.as_ty(ty::TyUint(ast::UintTy::U32))
296                                     } else {
297                                         arg
298                                     };
299                                     db.span_suggestion(
300                                         e.span,
301                                         "consider using",
302                                         format!("std::char::from_u32({}).unwrap()", arg.to_string()),
303                                     );
304                                 },
305                             ),
306                             (&ty::TyRef(_, ref ref_from), &ty::TyRef(_, ref ref_to)) => {
307                                 if_chain! {
308                                     if let (&ty::TySlice(slice_ty), &ty::TyStr) = (&ref_from.ty.sty, &ref_to.ty.sty);
309                                     if let ty::TyUint(ast::UintTy::U8) = slice_ty.sty;
310                                     if ref_from.mutbl == ref_to.mutbl;
311                                     then {
312                                         let postfix = if ref_from.mutbl == Mutability::MutMutable {
313                                             "_mut"
314                                         } else {
315                                             ""
316                                         };
317
318                                         span_lint_and_then(
319                                             cx,
320                                             TRANSMUTE_BYTES_TO_STR,
321                                             e.span,
322                                             &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
323                                             |db| {
324                                                 db.span_suggestion(
325                                                     e.span,
326                                                     "consider using",
327                                                     format!(
328                                                         "std::str::from_utf8{}({}).unwrap()",
329                                                         postfix,
330                                                         snippet(cx, args[0].span, ".."),
331                                                     ),
332                                                 );
333                                             }
334                                         )
335                                     }
336                                 }
337                             },
338                             (&ty::TyInt(ast::IntTy::I8), &ty::TyBool) | (&ty::TyUint(ast::UintTy::U8), &ty::TyBool) => {
339                                 span_lint_and_then(
340                                     cx,
341                                     TRANSMUTE_INT_TO_BOOL,
342                                     e.span,
343                                     &format!("transmute from a `{}` to a `bool`", from_ty),
344                                     |db| {
345                                         let arg = sugg::Sugg::hir(cx, &args[0], "..");
346                                         let zero = sugg::Sugg::NonParen(Cow::from("0"));
347                                         db.span_suggestion(
348                                             e.span,
349                                             "consider using",
350                                             sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
351                                         );
352                                     },
353                                 )
354                             },
355                             (&ty::TyInt(_), &ty::TyFloat(_)) | (&ty::TyUint(_), &ty::TyFloat(_)) => {
356                                 span_lint_and_then(
357                                     cx,
358                                     TRANSMUTE_INT_TO_FLOAT,
359                                     e.span,
360                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
361                                     |db| {
362                                         let arg = sugg::Sugg::hir(cx, &args[0], "..");
363                                         let arg = if let ty::TyInt(int_ty) = from_ty.sty {
364                                             arg.as_ty(format!(
365                                                 "u{}",
366                                                 int_ty
367                                                     .bit_width()
368                                                     .map_or_else(|| "size".to_string(), |v| v.to_string())
369                                             ))
370                                         } else {
371                                             arg
372                                         };
373                                         db.span_suggestion(
374                                             e.span,
375                                             "consider using",
376                                             format!("{}::from_bits({})", to_ty, arg.to_string()),
377                                         );
378                                     },
379                                 )
380                             },
381                             _ => return,
382                         };
383                     }
384                 }
385             }
386         }
387     }
388 }
389
390 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
391 /// not available , use
392 /// the type's `ToString` implementation. In weird cases it could lead to types
393 /// with invalid `'_`
394 /// lifetime, but it should be rare.
395 fn get_type_snippet(cx: &LateContext, path: &QPath, to_ref_ty: Ty) -> String {
396     let seg = last_path_segment(path);
397     if_chain! {
398         if let Some(ref params) = seg.parameters;
399         if !params.parenthesized;
400         if let Some(to_ty) = params.types.get(1);
401         if let TyRptr(_, ref to_ty) = to_ty.node;
402         then {
403             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
404         }
405     }
406
407     to_ref_ty.to_string()
408 }