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;
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;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for transmutes that can't ever be correct on any
15 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
17 /// **Known problems:** When accessing C, users might want to store pointer
18 /// sized objects in `extradata` arguments to save an allocation.
22 /// let ptr: *const T = core::intrinsics::transmute('x')
26 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
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.
33 /// **Why is this bad?** Readability. The code tricks people into thinking that
34 /// something complex is going on.
36 /// **Known problems:** None.
40 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
42 pub USELESS_TRANSMUTE,
44 "transmutes that have the same to and from types or could be a cast/coercion"
47 declare_clippy_lint! {
48 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
50 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
51 /// pointer to that type.
53 /// **Known problems:** None.
57 /// core::intrinsics::transmute(t) // where the result type is the same as
60 pub CROSSPOINTER_TRANSMUTE,
62 "transmutes that have to or from types that are a pointer to the other"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for transmutes from a pointer to a reference.
68 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
70 /// **Known problems:** None.
75 /// let _: &T = std::mem::transmute(p); // where p: *const T
78 /// // can be written:
81 pub TRANSMUTE_PTR_TO_REF,
83 "transmutes from a pointer to a reference type"
86 declare_clippy_lint! {
87 /// **What it does:** Checks for transmutes from an integer to a `char`.
89 /// **Why is this bad?** Not every integer is a Unicode scalar value.
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`.
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
106 /// let _: char = std::mem::transmute(x); // where x: u32
110 /// let _ = std::char::from_u32(x).unwrap();
112 pub TRANSMUTE_INT_TO_CHAR,
114 "transmutes from an integer to a `char`"
117 declare_clippy_lint! {
118 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
120 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
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`.
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
135 /// let b: &[u8] = &[1_u8, 2_u8];
137 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
141 /// let _ = std::str::from_utf8(b).unwrap();
143 pub TRANSMUTE_BYTES_TO_STR,
145 "transmutes from a `&[u8]` to a `&str`"
148 declare_clippy_lint! {
149 /// **What it does:** Checks for transmutes from an integer to a `bool`.
151 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
153 /// **Known problems:** None.
159 /// let _: bool = std::mem::transmute(x); // where x: u8
163 /// let _: bool = x != 0;
165 pub TRANSMUTE_INT_TO_BOOL,
167 "transmutes from an integer to a `bool`"
170 declare_clippy_lint! {
171 /// **What it does:** Checks for transmutes from an integer to a float.
173 /// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
176 /// **Known problems:** None.
181 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
185 /// let _: f32 = f32::from_bits(1_u32);
187 pub TRANSMUTE_INT_TO_FLOAT,
189 "transmutes from an integer to a float"
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.
196 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
197 /// written as casts.
199 /// **Known problems:** None.
203 /// let ptr = &1u32 as *const u32;
205 /// // pointer-to-pointer transmute
206 /// let _: *const f32 = std::mem::transmute(ptr);
207 /// // ref-ref transmute
208 /// let _: &f32 = std::mem::transmute(&1u32);
210 /// // These can be respectively written:
211 /// let _ = ptr as *const f32;
212 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
214 pub TRANSMUTE_PTR_TO_PTR,
216 "transmutes from a pointer to a pointer / a reference to a reference"
219 declare_clippy_lint! {
220 /// **What it does:** Checks for transmutes between collections whose
221 /// types have different ABI, size or alignment.
223 /// **Why is this bad?** This is undefined behavior.
225 /// **Known problems:** Currently, we cannot know whether a type is a
226 /// collection, so we just lint the ones that come with `std`.
230 /// // different size, therefore likely out-of-bounds memory access
231 /// // You absolutely do not want this in your code!
233 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
237 /// You must always iterate, map and collect the values:
240 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
242 pub UNSOUND_COLLECTION_TRANSMUTE,
244 "transmute between collections of layout-incompatible types"
246 declare_lint_pass!(Transmute => [
247 CROSSPOINTER_TRANSMUTE,
248 TRANSMUTE_PTR_TO_REF,
249 TRANSMUTE_PTR_TO_PTR,
252 TRANSMUTE_INT_TO_CHAR,
253 TRANSMUTE_BYTES_TO_STR,
254 TRANSMUTE_INT_TO_BOOL,
255 TRANSMUTE_INT_TO_FLOAT,
256 UNSOUND_COLLECTION_TRANSMUTE,
259 // used to check for UNSOUND_COLLECTION_TRANSMUTE
260 static COLLECTIONS: &[&[&str]] = &[
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) {
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);
278 let from_ty = cx.tables.expr_ty(&args[0]);
279 let to_ty = cx.tables.expr_ty(e);
281 match (&from_ty.kind, &to_ty.kind) {
282 _ if from_ty == to_ty => span_lint(
286 &format!("transmute from a type (`{}`) to itself", from_ty),
288 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
292 "transmute from a reference to a pointer",
294 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
295 let rty_and_mut = ty::TypeAndMut {
300 let sugg = if ptr_ty == rty_and_mut {
303 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
306 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
310 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
314 "transmute from an integer to a pointer",
316 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
320 arg.as_ty(&to_ty.to_string()).to_string(),
321 Applicability::Unspecified,
326 (&ty::Float(_), &ty::Ref(..))
327 | (&ty::Float(_), &ty::RawPtr(_))
328 | (&ty::Char, &ty::Ref(..))
329 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
333 &format!("transmute from a `{}` to a pointer", from_ty),
335 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
337 CROSSPOINTER_TRANSMUTE,
340 "transmute from a type (`{}`) to the type that it points to (`{}`)",
344 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
346 CROSSPOINTER_TRANSMUTE,
349 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
353 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
355 TRANSMUTE_PTR_TO_REF,
358 "transmute from a pointer type (`{}`) to a reference type \
363 let arg = sugg::Sugg::hir(cx, &args[0], "..");
364 let (deref, cast) = if mutbl == Mutability::Mutable {
370 let arg = if from_pty.ty == to_ref_ty {
373 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
379 sugg::make_unop(deref, arg).to_string(),
380 Applicability::Unspecified,
384 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
387 TRANSMUTE_INT_TO_CHAR,
389 &format!("transmute from a `{}` to a `char`", from_ty),
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())
400 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
401 Applicability::Unspecified,
406 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
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;
412 let postfix = if from_mutbl == Mutability::Mutable {
420 TRANSMUTE_BYTES_TO_STR,
422 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
428 "std::str::from_utf8{}({}).unwrap()",
430 snippet(cx, args[0].span, ".."),
432 Applicability::Unspecified,
437 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
440 TRANSMUTE_PTR_TO_PTR,
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 {
448 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
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()
455 sugg_paren.addr_deref()
461 Applicability::Unspecified,
469 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
471 TRANSMUTE_PTR_TO_PTR,
473 "transmute from a pointer to a pointer",
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);
481 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
484 TRANSMUTE_INT_TO_BOOL,
486 &format!("transmute from a `{}` to a `bool`", from_ty),
488 let arg = sugg::Sugg::hir(cx, &args[0], "..");
489 let zero = sugg::Sugg::NonParen(Cow::from("0"));
493 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
494 Applicability::Unspecified,
499 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
501 TRANSMUTE_INT_TO_FLOAT,
503 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
505 let arg = sugg::Sugg::hir(cx, &args[0], "..");
506 let arg = if let ty::Int(int_ty) = from_ty.kind {
509 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
517 format!("{}::from_bits({})", to_ty, arg.to_string()),
518 Applicability::Unspecified,
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)) {
527 if from_substs.types().zip(to_substs.types())
528 .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
531 UNSOUND_COLLECTION_TRANSMUTE,
534 "transmute from `{}` to `{}` with mismatched layout is unsound",
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);
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),
562 if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
564 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
568 to_ref_ty.to_string()
571 // check if the component types of the transmuted collection and the result have different ABI,
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
579 // no idea about layout, so don't lint