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