2 use rustc::{declare_lint, lint_array};
3 use if_chain::if_chain;
4 use rustc::ty::{self, Ty};
8 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
9 use crate::utils::{opt_def_id, sugg};
11 /// **What it does:** Checks for transmutes that can't ever be correct on any
14 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
16 /// **Known problems:** When accessing C, users might want to store pointer
17 /// sized objects in `extradata` arguments to save an allocation.
21 /// let ptr: *const T = core::intrinsics::transmute('x')
23 declare_clippy_lint! {
26 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
29 /// **What it does:** Checks for transmutes to the original type of the object
30 /// and transmutes that could be a cast.
32 /// **Why is this bad?** Readability. The code tricks people into thinking that
33 /// something complex is going on.
35 /// **Known problems:** None.
39 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
41 declare_clippy_lint! {
42 pub USELESS_TRANSMUTE,
44 "transmutes that have the same to and from types or could be a cast/coercion"
47 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
49 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
50 /// pointer to that type.
52 /// **Known problems:** None.
56 /// core::intrinsics::transmute(t) // where the result type is the same as
59 declare_clippy_lint! {
60 pub CROSSPOINTER_TRANSMUTE,
62 "transmutes that have to or from types that are a pointer to the other"
65 /// **What it does:** Checks for transmutes from a pointer to a reference.
67 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
69 /// **Known problems:** None.
73 /// let _: &T = std::mem::transmute(p); // where p: *const T
74 /// // can be written:
77 declare_clippy_lint! {
78 pub TRANSMUTE_PTR_TO_REF,
80 "transmutes from a pointer to a reference type"
83 /// **What it does:** Checks for transmutes from an integer to a `char`.
85 /// **Why is this bad?** Not every integer is a Unicode scalar value.
87 /// **Known problems:**
88 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
89 /// as it needs to validate the input.
90 /// If you are certain that the input is always a valid Unicode scalar value,
91 /// use [`from_u32_unchecked`] which is as fast as `transmute`
92 /// but has a semantically meaningful name.
93 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
95 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
96 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
100 /// let _: char = std::mem::transmute(x); // where x: u32
102 /// let _ = std::char::from_u32(x).unwrap();
104 declare_clippy_lint! {
105 pub TRANSMUTE_INT_TO_CHAR,
107 "transmutes from an integer to a `char`"
110 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
112 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
114 /// **Known problems:**
115 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
116 /// as it needs to validate the input.
117 /// If you are certain that the input is always a valid UTF-8,
118 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
119 /// but has a semantically meaningful name.
120 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
122 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
123 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
127 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
129 /// let _ = std::str::from_utf8(b).unwrap();
131 declare_clippy_lint! {
132 pub TRANSMUTE_BYTES_TO_STR,
134 "transmutes from a `&[u8]` to a `&str`"
137 /// **What it does:** Checks for transmutes from an integer to a `bool`.
139 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
141 /// **Known problems:** None.
145 /// let _: bool = std::mem::transmute(x); // where x: u8
147 /// let _: bool = x != 0;
149 declare_clippy_lint! {
150 pub TRANSMUTE_INT_TO_BOOL,
152 "transmutes from an integer to a `bool`"
155 /// **What it does:** Checks for transmutes from an integer to a float.
157 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
159 /// **Known problems:** None.
163 /// let _: f32 = std::mem::transmute(x); // where x: u32
165 /// let _: f32 = f32::from_bits(x);
167 declare_clippy_lint! {
168 pub TRANSMUTE_INT_TO_FLOAT,
170 "transmutes from an integer to a float"
173 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
174 /// from a reference to a reference.
176 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
177 /// written as casts.
179 /// **Known problems:** None.
183 /// let ptr = &1u32 as *const u32;
185 /// // pointer-to-pointer transmute
186 /// let _: *const f32 = std::mem::transmute(ptr);
187 /// // ref-ref transmute
188 /// let _: &f32 = std::mem::transmute(&1u32);
190 /// // These can be respectively written:
191 /// let _ = ptr as *const f32
192 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
194 declare_clippy_lint! {
195 pub TRANSMUTE_PTR_TO_PTR,
197 "transmutes from a pointer to a pointer / a reference to a reference"
200 pub struct Transmute;
202 impl LintPass for Transmute {
203 fn get_lints(&self) -> LintArray {
205 CROSSPOINTER_TRANSMUTE,
206 TRANSMUTE_PTR_TO_REF,
207 TRANSMUTE_PTR_TO_PTR,
210 TRANSMUTE_INT_TO_CHAR,
211 TRANSMUTE_BYTES_TO_STR,
212 TRANSMUTE_INT_TO_BOOL,
213 TRANSMUTE_INT_TO_FLOAT,
218 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
219 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
220 if let ExprKind::Call(ref path_expr, ref args) = e.node {
221 if let ExprKind::Path(ref qpath) = path_expr.node {
222 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
223 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
224 let from_ty = cx.tables.expr_ty(&args[0]);
225 let to_ty = cx.tables.expr_ty(e);
227 match (&from_ty.sty, &to_ty.sty) {
228 _ if from_ty == to_ty => span_lint(
232 &format!("transmute from a type (`{}`) to itself", from_ty),
234 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
238 "transmute from a reference to a pointer",
239 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
240 let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
242 let sugg = if ptr_ty == rty_and_mut {
245 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
248 db.span_suggestion(e.span, "try", sugg.to_string());
251 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => {
256 "transmute from an integer to a pointer",
257 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
258 db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
262 (&ty::Float(_), &ty::Ref(..)) |
263 (&ty::Float(_), &ty::RawPtr(_)) |
264 (&ty::Char, &ty::Ref(..)) |
265 (&ty::Char, &ty::RawPtr(_)) => span_lint(
269 &format!("transmute from a `{}` to a pointer", from_ty),
271 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
273 CROSSPOINTER_TRANSMUTE,
276 "transmute from a type (`{}`) to the type that it points to (`{}`)",
281 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
283 CROSSPOINTER_TRANSMUTE,
286 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
291 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
293 TRANSMUTE_PTR_TO_REF,
296 "transmute from a pointer type (`{}`) to a reference type \
302 let arg = sugg::Sugg::hir(cx, &args[0], "..");
303 let (deref, cast) = if mutbl == Mutability::MutMutable {
309 let arg = if from_pty.ty == to_ref_ty {
312 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
315 db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
318 (&ty::Int(ast::IntTy::I32), &ty::Char) |
319 (&ty::Uint(ast::UintTy::U32), &ty::Char) => span_lint_and_then(
321 TRANSMUTE_INT_TO_CHAR,
323 &format!("transmute from a `{}` to a `char`", from_ty),
325 let arg = sugg::Sugg::hir(cx, &args[0], "..");
326 let arg = if let ty::Int(_) = from_ty.sty {
327 arg.as_ty(ty::Uint(ast::UintTy::U32))
334 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
338 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
340 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.sty, &ty_to.sty);
341 if let ty::Uint(ast::UintTy::U8) = slice_ty.sty;
342 if from_mutbl == to_mutbl;
344 let postfix = if from_mutbl == Mutability::MutMutable {
352 TRANSMUTE_BYTES_TO_STR,
354 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
360 "std::str::from_utf8{}({}).unwrap()",
362 snippet(cx, args[0].span, ".."),
368 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
371 TRANSMUTE_PTR_TO_PTR,
373 "transmute from a reference to a reference",
374 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
375 let ty_from_and_mut = ty::TypeAndMut { ty: ty_from, mutbl: from_mutbl };
376 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
377 let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
378 let sugg = if to_mutbl == Mutability::MutMutable {
379 sugg_paren.mut_addr_deref()
381 sugg_paren.addr_deref()
383 db.span_suggestion(e.span, "try", sugg.to_string());
390 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
392 TRANSMUTE_PTR_TO_PTR,
394 "transmute from a pointer to a pointer",
395 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
396 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
397 db.span_suggestion(e.span, "try", sugg.to_string());
400 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
403 TRANSMUTE_INT_TO_BOOL,
405 &format!("transmute from a `{}` to a `bool`", from_ty),
407 let arg = sugg::Sugg::hir(cx, &args[0], "..");
408 let zero = sugg::Sugg::NonParen(Cow::from("0"));
412 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
417 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => {
420 TRANSMUTE_INT_TO_FLOAT,
422 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
424 let arg = sugg::Sugg::hir(cx, &args[0], "..");
425 let arg = if let ty::Int(int_ty) = from_ty.sty {
430 .map_or_else(|| "size".to_string(), |v| v.to_string())
438 format!("{}::from_bits({})", to_ty, arg.to_string()),
452 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
453 /// not available , use
454 /// the type's `ToString` implementation. In weird cases it could lead to types
455 /// with invalid `'_`
456 /// lifetime, but it should be rare.
457 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
458 let seg = last_path_segment(path);
460 if let Some(ref params) = seg.args;
461 if !params.parenthesized;
462 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
463 GenericArg::Type(ty) => Some(ty),
464 GenericArg::Lifetime(_) => None,
466 if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
468 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
472 to_ref_ty.to_string()