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_lint_pass!(Transmute => [
220 CROSSPOINTER_TRANSMUTE,
221 TRANSMUTE_PTR_TO_REF,
222 TRANSMUTE_PTR_TO_PTR,
225 TRANSMUTE_INT_TO_CHAR,
226 TRANSMUTE_BYTES_TO_STR,
227 TRANSMUTE_INT_TO_BOOL,
228 TRANSMUTE_INT_TO_FLOAT,
231 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
232 #[allow(clippy::similar_names, clippy::too_many_lines)]
233 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
234 if let ExprKind::Call(ref path_expr, ref args) = e.node {
235 if let ExprKind::Path(ref qpath) = path_expr.node {
236 if let Some(def_id) = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
237 if match_def_path(cx, def_id, &paths::TRANSMUTE) {
238 let from_ty = cx.tables.expr_ty(&args[0]);
239 let to_ty = cx.tables.expr_ty(e);
241 match (&from_ty.sty, &to_ty.sty) {
242 _ if from_ty == to_ty => span_lint(
246 &format!("transmute from a type (`{}`) to itself", from_ty),
248 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
252 "transmute from a reference to a pointer",
254 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
255 let rty_and_mut = ty::TypeAndMut {
260 let sugg = if ptr_ty == rty_and_mut {
263 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
266 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
270 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => span_lint_and_then(
274 "transmute from an integer to a pointer",
276 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
280 arg.as_ty(&to_ty.to_string()).to_string(),
281 Applicability::Unspecified,
286 (&ty::Float(_), &ty::Ref(..))
287 | (&ty::Float(_), &ty::RawPtr(_))
288 | (&ty::Char, &ty::Ref(..))
289 | (&ty::Char, &ty::RawPtr(_)) => span_lint(
293 &format!("transmute from a `{}` to a pointer", from_ty),
295 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
297 CROSSPOINTER_TRANSMUTE,
300 "transmute from a type (`{}`) to the type that it points to (`{}`)",
304 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
306 CROSSPOINTER_TRANSMUTE,
309 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
313 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
315 TRANSMUTE_PTR_TO_REF,
318 "transmute from a pointer type (`{}`) to a reference type \
323 let arg = sugg::Sugg::hir(cx, &args[0], "..");
324 let (deref, cast) = if mutbl == Mutability::MutMutable {
330 let arg = if from_pty.ty == to_ref_ty {
333 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
339 sugg::make_unop(deref, arg).to_string(),
340 Applicability::Unspecified,
344 (&ty::Int(ast::IntTy::I32), &ty::Char) | (&ty::Uint(ast::UintTy::U32), &ty::Char) => {
347 TRANSMUTE_INT_TO_CHAR,
349 &format!("transmute from a `{}` to a `char`", from_ty),
351 let arg = sugg::Sugg::hir(cx, &args[0], "..");
352 let arg = if let ty::Int(_) = from_ty.sty {
353 arg.as_ty(ast::UintTy::U32)
360 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
361 Applicability::Unspecified,
366 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
368 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.sty, &ty_to.sty);
369 if let ty::Uint(ast::UintTy::U8) = slice_ty.sty;
370 if from_mutbl == to_mutbl;
372 let postfix = if from_mutbl == Mutability::MutMutable {
380 TRANSMUTE_BYTES_TO_STR,
382 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
388 "std::str::from_utf8{}({}).unwrap()",
390 snippet(cx, args[0].span, ".."),
392 Applicability::Unspecified,
397 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
400 TRANSMUTE_PTR_TO_PTR,
402 "transmute from a reference to a reference",
403 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
404 let ty_from_and_mut = ty::TypeAndMut {
408 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
410 .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
411 .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
412 let sugg = if to_mutbl == Mutability::MutMutable {
413 sugg_paren.mut_addr_deref()
415 sugg_paren.addr_deref()
421 Applicability::Unspecified,
429 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
431 TRANSMUTE_PTR_TO_PTR,
433 "transmute from a pointer to a pointer",
435 if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
436 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
437 db.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
441 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
444 TRANSMUTE_INT_TO_BOOL,
446 &format!("transmute from a `{}` to a `bool`", from_ty),
448 let arg = sugg::Sugg::hir(cx, &args[0], "..");
449 let zero = sugg::Sugg::NonParen(Cow::from("0"));
453 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
454 Applicability::Unspecified,
459 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => span_lint_and_then(
461 TRANSMUTE_INT_TO_FLOAT,
463 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
465 let arg = sugg::Sugg::hir(cx, &args[0], "..");
466 let arg = if let ty::Int(int_ty) = from_ty.sty {
469 int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
477 format!("{}::from_bits({})", to_ty, arg.to_string()),
478 Applicability::Unspecified,
491 /// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
492 /// not available , use
493 /// the type's `ToString` implementation. In weird cases it could lead to types
494 /// with invalid `'_`
495 /// lifetime, but it should be rare.
496 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
497 let seg = last_path_segment(path);
499 if let Some(ref params) = seg.args;
500 if !params.parenthesized;
501 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
502 GenericArg::Type(ty) => Some(ty),
505 if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
507 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
511 to_ref_ty.to_string()