]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute.rs
88ed11d26e581b57333c0f223e4e398265d81e52
[rust.git] / clippy_lints / src / transmute.rs
1 use rustc::lint::*;
2 use rustc::ty::TypeVariants::{TyRawPtr, TyRef};
3 use rustc::ty;
4 use rustc::hir::*;
5 use utils::{match_def_path, paths, span_lint, span_lint_and_then};
6 use utils::sugg;
7
8 /// **What it does:** This lint checks for transmutes that can't ever be correct on any architecture
9 ///
10 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour
11 ///
12 /// **Known problems:** When accessing C, users might want to store pointer sized objects in `extradata` arguments to save an allocation.
13 ///
14 /// **Example:** `let ptr: *const T = core::intrinsics::transmute('x')`.
15 declare_lint! {
16     pub WRONG_TRANSMUTE,
17     Warn,
18     "transmutes that are confusing at best, undefined behaviour at worst and always useless"
19 }
20
21 /// **What it does:** This lint checks for transmutes to the original type of the object and transmutes that could be a cast.
22 ///
23 /// **Why is this bad?** Readability. The code tricks people into thinking that something complex is going on
24 ///
25 /// **Known problems:** None.
26 ///
27 /// **Example:** `core::intrinsics::transmute(t)` where the result type is the same as `t`'s.
28 declare_lint! {
29     pub USELESS_TRANSMUTE,
30     Warn,
31     "transmutes that have the same to and from types or could be a cast/coercion"
32 }
33
34 /// **What it does:*** This lint checks for transmutes between a type `T` and `*T`.
35 ///
36 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a pointer to that type.
37 ///
38 /// **Known problems:** None.
39 ///
40 /// **Example:** `core::intrinsics::transmute(t)` where the result type is the same as `*t` or `&t`'s.
41 declare_lint! {
42     pub CROSSPOINTER_TRANSMUTE,
43     Warn,
44     "transmutes that have to or from types that are a pointer to the other"
45 }
46
47 /// **What it does:*** This lint checks for transmutes from a pointer to a reference.
48 ///
49 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
50 ///
51 /// **Known problems:** None.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// let _: &T = std::mem::transmute(p); // where p: *const T
56 /// // can be written:
57 /// let _: &T = &*p;
58 /// ```
59 declare_lint! {
60     pub TRANSMUTE_PTR_TO_REF,
61     Warn,
62     "transmutes from a pointer to a reference type"
63 }
64
65 pub struct Transmute;
66
67 impl LintPass for Transmute {
68     fn get_lints(&self) -> LintArray {
69         lint_array![CROSSPOINTER_TRANSMUTE, TRANSMUTE_PTR_TO_REF, USELESS_TRANSMUTE, WRONG_TRANSMUTE]
70     }
71 }
72
73 impl LateLintPass for Transmute {
74     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
75         if let ExprCall(ref path_expr, ref args) = e.node {
76             if let ExprPath(None, _) = path_expr.node {
77                 let def_id = cx.tcx.expect_def(path_expr.id).def_id();
78
79                 if match_def_path(cx, def_id, &paths::TRANSMUTE) {
80                     let from_ty = cx.tcx.expr_ty(&args[0]);
81                     let to_ty = cx.tcx.expr_ty(e);
82
83                     match (&from_ty.sty, &to_ty.sty) {
84                         _ if from_ty == to_ty => span_lint(
85                             cx,
86                             USELESS_TRANSMUTE,
87                             e.span,
88                             &format!("transmute from a type (`{}`) to itself", from_ty),
89                         ),
90                         (&TyRef(_, rty), &TyRawPtr(ptr_ty)) => span_lint_and_then(
91                             cx,
92                             USELESS_TRANSMUTE,
93                             e.span,
94                             "transmute from a reference to a pointer",
95                             |db| {
96                                 if let Some(arg) = sugg::Sugg::hir_opt(cx, &*args[0]) {
97                                     let sugg = if ptr_ty == rty {
98                                         arg.as_ty(&to_ty.to_string())
99                                     } else {
100                                         arg.as_ty(&format!("{} as {}", cx.tcx.mk_ptr(rty), to_ty))
101                                     };
102
103                                     db.span_suggestion(e.span, "try", sugg.to_string());
104                                 }
105                             },
106                         ),
107                         (&ty::TyInt(_), &TyRawPtr(_)) |
108                         (&ty::TyUint(_), &TyRawPtr(_)) => span_lint_and_then(
109                             cx,
110                             USELESS_TRANSMUTE,
111                             e.span,
112                             "transmute from an integer to a pointer",
113                             |db| {
114                                 if let Some(arg) = sugg::Sugg::hir_opt(cx, &*args[0]) {
115                                     db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
116                                 }
117                             },
118                         ),
119                         (&ty::TyFloat(_), &TyRef(..)) |
120                         (&ty::TyFloat(_), &TyRawPtr(_)) |
121                         (&ty::TyChar, &TyRef(..)) |
122                         (&ty::TyChar, &TyRawPtr(_)) => span_lint(
123                             cx,
124                             WRONG_TRANSMUTE,
125                             e.span,
126                             &format!("transmute from a `{}` to a pointer", from_ty),
127                         ),
128                         (&TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
129                             cx,
130                             CROSSPOINTER_TRANSMUTE,
131                             e.span,
132                             &format!("transmute from a type (`{}`) to the type that it points to (`{}`)",
133                                      from_ty,
134                                      to_ty),
135                         ),
136                         (_, &TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
137                             cx,
138                             CROSSPOINTER_TRANSMUTE,
139                             e.span,
140                             &format!("transmute from a type (`{}`) to a pointer to that type (`{}`)",
141                                      from_ty,
142                                      to_ty),
143                         ),
144                         (&TyRawPtr(from_pty), &TyRef(_, to_rty)) => span_lint_and_then(
145                             cx,
146                             TRANSMUTE_PTR_TO_REF,
147                             e.span,
148                             &format!("transmute from a pointer type (`{}`) to a reference type (`{}`)",
149                                     from_ty,
150                                     to_ty),
151                             |db| {
152                                 let arg = sugg::Sugg::hir(cx, &args[0], "..");
153                                 let (deref, cast) = if to_rty.mutbl == Mutability::MutMutable {
154                                     ("&mut *", "*mut")
155                                 } else {
156                                     ("&*", "*const")
157                                 };
158
159
160                                 let arg = if from_pty.ty == to_rty.ty {
161                                     arg
162                                 } else {
163                                     arg.as_ty(&format!("{} {}", cast, to_rty.ty))
164                                 };
165
166                                 db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
167                             },
168                         ),
169                         _ => return,
170                     };
171                 }
172             }
173         }
174     }
175 }