1 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use crate::rustc::{declare_tool_lint, lint_array};
3 use if_chain::if_chain;
4 use crate::rustc::ty::{self, Ty};
5 use crate::rustc::hir::*;
7 use crate::syntax::ast;
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};
10 use crate::rustc_errors::Applicability;
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')
24 declare_clippy_lint! {
27 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
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 declare_clippy_lint! {
43 pub USELESS_TRANSMUTE,
45 "transmutes that have the same to and from types or could be a cast/coercion"
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 declare_clippy_lint! {
61 pub CROSSPOINTER_TRANSMUTE,
63 "transmutes that have to or from types that are a pointer to the other"
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.
74 /// let _: &T = std::mem::transmute(p); // where p: *const T
75 /// // can be written:
78 declare_clippy_lint! {
79 pub TRANSMUTE_PTR_TO_REF,
81 "transmutes from a pointer to a reference type"
84 /// **What it does:** Checks for transmutes from an integer to a `char`.
86 /// **Why is this bad?** Not every integer is a Unicode scalar value.
88 /// **Known problems:**
89 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
90 /// as it needs to validate the input.
91 /// If you are certain that the input is always a valid Unicode scalar value,
92 /// use [`from_u32_unchecked`] which is as fast as `transmute`
93 /// but has a semantically meaningful name.
94 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
96 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
97 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
101 /// let _: char = std::mem::transmute(x); // where x: u32
103 /// let _ = std::char::from_u32(x).unwrap();
105 declare_clippy_lint! {
106 pub TRANSMUTE_INT_TO_CHAR,
108 "transmutes from an integer to a `char`"
111 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
113 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
115 /// **Known problems:**
116 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
117 /// as it needs to validate the input.
118 /// If you are certain that the input is always a valid UTF-8,
119 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
120 /// but has a semantically meaningful name.
121 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
123 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
124 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
128 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
130 /// let _ = std::str::from_utf8(b).unwrap();
132 declare_clippy_lint! {
133 pub TRANSMUTE_BYTES_TO_STR,
135 "transmutes from a `&[u8]` to a `&str`"
138 /// **What it does:** Checks for transmutes from an integer to a `bool`.
140 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
142 /// **Known problems:** None.
146 /// let _: bool = std::mem::transmute(x); // where x: u8
148 /// let _: bool = x != 0;
150 declare_clippy_lint! {
151 pub TRANSMUTE_INT_TO_BOOL,
153 "transmutes from an integer to a `bool`"
156 /// **What it does:** Checks for transmutes from an integer to a float.
158 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
160 /// **Known problems:** None.
164 /// let _: f32 = std::mem::transmute(x); // where x: u32
166 /// let _: f32 = f32::from_bits(x);
168 declare_clippy_lint! {
169 pub TRANSMUTE_INT_TO_FLOAT,
171 "transmutes from an integer to a float"
174 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
175 /// from a reference to a reference.
177 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
178 /// written as casts.
180 /// **Known problems:** None.
184 /// let ptr = &1u32 as *const u32;
186 /// // pointer-to-pointer transmute
187 /// let _: *const f32 = std::mem::transmute(ptr);
188 /// // ref-ref transmute
189 /// let _: &f32 = std::mem::transmute(&1u32);
191 /// // These can be respectively written:
192 /// let _ = ptr as *const f32
193 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
195 declare_clippy_lint! {
196 pub TRANSMUTE_PTR_TO_PTR,
198 "transmutes from a pointer to a pointer / a reference to a reference"
201 pub struct Transmute;
203 impl LintPass for Transmute {
204 fn get_lints(&self) -> LintArray {
206 CROSSPOINTER_TRANSMUTE,
207 TRANSMUTE_PTR_TO_REF,
208 TRANSMUTE_PTR_TO_PTR,
211 TRANSMUTE_INT_TO_CHAR,
212 TRANSMUTE_BYTES_TO_STR,
213 TRANSMUTE_INT_TO_BOOL,
214 TRANSMUTE_INT_TO_FLOAT,
219 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
220 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
221 if let ExprKind::Call(ref path_expr, ref args) = e.node {
222 if let ExprKind::Path(ref qpath) = path_expr.node {
223 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
224 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
225 let from_ty = cx.tables.expr_ty(&args[0]);
226 let to_ty = cx.tables.expr_ty(e);
228 match (&from_ty.sty, &to_ty.sty) {
229 _ if from_ty == to_ty => span_lint(
233 &format!("transmute from a type (`{}`) to itself", from_ty),
235 (&ty::Ref(_, rty, rty_mutbl), &ty::RawPtr(ptr_ty)) => span_lint_and_then(
239 "transmute from a reference to a pointer",
240 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
241 let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
243 let sugg = if ptr_ty == rty_and_mut {
246 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
249 db.span_suggestion_with_applicability(
253 Applicability::Unspecified,
257 (&ty::Int(_), &ty::RawPtr(_)) | (&ty::Uint(_), &ty::RawPtr(_)) => {
262 "transmute from an integer to a pointer",
263 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
264 db.span_suggestion_with_applicability(
267 arg.as_ty(&to_ty.to_string()).to_string(),
268 Applicability::Unspecified,
273 (&ty::Float(_), &ty::Ref(..)) |
274 (&ty::Float(_), &ty::RawPtr(_)) |
275 (&ty::Char, &ty::Ref(..)) |
276 (&ty::Char, &ty::RawPtr(_)) => span_lint(
280 &format!("transmute from a `{}` to a pointer", from_ty),
282 (&ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
284 CROSSPOINTER_TRANSMUTE,
287 "transmute from a type (`{}`) to the type that it points to (`{}`)",
292 (_, &ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
294 CROSSPOINTER_TRANSMUTE,
297 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
302 (&ty::RawPtr(from_pty), &ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
304 TRANSMUTE_PTR_TO_REF,
307 "transmute from a pointer type (`{}`) to a reference type \
313 let arg = sugg::Sugg::hir(cx, &args[0], "..");
314 let (deref, cast) = if mutbl == Mutability::MutMutable {
320 let arg = if from_pty.ty == to_ref_ty {
323 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
326 db.span_suggestion_with_applicability(
329 sugg::make_unop(deref, arg).to_string(),
330 Applicability::Unspecified,
334 (&ty::Int(ast::IntTy::I32), &ty::Char) |
335 (&ty::Uint(ast::UintTy::U32), &ty::Char) => span_lint_and_then(
337 TRANSMUTE_INT_TO_CHAR,
339 &format!("transmute from a `{}` to a `char`", from_ty),
341 let arg = sugg::Sugg::hir(cx, &args[0], "..");
342 let arg = if let ty::Int(_) = from_ty.sty {
343 arg.as_ty(ty::Uint(ast::UintTy::U32))
347 db.span_suggestion_with_applicability(
350 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
351 Applicability::Unspecified,
355 (&ty::Ref(_, ty_from, from_mutbl), &ty::Ref(_, ty_to, to_mutbl)) => {
357 if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.sty, &ty_to.sty);
358 if let ty::Uint(ast::UintTy::U8) = slice_ty.sty;
359 if from_mutbl == to_mutbl;
361 let postfix = if from_mutbl == Mutability::MutMutable {
369 TRANSMUTE_BYTES_TO_STR,
371 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
373 db.span_suggestion_with_applicability(
377 "std::str::from_utf8{}({}).unwrap()",
379 snippet(cx, args[0].span, ".."),
381 Applicability::Unspecified,
386 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
389 TRANSMUTE_PTR_TO_PTR,
391 "transmute from a reference to a reference",
392 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
393 let ty_from_and_mut = ty::TypeAndMut { ty: ty_from, mutbl: from_mutbl };
394 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
395 let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
396 let sugg = if to_mutbl == Mutability::MutMutable {
397 sugg_paren.mut_addr_deref()
399 sugg_paren.addr_deref()
401 db.span_suggestion_with_applicability(
405 Applicability::Unspecified,
413 (&ty::RawPtr(_), &ty::RawPtr(to_ty)) => span_lint_and_then(
415 TRANSMUTE_PTR_TO_PTR,
417 "transmute from a pointer to a pointer",
418 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
419 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
420 db.span_suggestion_with_applicability(
424 Applicability::Unspecified,
428 (&ty::Int(ast::IntTy::I8), &ty::Bool) | (&ty::Uint(ast::UintTy::U8), &ty::Bool) => {
431 TRANSMUTE_INT_TO_BOOL,
433 &format!("transmute from a `{}` to a `bool`", from_ty),
435 let arg = sugg::Sugg::hir(cx, &args[0], "..");
436 let zero = sugg::Sugg::NonParen(Cow::from("0"));
437 db.span_suggestion_with_applicability(
440 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
441 Applicability::Unspecified,
446 (&ty::Int(_), &ty::Float(_)) | (&ty::Uint(_), &ty::Float(_)) => {
449 TRANSMUTE_INT_TO_FLOAT,
451 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
453 let arg = sugg::Sugg::hir(cx, &args[0], "..");
454 let arg = if let ty::Int(int_ty) = from_ty.sty {
459 .map_or_else(|| "size".to_string(), |v| v.to_string())
464 db.span_suggestion_with_applicability(
467 format!("{}::from_bits({})", to_ty, arg.to_string()),
468 Applicability::Unspecified,
482 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
483 /// not available , use
484 /// the type's `ToString` implementation. In weird cases it could lead to types
485 /// with invalid `'_`
486 /// lifetime, but it should be rare.
487 fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath, to_ref_ty: Ty<'_>) -> String {
488 let seg = last_path_segment(path);
490 if let Some(ref params) = seg.args;
491 if !params.parenthesized;
492 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
493 GenericArg::Type(ty) => Some(ty),
494 GenericArg::Lifetime(_) => None,
496 if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
498 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
502 to_ref_ty.to_string()