]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/transmute.rs
New upstream version 1.28.0~beta.14+dfsg1
[rustc.git] / src / tools / clippy / 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_clippy_lint! {
22 pub WRONG_TRANSMUTE,
23 correctness,
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_clippy_lint! {
40 pub USELESS_TRANSMUTE,
41 complexity,
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_clippy_lint! {
58 pub CROSSPOINTER_TRANSMUTE,
59 complexity,
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_clippy_lint! {
76 pub TRANSMUTE_PTR_TO_REF,
77 complexity,
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_clippy_lint! {
103 pub TRANSMUTE_INT_TO_CHAR,
104 complexity,
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_clippy_lint! {
130 pub TRANSMUTE_BYTES_TO_STR,
131 complexity,
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_clippy_lint! {
148 pub TRANSMUTE_INT_TO_BOOL,
149 complexity,
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_clippy_lint! {
166 pub TRANSMUTE_INT_TO_FLOAT,
167 complexity,
168 "transmutes from an integer to a float"
169 }
170
171 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
172 /// from a reference to a reference.
173 ///
174 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
175 /// written as casts.
176 ///
177 /// **Known problems:** None.
178 ///
179 /// **Example:**
180 /// ```rust
181 /// let ptr = &1u32 as *const u32;
182 /// unsafe {
183 /// // pointer-to-pointer transmute
184 /// let _: *const f32 = std::mem::transmute(ptr);
185 /// // ref-ref transmute
186 /// let _: &f32 = std::mem::transmute(&1u32);
187 /// }
188 /// // These can be respectively written:
189 /// let _ = ptr as *const f32
190 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
191 /// ```
192 declare_clippy_lint! {
193 pub TRANSMUTE_PTR_TO_PTR,
194 complexity,
195 "transmutes from a pointer to a reference type"
196 }
197
198 pub struct Transmute;
199
200 impl LintPass for Transmute {
201 fn get_lints(&self) -> LintArray {
202 lint_array!(
203 CROSSPOINTER_TRANSMUTE,
204 TRANSMUTE_PTR_TO_REF,
205 TRANSMUTE_PTR_TO_PTR,
206 USELESS_TRANSMUTE,
207 WRONG_TRANSMUTE,
208 TRANSMUTE_INT_TO_CHAR,
209 TRANSMUTE_BYTES_TO_STR,
210 TRANSMUTE_INT_TO_BOOL,
211 TRANSMUTE_INT_TO_FLOAT,
212 )
213 }
214 }
215
216 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
217 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
218 if let ExprCall(ref path_expr, ref args) = e.node {
219 if let ExprPath(ref qpath) = path_expr.node {
220 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
221 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
222 let from_ty = cx.tables.expr_ty(&args[0]);
223 let to_ty = cx.tables.expr_ty(e);
224
225 match (&from_ty.sty, &to_ty.sty) {
226 _ if from_ty == to_ty => span_lint(
227 cx,
228 USELESS_TRANSMUTE,
229 e.span,
230 &format!("transmute from a type (`{}`) to itself", from_ty),
231 ),
232 (&ty::TyRef(_, rty, rty_mutbl), &ty::TyRawPtr(ptr_ty)) => span_lint_and_then(
233 cx,
234 USELESS_TRANSMUTE,
235 e.span,
236 "transmute from a reference to a pointer",
237 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
238 let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
239
240 let sugg = if ptr_ty == rty_and_mut {
241 arg.as_ty(to_ty)
242 } else {
243 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
244 };
245
246 db.span_suggestion(e.span, "try", sugg.to_string());
247 },
248 ),
249 (&ty::TyInt(_), &ty::TyRawPtr(_)) | (&ty::TyUint(_), &ty::TyRawPtr(_)) => {
250 span_lint_and_then(
251 cx,
252 USELESS_TRANSMUTE,
253 e.span,
254 "transmute from an integer to a pointer",
255 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
256 db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
257 },
258 )
259 },
260 (&ty::TyFloat(_), &ty::TyRef(..)) |
261 (&ty::TyFloat(_), &ty::TyRawPtr(_)) |
262 (&ty::TyChar, &ty::TyRef(..)) |
263 (&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
264 cx,
265 WRONG_TRANSMUTE,
266 e.span,
267 &format!("transmute from a `{}` to a pointer", from_ty),
268 ),
269 (&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
270 cx,
271 CROSSPOINTER_TRANSMUTE,
272 e.span,
273 &format!(
274 "transmute from a type (`{}`) to the type that it points to (`{}`)",
275 from_ty,
276 to_ty
277 ),
278 ),
279 (_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
280 cx,
281 CROSSPOINTER_TRANSMUTE,
282 e.span,
283 &format!(
284 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
285 from_ty,
286 to_ty
287 ),
288 ),
289 (&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_ref_ty, mutbl)) => span_lint_and_then(
290 cx,
291 TRANSMUTE_PTR_TO_REF,
292 e.span,
293 &format!(
294 "transmute from a pointer type (`{}`) to a reference type \
295 (`{}`)",
296 from_ty,
297 to_ty
298 ),
299 |db| {
300 let arg = sugg::Sugg::hir(cx, &args[0], "..");
301 let (deref, cast) = if mutbl == Mutability::MutMutable {
302 ("&mut *", "*mut")
303 } else {
304 ("&*", "*const")
305 };
306
307 let arg = if from_pty.ty == to_ref_ty {
308 arg
309 } else {
310 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
311 };
312
313 db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
314 },
315 ),
316 (&ty::TyInt(ast::IntTy::I32), &ty::TyChar) |
317 (&ty::TyUint(ast::UintTy::U32), &ty::TyChar) => span_lint_and_then(
318 cx,
319 TRANSMUTE_INT_TO_CHAR,
320 e.span,
321 &format!("transmute from a `{}` to a `char`", from_ty),
322 |db| {
323 let arg = sugg::Sugg::hir(cx, &args[0], "..");
324 let arg = if let ty::TyInt(_) = from_ty.sty {
325 arg.as_ty(ty::TyUint(ast::UintTy::U32))
326 } else {
327 arg
328 };
329 db.span_suggestion(
330 e.span,
331 "consider using",
332 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
333 );
334 },
335 ),
336 (&ty::TyRef(_, ty_from, from_mutbl), &ty::TyRef(_, ty_to, to_mutbl)) => {
337 if_chain! {
338 if let (&ty::TySlice(slice_ty), &ty::TyStr) = (&ty_from.sty, &ty_to.sty);
339 if let ty::TyUint(ast::UintTy::U8) = slice_ty.sty;
340 if from_mutbl == to_mutbl;
341 then {
342 let postfix = if from_mutbl == Mutability::MutMutable {
343 "_mut"
344 } else {
345 ""
346 };
347
348 span_lint_and_then(
349 cx,
350 TRANSMUTE_BYTES_TO_STR,
351 e.span,
352 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
353 |db| {
354 db.span_suggestion(
355 e.span,
356 "consider using",
357 format!(
358 "std::str::from_utf8{}({}).unwrap()",
359 postfix,
360 snippet(cx, args[0].span, ".."),
361 ),
362 );
363 }
364 )
365 } else {
366 span_lint_and_then(
367 cx,
368 TRANSMUTE_PTR_TO_PTR,
369 e.span,
370 "transmute from a reference to a reference",
371 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
372 let ty_from_and_mut = ty::TypeAndMut { ty: ty_from, mutbl: from_mutbl };
373 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
374 let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
375 let sugg = if to_mutbl == Mutability::MutMutable {
376 sugg_paren.mut_addr_deref()
377 } else {
378 sugg_paren.addr_deref()
379 };
380 db.span_suggestion(e.span, "try", sugg.to_string());
381 },
382 )
383 }
384 }
385 },
386 (&ty::TyRawPtr(_), &ty::TyRawPtr(to_ty)) => span_lint_and_then(
387 cx,
388 TRANSMUTE_PTR_TO_PTR,
389 e.span,
390 "transmute from a pointer to a pointer",
391 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
392 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
393 db.span_suggestion(e.span, "try", sugg.to_string());
394 },
395 ),
396 (&ty::TyInt(ast::IntTy::I8), &ty::TyBool) | (&ty::TyUint(ast::UintTy::U8), &ty::TyBool) => {
397 span_lint_and_then(
398 cx,
399 TRANSMUTE_INT_TO_BOOL,
400 e.span,
401 &format!("transmute from a `{}` to a `bool`", from_ty),
402 |db| {
403 let arg = sugg::Sugg::hir(cx, &args[0], "..");
404 let zero = sugg::Sugg::NonParen(Cow::from("0"));
405 db.span_suggestion(
406 e.span,
407 "consider using",
408 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
409 );
410 },
411 )
412 },
413 (&ty::TyInt(_), &ty::TyFloat(_)) | (&ty::TyUint(_), &ty::TyFloat(_)) => {
414 span_lint_and_then(
415 cx,
416 TRANSMUTE_INT_TO_FLOAT,
417 e.span,
418 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
419 |db| {
420 let arg = sugg::Sugg::hir(cx, &args[0], "..");
421 let arg = if let ty::TyInt(int_ty) = from_ty.sty {
422 arg.as_ty(format!(
423 "u{}",
424 int_ty
425 .bit_width()
426 .map_or_else(|| "size".to_string(), |v| v.to_string())
427 ))
428 } else {
429 arg
430 };
431 db.span_suggestion(
432 e.span,
433 "consider using",
434 format!("{}::from_bits({})", to_ty, arg.to_string()),
435 );
436 },
437 )
438 },
439 _ => return,
440 };
441 }
442 }
443 }
444 }
445 }
446 }
447
448 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
449 /// not available , use
450 /// the type's `ToString` implementation. In weird cases it could lead to types
451 /// with invalid `'_`
452 /// lifetime, but it should be rare.
453 fn get_type_snippet(cx: &LateContext, path: &QPath, to_ref_ty: Ty) -> String {
454 let seg = last_path_segment(path);
455 if_chain! {
456 if let Some(ref params) = seg.parameters;
457 if !params.parenthesized;
458 if let Some(to_ty) = params.types.get(1);
459 if let TyRptr(_, ref to_ty) = to_ty.node;
460 then {
461 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
462 }
463 }
464
465 to_ref_ty.to_string()
466 }