2 use rustc
::ty
::{self, Ty}
;
6 use utils
::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then}
;
7 use utils
::{opt_def_id, sugg}
;
9 /// **What it does:** Checks for transmutes that can't ever be correct on any
12 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
14 /// **Known problems:** When accessing C, users might want to store pointer
15 /// sized objects in `extradata` arguments to save an allocation.
19 /// let ptr: *const T = core::intrinsics::transmute('x')
21 declare_clippy_lint
! {
24 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
27 /// **What it does:** Checks for transmutes to the original type of the object
28 /// and transmutes that could be a cast.
30 /// **Why is this bad?** Readability. The code tricks people into thinking that
31 /// something complex is going on.
33 /// **Known problems:** None.
37 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
39 declare_clippy_lint
! {
40 pub USELESS_TRANSMUTE
,
42 "transmutes that have the same to and from types or could be a cast/coercion"
45 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
47 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
48 /// pointer to that type.
50 /// **Known problems:** None.
54 /// core::intrinsics::transmute(t) // where the result type is the same as
57 declare_clippy_lint
! {
58 pub CROSSPOINTER_TRANSMUTE
,
60 "transmutes that have to or from types that are a pointer to the other"
63 /// **What it does:** Checks for transmutes from a pointer to a reference.
65 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
67 /// **Known problems:** None.
71 /// let _: &T = std::mem::transmute(p); // where p: *const T
72 /// // can be written:
75 declare_clippy_lint
! {
76 pub TRANSMUTE_PTR_TO_REF
,
78 "transmutes from a pointer to a reference type"
81 /// **What it does:** Checks for transmutes from an integer to a `char`.
83 /// **Why is this bad?** Not every integer is a Unicode scalar value.
85 /// **Known problems:**
86 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
87 /// as it needs to validate the input.
88 /// If you are certain that the input is always a valid Unicode scalar value,
89 /// use [`from_u32_unchecked`] which is as fast as `transmute`
90 /// but has a semantically meaningful name.
91 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
93 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
94 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
98 /// let _: char = std::mem::transmute(x); // where x: u32
100 /// let _ = std::char::from_u32(x).unwrap();
102 declare_clippy_lint
! {
103 pub TRANSMUTE_INT_TO_CHAR
,
105 "transmutes from an integer to a `char`"
108 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
110 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
112 /// **Known problems:**
113 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
114 /// as it needs to validate the input.
115 /// If you are certain that the input is always a valid UTF-8,
116 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
117 /// but has a semantically meaningful name.
118 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
120 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
121 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
125 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
127 /// let _ = std::str::from_utf8(b).unwrap();
129 declare_clippy_lint
! {
130 pub TRANSMUTE_BYTES_TO_STR
,
132 "transmutes from a `&[u8]` to a `&str`"
135 /// **What it does:** Checks for transmutes from an integer to a `bool`.
137 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
139 /// **Known problems:** None.
143 /// let _: bool = std::mem::transmute(x); // where x: u8
145 /// let _: bool = x != 0;
147 declare_clippy_lint
! {
148 pub TRANSMUTE_INT_TO_BOOL
,
150 "transmutes from an integer to a `bool`"
153 /// **What it does:** Checks for transmutes from an integer to a float.
155 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
157 /// **Known problems:** None.
161 /// let _: f32 = std::mem::transmute(x); // where x: u32
163 /// let _: f32 = f32::from_bits(x);
165 declare_clippy_lint
! {
166 pub TRANSMUTE_INT_TO_FLOAT
,
168 "transmutes from an integer to a float"
171 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
172 /// from a reference to a reference.
174 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
175 /// written as casts.
177 /// **Known problems:** None.
181 /// let ptr = &1u32 as *const u32;
183 /// // pointer-to-pointer transmute
184 /// let _: *const f32 = std::mem::transmute(ptr);
185 /// // ref-ref transmute
186 /// let _: &f32 = std::mem::transmute(&1u32);
188 /// // These can be respectively written:
189 /// let _ = ptr as *const f32
190 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
192 declare_clippy_lint
! {
193 pub TRANSMUTE_PTR_TO_PTR
,
195 "transmutes from a pointer to a reference type"
198 pub struct Transmute
;
200 impl LintPass
for Transmute
{
201 fn get_lints(&self) -> LintArray
{
203 CROSSPOINTER_TRANSMUTE
,
204 TRANSMUTE_PTR_TO_REF
,
205 TRANSMUTE_PTR_TO_PTR
,
208 TRANSMUTE_INT_TO_CHAR
,
209 TRANSMUTE_BYTES_TO_STR
,
210 TRANSMUTE_INT_TO_BOOL
,
211 TRANSMUTE_INT_TO_FLOAT
,
216 impl<'a
, 'tcx
> LateLintPass
<'a
, 'tcx
> for Transmute
{
217 fn check_expr(&mut self, cx
: &LateContext
<'a
, 'tcx
>, e
: &'tcx Expr
) {
218 if let ExprCall(ref path_expr
, ref args
) = e
.node
{
219 if let ExprPath(ref qpath
) = path_expr
.node
{
220 if let Some(def_id
) = opt_def_id(cx
.tables
.qpath_def(qpath
, path_expr
.hir_id
)) {
221 if match_def_path(cx
.tcx
, def_id
, &paths
::TRANSMUTE
) {
222 let from_ty
= cx
.tables
.expr_ty(&args
[0]);
223 let to_ty
= cx
.tables
.expr_ty(e
);
225 match (&from_ty
.sty
, &to_ty
.sty
) {
226 _
if from_ty
== to_ty
=> span_lint(
230 &format
!("transmute from a type (`{}`) to itself", from_ty
),
232 (&ty
::TyRef(_
, rty
, rty_mutbl
), &ty
::TyRawPtr(ptr_ty
)) => span_lint_and_then(
236 "transmute from a reference to a pointer",
237 |db
| if let Some(arg
) = sugg
::Sugg
::hir_opt(cx
, &args
[0]) {
238 let rty_and_mut
= ty
::TypeAndMut { ty: rty, mutbl: rty_mutbl }
;
240 let sugg
= if ptr_ty
== rty_and_mut
{
243 arg
.as_ty(cx
.tcx
.mk_ptr(rty_and_mut
)).as_ty(to_ty
)
246 db
.span_suggestion(e
.span
, "try", sugg
.to_string());
249 (&ty
::TyInt(_
), &ty
::TyRawPtr(_
)) | (&ty
::TyUint(_
), &ty
::TyRawPtr(_
)) => {
254 "transmute from an integer to a pointer",
255 |db
| if let Some(arg
) = sugg
::Sugg
::hir_opt(cx
, &args
[0]) {
256 db
.span_suggestion(e
.span
, "try", arg
.as_ty(&to_ty
.to_string()).to_string());
260 (&ty
::TyFloat(_
), &ty
::TyRef(..)) |
261 (&ty
::TyFloat(_
), &ty
::TyRawPtr(_
)) |
262 (&ty
::TyChar
, &ty
::TyRef(..)) |
263 (&ty
::TyChar
, &ty
::TyRawPtr(_
)) => span_lint(
267 &format
!("transmute from a `{}` to a pointer", from_ty
),
269 (&ty
::TyRawPtr(from_ptr
), _
) if from_ptr
.ty
== to_ty
=> span_lint(
271 CROSSPOINTER_TRANSMUTE
,
274 "transmute from a type (`{}`) to the type that it points to (`{}`)",
279 (_
, &ty
::TyRawPtr(to_ptr
)) if to_ptr
.ty
== from_ty
=> span_lint(
281 CROSSPOINTER_TRANSMUTE
,
284 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
289 (&ty
::TyRawPtr(from_pty
), &ty
::TyRef(_
, to_ref_ty
, mutbl
)) => span_lint_and_then(
291 TRANSMUTE_PTR_TO_REF
,
294 "transmute from a pointer type (`{}`) to a reference type \
300 let arg
= sugg
::Sugg
::hir(cx
, &args
[0], "..");
301 let (deref
, cast
) = if mutbl
== Mutability
::MutMutable
{
307 let arg
= if from_pty
.ty
== to_ref_ty
{
310 arg
.as_ty(&format
!("{} {}", cast
, get_type_snippet(cx
, qpath
, to_ref_ty
)))
313 db
.span_suggestion(e
.span
, "try", sugg
::make_unop(deref
, arg
).to_string());
316 (&ty
::TyInt(ast
::IntTy
::I32
), &ty
::TyChar
) |
317 (&ty
::TyUint(ast
::UintTy
::U32
), &ty
::TyChar
) => span_lint_and_then(
319 TRANSMUTE_INT_TO_CHAR
,
321 &format
!("transmute from a `{}` to a `char`", from_ty
),
323 let arg
= sugg
::Sugg
::hir(cx
, &args
[0], "..");
324 let arg
= if let ty
::TyInt(_
) = from_ty
.sty
{
325 arg
.as_ty(ty
::TyUint(ast
::UintTy
::U32
))
332 format
!("std::char::from_u32({}).unwrap()", arg
.to_string()),
336 (&ty
::TyRef(_
, ty_from
, from_mutbl
), &ty
::TyRef(_
, ty_to
, to_mutbl
)) => {
338 if let (&ty
::TySlice(slice_ty
), &ty
::TyStr
) = (&ty_from
.sty
, &ty_to
.sty
);
339 if let ty
::TyUint(ast
::UintTy
::U8
) = slice_ty
.sty
;
340 if from_mutbl
== to_mutbl
;
342 let postfix
= if from_mutbl
== Mutability
::MutMutable
{
350 TRANSMUTE_BYTES_TO_STR
,
352 &format
!("transmute from a `{}` to a `{}`", from_ty
, to_ty
),
358 "std::str::from_utf8{}({}).unwrap()",
360 snippet(cx
, args
[0].span
, ".."),
368 TRANSMUTE_PTR_TO_PTR
,
370 "transmute from a reference to a reference",
371 |db
| if let Some(arg
) = sugg
::Sugg
::hir_opt(cx
, &args
[0]) {
372 let ty_from_and_mut
= ty
::TypeAndMut { ty: ty_from, mutbl: from_mutbl }
;
373 let ty_to_and_mut
= ty
::TypeAndMut { ty: ty_to, mutbl: to_mutbl }
;
374 let sugg_paren
= arg
.as_ty(cx
.tcx
.mk_ptr(ty_from_and_mut
)).as_ty(cx
.tcx
.mk_ptr(ty_to_and_mut
));
375 let sugg
= if to_mutbl
== Mutability
::MutMutable
{
376 sugg_paren
.mut_addr_deref()
378 sugg_paren
.addr_deref()
380 db
.span_suggestion(e
.span
, "try", sugg
.to_string());
386 (&ty
::TyRawPtr(_
), &ty
::TyRawPtr(to_ty
)) => span_lint_and_then(
388 TRANSMUTE_PTR_TO_PTR
,
390 "transmute from a pointer to a pointer",
391 |db
| if let Some(arg
) = sugg
::Sugg
::hir_opt(cx
, &args
[0]) {
392 let sugg
= arg
.as_ty(cx
.tcx
.mk_ptr(to_ty
));
393 db
.span_suggestion(e
.span
, "try", sugg
.to_string());
396 (&ty
::TyInt(ast
::IntTy
::I8
), &ty
::TyBool
) | (&ty
::TyUint(ast
::UintTy
::U8
), &ty
::TyBool
) => {
399 TRANSMUTE_INT_TO_BOOL
,
401 &format
!("transmute from a `{}` to a `bool`", from_ty
),
403 let arg
= sugg
::Sugg
::hir(cx
, &args
[0], "..");
404 let zero
= sugg
::Sugg
::NonParen(Cow
::from("0"));
408 sugg
::make_binop(ast
::BinOpKind
::Ne
, &arg
, &zero
).to_string(),
413 (&ty
::TyInt(_
), &ty
::TyFloat(_
)) | (&ty
::TyUint(_
), &ty
::TyFloat(_
)) => {
416 TRANSMUTE_INT_TO_FLOAT
,
418 &format
!("transmute from a `{}` to a `{}`", from_ty
, to_ty
),
420 let arg
= sugg
::Sugg
::hir(cx
, &args
[0], "..");
421 let arg
= if let ty
::TyInt(int_ty
) = from_ty
.sty
{
426 .map_or_else(|| "size".to_string(), |v
| v
.to_string())
434 format
!("{}::from_bits({})", to_ty
, arg
.to_string()),
448 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
449 /// not available , use
450 /// the type's `ToString` implementation. In weird cases it could lead to types
451 /// with invalid `'_`
452 /// lifetime, but it should be rare.
453 fn get_type_snippet(cx
: &LateContext
, path
: &QPath
, to_ref_ty
: Ty
) -> String
{
454 let seg
= last_path_segment(path
);
456 if let Some(ref params
) = seg
.parameters
;
457 if !params
.parenthesized
;
458 if let Some(to_ty
) = params
.types
.get(1);
459 if let TyRptr(_
, ref to_ty
) = to_ty
.node
;
461 return snippet(cx
, to_ty
.ty
.span
, &to_ref_ty
.to_string()).to_string();
465 to_ref_ty
.to_string()