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;
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;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for transmutes that can't ever be correct on any
16 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
18 /// **Known problems:** When accessing C, users might want to store pointer
19 /// sized objects in `extradata` arguments to save an allocation.
23 /// let ptr: *const T = core::intrinsics::transmute('x')
27 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
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.
34 /// **Why is this bad?** Readability. The code tricks people into thinking that
35 /// something complex is going on.
37 /// **Known problems:** None.
41 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
43 pub USELESS_TRANSMUTE,
45 "transmutes that have the same to and from types or could be a cast/coercion"
48 declare_clippy_lint! {
49 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
51 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
52 /// pointer to that type.
54 /// **Known problems:** None.
58 /// core::intrinsics::transmute(t) // where the result type is the same as
61 pub CROSSPOINTER_TRANSMUTE,
63 "transmutes that have to or from types that are a pointer to the other"
66 declare_clippy_lint! {
67 /// **What it does:** Checks for transmutes from a pointer to a reference.
69 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
71 /// **Known problems:** None.
76 /// let _: &T = std::mem::transmute(p); // where p: *const T
79 /// // can be written:
82 pub TRANSMUTE_PTR_TO_REF,
84 "transmutes from a pointer to a reference type"
87 declare_clippy_lint! {
88 /// **What it does:** Checks for transmutes from an integer to a `char`.
90 /// **Why is this bad?** Not every integer is a Unicode scalar value.
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`.
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
107 /// let _: char = std::mem::transmute(x); // where x: u32
111 /// let _ = std::char::from_u32(x).unwrap();
113 pub TRANSMUTE_INT_TO_CHAR,
115 "transmutes from an integer to a `char`"
118 declare_clippy_lint! {
119 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
121 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
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`.
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
136 /// let b: &[u8] = &[1_u8, 2_u8];
138 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
142 /// let _ = std::str::from_utf8(b).unwrap();
144 pub TRANSMUTE_BYTES_TO_STR,
146 "transmutes from a `&[u8]` to a `&str`"
149 declare_clippy_lint! {
150 /// **What it does:** Checks for transmutes from an integer to a `bool`.
152 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
154 /// **Known problems:** None.
160 /// let _: bool = std::mem::transmute(x); // where x: u8
164 /// let _: bool = x != 0;
166 pub TRANSMUTE_INT_TO_BOOL,
168 "transmutes from an integer to a `bool`"
171 declare_clippy_lint! {
172 /// **What it does:** Checks for transmutes from an integer to a float.
174 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
177 /// **Known problems:** None.
182 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
186 /// let _: f32 = f32::from_bits(1_u32);
188 pub TRANSMUTE_INT_TO_FLOAT,
190 "transmutes from an integer to a float"
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.
197 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
198 /// written as casts.
200 /// **Known problems:** None.
204 /// let ptr = &1u32 as *const u32;
206 /// // pointer-to-pointer transmute
207 /// let _: *const f32 = std::mem::transmute(ptr);
208 /// // ref-ref transmute
209 /// let _: &f32 = std::mem::transmute(&1u32);
211 /// // These can be respectively written:
212 /// let _ = ptr as *const f32;
213 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
215 pub TRANSMUTE_PTR_TO_PTR,
217 "transmutes from a pointer to a pointer / a reference to a reference"
220 declare_clippy_lint! {
221 /// **What it does:** Checks for transmutes between collections whose
222 /// types have different ABI, size or alignment.
224 /// **Why is this bad?** This is undefined behavior.
226 /// **Known problems:** Currently, we cannot know whether a type is a
227 /// collection, so we just lint the ones that come with `std`.
231 /// // different size, therefore likely out-of-bounds memory access
232 /// // You absolutely do not want this in your code!
234 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
238 /// You must always iterate, map and collect the values:
241 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
243 pub UNSOUND_COLLECTION_TRANSMUTE,
245 "transmute between collections of layout-incompatible types"
247 declare_lint_pass!(Transmute => [
248 CROSSPOINTER_TRANSMUTE,
249 TRANSMUTE_PTR_TO_REF,
250 TRANSMUTE_PTR_TO_PTR,
253 TRANSMUTE_INT_TO_CHAR,
254 TRANSMUTE_BYTES_TO_STR,
255 TRANSMUTE_INT_TO_BOOL,
256 TRANSMUTE_INT_TO_FLOAT,
257 UNSOUND_COLLECTION_TRANSMUTE,
260 // used to check for UNSOUND_COLLECTION_TRANSMUTE
261 static COLLECTIONS: &[&[&str]] = &[
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) {
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);
279 let from_ty = cx.tables.expr_ty(&args[0]);
280 let to_ty = cx.tables.expr_ty(e);
282 match (&from_ty.kind, &to_ty.kind) {
283 _ if from_ty == to_ty => span_lint(
287 &format!("transmute from a type (`{}`) to itself", from_ty),
289 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
293 "transmute from a reference to a pointer",
295 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
296 let rty_and_mut = ty::TypeAndMut {
301 let sugg = if ptr_ty == rty_and_mut {
304 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
307 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
311 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
315 "transmute from an integer to a pointer",
317 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
321 arg.as_ty(&to_ty.to_string()).to_string(),
322 Applicability::Unspecified,
327 (&ty::Float(_), &ty::Ref(..))
328 | (&ty::Float(_), &ty::RawPtr(_))
329 | (&ty::Char, &ty::Ref(..))
330 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
334 &format!("transmute from a `{}` to a pointer", from_ty),
336 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
338 CROSSPOINTER_TRANSMUTE,
341 "transmute from a type (`{}`) to the type that it points to (`{}`)",
345 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
347 CROSSPOINTER_TRANSMUTE,
350 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
354 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
356 TRANSMUTE_PTR_TO_REF,
359 "transmute from a pointer type (`{}`) to a reference type \
364 let arg = sugg::Sugg::hir(cx, &args[0], "..");
365 let (deref, cast) = if mutbl == Mutability::Mutable {
371 let arg = if from_pty.ty == to_ref_ty {
374 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
380 sugg::make_unop(deref, arg).to_string(),
381 Applicability::Unspecified,
385 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
388 TRANSMUTE_INT_TO_CHAR,
390 &format!("transmute from a `{}` to a `char`", from_ty),
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())
401 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
402 Applicability::Unspecified,
407 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
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;
413 let postfix = if from_mutbl == Mutability::Mutable {
421 TRANSMUTE_BYTES_TO_STR,
423 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
429 "std::str::from_utf8{}({}).unwrap()",
431 snippet(cx, args[0].span, ".."),
433 Applicability::Unspecified,
438 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
441 TRANSMUTE_PTR_TO_PTR,
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 {
449 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
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()
456 sugg_paren.addr_deref()
462 Applicability::Unspecified,
470 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
472 TRANSMUTE_PTR_TO_PTR,
474 "transmute from a pointer to a pointer",
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);
482 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
485 TRANSMUTE_INT_TO_BOOL,
487 &format!("transmute from a `{}` to a `bool`", from_ty),
489 let arg = sugg::Sugg::hir(cx, &args[0], "..");
490 let zero = sugg::Sugg::NonParen(Cow::from("0"));
494 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
495 Applicability::Unspecified,
500 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
502 TRANSMUTE_INT_TO_FLOAT,
504 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
506 let arg = sugg::Sugg::hir(cx, &args[0], "..");
507 let arg = if let ty::Int(int_ty) = from_ty.kind {
510 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
518 format!("{}::from_bits({})", to_ty, arg.to_string()),
519 Applicability::Unspecified,
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)) {
528 if from_substs.types().zip(to_substs.types())
529 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
532 UNSOUND_COLLECTION_TRANSMUTE,
535 "transmute from `{}` to `{}` with mismatched layout is unsound",
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);
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),
563 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
565 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
569 to_ref_ty.to_string()
572 // check if the component types of the transmuted collection and the result have different ABI,
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
580 // no idea about layout, so don't lint