]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
Less needless_doctest_main false positives
[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, sugg};
2 use if_chain::if_chain;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty::{self, Ty};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_errors::Applicability;
8 use std::borrow::Cow;
9 use syntax::ast;
10
11 declare_clippy_lint! {
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     /// ```ignore
22     /// let ptr: *const T = core::intrinsics::transmute('x')
23     /// ```
24     pub WRONG_TRANSMUTE,
25     correctness,
26     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
27 }
28
29 declare_clippy_lint! {
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,ignore
40     /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
41     /// ```
42     pub USELESS_TRANSMUTE,
43     complexity,
44     "transmutes that have the same to and from types or could be a cast/coercion"
45 }
46
47 declare_clippy_lint! {
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,ignore
57     /// core::intrinsics::transmute(t) // where the result type is the same as
58     ///                                // `*t` or `&t`'s
59     /// ```
60     pub CROSSPOINTER_TRANSMUTE,
61     complexity,
62     "transmutes that have to or from types that are a pointer to the other"
63 }
64
65 declare_clippy_lint! {
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,ignore
74     /// unsafe {
75     ///     let _: &T = std::mem::transmute(p); // where p: *const T
76     /// }
77     ///
78     /// // can be written:
79     /// let _: &T = &*p;
80     /// ```
81     pub TRANSMUTE_PTR_TO_REF,
82     complexity,
83     "transmutes from a pointer to a reference type"
84 }
85
86 declare_clippy_lint! {
87     /// **What it does:** Checks for transmutes from an integer to a `char`.
88     ///
89     /// **Why is this bad?** Not every integer is a Unicode scalar value.
90     ///
91     /// **Known problems:**
92     /// - [`from_u32`] which this lint suggests using is slower than `transmute`
93     /// as it needs to validate the input.
94     /// If you are certain that the input is always a valid Unicode scalar value,
95     /// use [`from_u32_unchecked`] which is as fast as `transmute`
96     /// but has a semantically meaningful name.
97     /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
98     ///
99     /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
100     /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
101     ///
102     /// **Example:**
103     /// ```rust
104     /// let x = 1_u32;
105     /// unsafe {
106     ///     let _: char = std::mem::transmute(x); // where x: u32
107     /// }
108     ///
109     /// // should be:
110     /// let _ = std::char::from_u32(x).unwrap();
111     /// ```
112     pub TRANSMUTE_INT_TO_CHAR,
113     complexity,
114     "transmutes from an integer to a `char`"
115 }
116
117 declare_clippy_lint! {
118     /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
119     ///
120     /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
121     ///
122     /// **Known problems:**
123     /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
124     /// as it needs to validate the input.
125     /// If you are certain that the input is always a valid UTF-8,
126     /// use [`from_utf8_unchecked`] which is as fast as `transmute`
127     /// but has a semantically meaningful name.
128     /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
129     ///
130     /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
131     /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
132     ///
133     /// **Example:**
134     /// ```rust
135     /// let b: &[u8] = &[1_u8, 2_u8];
136     /// unsafe {
137     ///     let _: &str = std::mem::transmute(b); // where b: &[u8]
138     /// }
139     ///
140     /// // should be:
141     /// let _ = std::str::from_utf8(b).unwrap();
142     /// ```
143     pub TRANSMUTE_BYTES_TO_STR,
144     complexity,
145     "transmutes from a `&[u8]` to a `&str`"
146 }
147
148 declare_clippy_lint! {
149     /// **What it does:** Checks for transmutes from an integer to a `bool`.
150     ///
151     /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
152     ///
153     /// **Known problems:** None.
154     ///
155     /// **Example:**
156     /// ```rust
157     /// let x = 1_u8;
158     /// unsafe {
159     ///     let _: bool = std::mem::transmute(x); // where x: u8
160     /// }
161     ///
162     /// // should be:
163     /// let _: bool = x != 0;
164     /// ```
165     pub TRANSMUTE_INT_TO_BOOL,
166     complexity,
167     "transmutes from an integer to a `bool`"
168 }
169
170 declare_clippy_lint! {
171     /// **What it does:** Checks for transmutes from an integer to a float.
172     ///
173     /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
174     /// and safe.
175     ///
176     /// **Known problems:** None.
177     ///
178     /// **Example:**
179     /// ```rust
180     /// unsafe {
181     ///     let _: f32 = std::mem::transmute(1_u32); // where x: u32
182     /// }
183     ///
184     /// // should be:
185     /// let _: f32 = f32::from_bits(1_u32);
186     /// ```
187     pub TRANSMUTE_INT_TO_FLOAT,
188     complexity,
189     "transmutes from an integer to a float"
190 }
191
192 declare_clippy_lint! {
193     /// **What it does:** Checks for transmutes from a pointer to a pointer, or
194     /// from a reference to a reference.
195     ///
196     /// **Why is this bad?** Transmutes are dangerous, and these can instead be
197     /// written as casts.
198     ///
199     /// **Known problems:** None.
200     ///
201     /// **Example:**
202     /// ```rust
203     /// let ptr = &1u32 as *const u32;
204     /// unsafe {
205     ///     // pointer-to-pointer transmute
206     ///     let _: *const f32 = std::mem::transmute(ptr);
207     ///     // ref-ref transmute
208     ///     let _: &f32 = std::mem::transmute(&1u32);
209     /// }
210     /// // These can be respectively written:
211     /// let _ = ptr as *const f32;
212     /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
213     /// ```
214     pub TRANSMUTE_PTR_TO_PTR,
215     complexity,
216     "transmutes from a pointer to a pointer / a reference to a reference"
217 }
218
219 declare_clippy_lint! {
220     /// **What it does:** Checks for transmutes between collections whose
221     /// types have different ABI, size or alignment.
222     ///
223     /// **Why is this bad?** This is undefined behavior.
224     ///
225     /// **Known problems:** Currently, we cannot know whether a type is a
226     /// collection, so we just lint the ones that come with `std`.
227     ///
228     /// **Example:**
229     /// ```rust
230     /// // different size, therefore likely out-of-bounds memory access
231     /// // You absolutely do not want this in your code!
232     /// unsafe {
233     ///     std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
234     /// };
235     /// ```
236     ///
237     /// You must always iterate, map and collect the values:
238     ///
239     /// ```rust
240     /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
241     /// ```
242     pub UNSOUND_COLLECTION_TRANSMUTE,
243     correctness,
244     "transmute between collections of layout-incompatible types"
245 }
246 declare_lint_pass!(Transmute => [
247     CROSSPOINTER_TRANSMUTE,
248     TRANSMUTE_PTR_TO_REF,
249     TRANSMUTE_PTR_TO_PTR,
250     USELESS_TRANSMUTE,
251     WRONG_TRANSMUTE,
252     TRANSMUTE_INT_TO_CHAR,
253     TRANSMUTE_BYTES_TO_STR,
254     TRANSMUTE_INT_TO_BOOL,
255     TRANSMUTE_INT_TO_FLOAT,
256     UNSOUND_COLLECTION_TRANSMUTE,
257 ]);
258
259 // used to check for UNSOUND_COLLECTION_TRANSMUTE
260 static COLLECTIONS: &[&[&str]] = &[
261     &paths::VEC,
262     &paths::VEC_DEQUE,
263     &paths::BINARY_HEAP,
264     &paths::BTREESET,
265     &paths::BTREEMAP,
266     &paths::HASHSET,
267     &paths::HASHMAP,
268 ];
269 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
270     #[allow(clippy::similar_names, clippy::too_many_lines)]
271     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
272         if_chain! {
273             if let ExprKind::Call(ref path_expr, ref args) = e.kind;
274             if let ExprKind::Path(ref qpath) = path_expr.kind;
275             if let Some(def_id) = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id();
276             if match_def_path(cx, def_id, &paths::TRANSMUTE);
277             then {
278                 let from_ty = cx.tables.expr_ty(&args[0]);
279                 let to_ty = cx.tables.expr_ty(e);
280
281                 match (&from_ty.kind, &to_ty.kind) {
282                     _ if from_ty == to_ty => span_lint(
283                         cx,
284                         USELESS_TRANSMUTE,
285                         e.span,
286                         &format!("transmute from a type (`{}`) to itself", from_ty),
287                     ),
288                     (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
289                         cx,
290                         USELESS_TRANSMUTE,
291                         e.span,
292                         "transmute from a reference to a pointer",
293                         |db| {
294                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
295                                 let rty_and_mut = ty::TypeAndMut {
296                                     ty: rty,
297                                     mutbl: rty_mutbl,
298                                 };
299
300                                 let sugg = if ptr_ty == rty_and_mut {
301                                     arg.as_ty(to_ty)
302                                 } else {
303                                     arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
304                                 };
305
306                                 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
307                             }
308                         },
309                     ),
310                     (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
311                         cx,
312                         USELESS_TRANSMUTE,
313                         e.span,
314                         "transmute from an integer to a pointer",
315                         |db| {
316                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
317                                 db.span_suggestion(
318                                     e.span,
319                                     "try",
320                                     arg.as_ty(&to_ty.to_string()).to_string(),
321                                     Applicability::Unspecified,
322                                 );
323                             }
324                         },
325                     ),
326                     (&ty::Float(_), &ty::Ref(..))
327                     | (&ty::Float(_), &ty::RawPtr(_))
328                     | (&ty::Char, &ty::Ref(..))
329                     | (&ty::Char, &ty::RawPtr(_)) => span_lint(
330                         cx,
331                         WRONG_TRANSMUTE,
332                         e.span,
333                         &format!("transmute from a `{}` to a pointer", from_ty),
334                     ),
335                     (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
336                         cx,
337                         CROSSPOINTER_TRANSMUTE,
338                         e.span,
339                         &format!(
340                             "transmute from a type (`{}`) to the type that it points to (`{}`)",
341                             from_ty, to_ty
342                         ),
343                     ),
344                     (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
345                         cx,
346                         CROSSPOINTER_TRANSMUTE,
347                         e.span,
348                         &format!(
349                             "transmute from a type (`{}`) to a pointer to that type (`{}`)",
350                             from_ty, to_ty
351                         ),
352                     ),
353                     (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
354                         cx,
355                         TRANSMUTE_PTR_TO_REF,
356                         e.span,
357                         &format!(
358                             "transmute from a pointer type (`{}`) to a reference type \
359                              (`{}`)",
360                             from_ty, to_ty
361                         ),
362                         |db| {
363                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
364                             let (deref, cast) = if mutbl == Mutability::Mutable {
365                                 ("&mut *", "*mut")
366                             } else {
367                                 ("&*", "*const")
368                             };
369
370                             let arg = if from_pty.ty == to_ref_ty {
371                                 arg
372                             } else {
373                                 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
374                             };
375
376                             db.span_suggestion(
377                                 e.span,
378                                 "try",
379                                 sugg::make_unop(deref, arg).to_string(),
380                                 Applicability::Unspecified,
381                             );
382                         },
383                     ),
384                     (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
385                         span_lint_and_then(
386                             cx,
387                             TRANSMUTE_INT_TO_CHAR,
388                             e.span,
389                             &format!("transmute from a `{}` to a `char`", from_ty),
390                             |db| {
391                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
392                                 let arg = if let ty::Int(_) = from_ty.kind {
393                                     arg.as_ty(ast::UintTy::U32.name_str())
394                                 } else {
395                                     arg
396                                 };
397                                 db.span_suggestion(
398                                     e.span,
399                                     "consider using",
400                                     format!("std::char::from_u32({}).unwrap()", arg.to_string()),
401                                     Applicability::Unspecified,
402                                 );
403                             },
404                         )
405                     },
406                     (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
407                         if_chain! {
408                             if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind, &ty_to.kind);
409                             if let ty::Uint(ast::UintTy::U8) = slice_ty.kind;
410                             if from_mutbl == to_mutbl;
411                             then {
412                                 let postfix = if from_mutbl == Mutability::Mutable {
413                                     "_mut"
414                                 } else {
415                                     ""
416                                 };
417
418                                 span_lint_and_then(
419                                     cx,
420                                     TRANSMUTE_BYTES_TO_STR,
421                                     e.span,
422                                     &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
423                                     |db| {
424                                         db.span_suggestion(
425                                             e.span,
426                                             "consider using",
427                                             format!(
428                                                 "std::str::from_utf8{}({}).unwrap()",
429                                                 postfix,
430                                                 snippet(cx, args[0].span, ".."),
431                                             ),
432                                             Applicability::Unspecified,
433                                         );
434                                     }
435                                 )
436                             } else {
437                                 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
438                                     span_lint_and_then(
439                                         cx,
440                                         TRANSMUTE_PTR_TO_PTR,
441                                         e.span,
442                                         "transmute from a reference to a reference",
443                                         |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
444                                             let ty_from_and_mut = ty::TypeAndMut {
445                                                 ty: ty_from,
446                                                 mutbl: from_mutbl
447                                             };
448                                             let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
449                                             let sugg_paren = arg
450                                                 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
451                                                 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
452                                             let sugg = if to_mutbl == Mutability::Mutable {
453                                                 sugg_paren.mut_addr_deref()
454                                             } else {
455                                                 sugg_paren.addr_deref()
456                                             };
457                                             db.span_suggestion(
458                                                 e.span,
459                                                 "try",
460                                                 sugg.to_string(),
461                                                 Applicability::Unspecified,
462                                             );
463                                         },
464                                     )
465                                 }
466                             }
467                         }
468                     },
469                     (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
470                         cx,
471                         TRANSMUTE_PTR_TO_PTR,
472                         e.span,
473                         "transmute from a pointer to a pointer",
474                         |db| {
475                             if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
476                                 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
477                                 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
478                             }
479                         },
480                     ),
481                     (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
482                         span_lint_and_then(
483                             cx,
484                             TRANSMUTE_INT_TO_BOOL,
485                             e.span,
486                             &format!("transmute from a `{}` to a `bool`", from_ty),
487                             |db| {
488                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
489                                 let zero = sugg::Sugg::NonParen(Cow::from("0"));
490                                 db.span_suggestion(
491                                     e.span,
492                                     "consider using",
493                                     sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
494                                     Applicability::Unspecified,
495                                 );
496                             },
497                         )
498                     },
499                     (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
500                         cx,
501                         TRANSMUTE_INT_TO_FLOAT,
502                         e.span,
503                         &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
504                         |db| {
505                             let arg = sugg::Sugg::hir(cx, &args[0], "..");
506                             let arg = if let ty::Int(int_ty) = from_ty.kind {
507                                 arg.as_ty(format!(
508                                     "u{}",
509                                     int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
510                                 ))
511                             } else {
512                                 arg
513                             };
514                             db.span_suggestion(
515                                 e.span,
516                                 "consider using",
517                                 format!("{}::from_bits({})", to_ty, arg.to_string()),
518                                 Applicability::Unspecified,
519                             );
520                         },
521                     ),
522                     (&ty::Adt(ref from_adt, ref from_substs), &ty::Adt(ref to_adt, ref to_substs)) => {
523                         if from_adt.did != to_adt.did ||
524                                 !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
525                             return;
526                         }
527                         if from_substs.types().zip(to_substs.types())
528                                               .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
529                             span_lint(
530                                 cx,
531                                 UNSOUND_COLLECTION_TRANSMUTE,
532                                 e.span,
533                                 &format!(
534                                     "transmute from `{}` to `{}` with mismatched layout is unsound",
535                                     from_ty,
536                                     to_ty
537                                 )
538                             );
539                         }
540                     },
541                     _ => return,
542                 }
543             }
544         }
545     }
546 }
547
548 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
549 /// not available , use
550 /// the type's `ToString` implementation. In weird cases it could lead to types
551 /// with invalid `'_`
552 /// lifetime, but it should be rare.
553 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
554     let seg = last_path_segment(path);
555     if_chain! {
556         if let Some(ref params) = seg.args;
557         if !params.parenthesized;
558         if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
559             GenericArg::Type(ty) => Some(ty),
560             _ => None,
561         }).nth(1);
562         if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
563         then {
564             return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
565         }
566     }
567
568     to_ref_ty.to_string()
569 }
570
571 // check if the component types of the transmuted collection and the result have different ABI,
572 // size or alignment
573 fn is_layout_incompatible<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
574     let from_ty_layout = cx.tcx.layout_of(ty::ParamEnv::empty().and(from));
575     let to_ty_layout = cx.tcx.layout_of(ty::ParamEnv::empty().and(to));
576     if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
577         from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
578     } else {
579         // no idea about layout, so don't lint
580         false
581     }
582 }