2 use rustc::{declare_lint, lint_array};
3 use rustc::ty::{self, Ty};
7 use crate::utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
8 use crate::utils::{opt_def_id, sugg};
10 /// **What it does:** Checks for transmutes that can't ever be correct on any
13 /// **Why is this bad?** It's basically guaranteed to be undefined behaviour.
15 /// **Known problems:** When accessing C, users might want to store pointer
16 /// sized objects in `extradata` arguments to save an allocation.
20 /// let ptr: *const T = core::intrinsics::transmute('x')
22 declare_clippy_lint! {
25 "transmutes that are confusing at best, undefined behaviour at worst and always useless"
28 /// **What it does:** Checks for transmutes to the original type of the object
29 /// and transmutes that could be a cast.
31 /// **Why is this bad?** Readability. The code tricks people into thinking that
32 /// something complex is going on.
34 /// **Known problems:** None.
38 /// core::intrinsics::transmute(t) // where the result type is the same as `t`'s
40 declare_clippy_lint! {
41 pub USELESS_TRANSMUTE,
43 "transmutes that have the same to and from types or could be a cast/coercion"
46 /// **What it does:** Checks for transmutes between a type `T` and `*T`.
48 /// **Why is this bad?** It's easy to mistakenly transmute between a type and a
49 /// pointer to that type.
51 /// **Known problems:** None.
55 /// core::intrinsics::transmute(t) // where the result type is the same as
58 declare_clippy_lint! {
59 pub CROSSPOINTER_TRANSMUTE,
61 "transmutes that have to or from types that are a pointer to the other"
64 /// **What it does:** Checks for transmutes from a pointer to a reference.
66 /// **Why is this bad?** This can always be rewritten with `&` and `*`.
68 /// **Known problems:** None.
72 /// let _: &T = std::mem::transmute(p); // where p: *const T
73 /// // can be written:
76 declare_clippy_lint! {
77 pub TRANSMUTE_PTR_TO_REF,
79 "transmutes from a pointer to a reference type"
82 /// **What it does:** Checks for transmutes from an integer to a `char`.
84 /// **Why is this bad?** Not every integer is a Unicode scalar value.
86 /// **Known problems:**
87 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
88 /// as it needs to validate the input.
89 /// If you are certain that the input is always a valid Unicode scalar value,
90 /// use [`from_u32_unchecked`] which is as fast as `transmute`
91 /// but has a semantically meaningful name.
92 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
94 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
95 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
99 /// let _: char = std::mem::transmute(x); // where x: u32
101 /// let _ = std::char::from_u32(x).unwrap();
103 declare_clippy_lint! {
104 pub TRANSMUTE_INT_TO_CHAR,
106 "transmutes from an integer to a `char`"
109 /// **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.
111 /// **Why is this bad?** Not every byte slice is a valid UTF-8 string.
113 /// **Known problems:**
114 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
115 /// as it needs to validate the input.
116 /// If you are certain that the input is always a valid UTF-8,
117 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
118 /// but has a semantically meaningful name.
119 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
121 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
122 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
126 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
128 /// let _ = std::str::from_utf8(b).unwrap();
130 declare_clippy_lint! {
131 pub TRANSMUTE_BYTES_TO_STR,
133 "transmutes from a `&[u8]` to a `&str`"
136 /// **What it does:** Checks for transmutes from an integer to a `bool`.
138 /// **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.
140 /// **Known problems:** None.
144 /// let _: bool = std::mem::transmute(x); // where x: u8
146 /// let _: bool = x != 0;
148 declare_clippy_lint! {
149 pub TRANSMUTE_INT_TO_BOOL,
151 "transmutes from an integer to a `bool`"
154 /// **What it does:** Checks for transmutes from an integer to a float.
156 /// **Why is this bad?** This might result in an invalid in-memory representation of a float.
158 /// **Known problems:** None.
162 /// let _: f32 = std::mem::transmute(x); // where x: u32
164 /// let _: f32 = f32::from_bits(x);
166 declare_clippy_lint! {
167 pub TRANSMUTE_INT_TO_FLOAT,
169 "transmutes from an integer to a float"
172 /// **What it does:** Checks for transmutes from a pointer to a pointer, or
173 /// from a reference to a reference.
175 /// **Why is this bad?** Transmutes are dangerous, and these can instead be
176 /// written as casts.
178 /// **Known problems:** None.
182 /// let ptr = &1u32 as *const u32;
184 /// // pointer-to-pointer transmute
185 /// let _: *const f32 = std::mem::transmute(ptr);
186 /// // ref-ref transmute
187 /// let _: &f32 = std::mem::transmute(&1u32);
189 /// // These can be respectively written:
190 /// let _ = ptr as *const f32
191 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
193 declare_clippy_lint! {
194 pub TRANSMUTE_PTR_TO_PTR,
196 "transmutes from a pointer to a pointer / a reference to a reference"
199 pub struct Transmute;
201 impl LintPass for Transmute {
202 fn get_lints(&self) -> LintArray {
204 CROSSPOINTER_TRANSMUTE,
205 TRANSMUTE_PTR_TO_REF,
206 TRANSMUTE_PTR_TO_PTR,
209 TRANSMUTE_INT_TO_CHAR,
210 TRANSMUTE_BYTES_TO_STR,
211 TRANSMUTE_INT_TO_BOOL,
212 TRANSMUTE_INT_TO_FLOAT,
217 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
218 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
219 if let ExprKind::Call(ref path_expr, ref args) = e.node {
220 if let ExprKind::Path(ref qpath) = path_expr.node {
221 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
222 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
223 let from_ty = cx.tables.expr_ty(&args[0]);
224 let to_ty = cx.tables.expr_ty(e);
226 match (&from_ty.sty, &to_ty.sty) {
227 _ if from_ty == to_ty => span_lint(
231 &format!("transmute from a type (`{}`) to itself", from_ty),
233 (&ty::TyRef(_, rty, rty_mutbl), &ty::TyRawPtr(ptr_ty)) => span_lint_and_then(
237 "transmute from a reference to a pointer",
238 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
239 let rty_and_mut = ty::TypeAndMut { ty: rty, mutbl: rty_mutbl };
241 let sugg = if ptr_ty == rty_and_mut {
244 arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
247 db.span_suggestion(e.span, "try", sugg.to_string());
250 (&ty::TyInt(_), &ty::TyRawPtr(_)) | (&ty::TyUint(_), &ty::TyRawPtr(_)) => {
255 "transmute from an integer to a pointer",
256 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
257 db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
261 (&ty::TyFloat(_), &ty::TyRef(..)) |
262 (&ty::TyFloat(_), &ty::TyRawPtr(_)) |
263 (&ty::TyChar, &ty::TyRef(..)) |
264 (&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
268 &format!("transmute from a `{}` to a pointer", from_ty),
270 (&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
272 CROSSPOINTER_TRANSMUTE,
275 "transmute from a type (`{}`) to the type that it points to (`{}`)",
280 (_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
282 CROSSPOINTER_TRANSMUTE,
285 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
290 (&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_ref_ty, mutbl)) => span_lint_and_then(
292 TRANSMUTE_PTR_TO_REF,
295 "transmute from a pointer type (`{}`) to a reference type \
301 let arg = sugg::Sugg::hir(cx, &args[0], "..");
302 let (deref, cast) = if mutbl == Mutability::MutMutable {
308 let arg = if from_pty.ty == to_ref_ty {
311 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
314 db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
317 (&ty::TyInt(ast::IntTy::I32), &ty::TyChar) |
318 (&ty::TyUint(ast::UintTy::U32), &ty::TyChar) => span_lint_and_then(
320 TRANSMUTE_INT_TO_CHAR,
322 &format!("transmute from a `{}` to a `char`", from_ty),
324 let arg = sugg::Sugg::hir(cx, &args[0], "..");
325 let arg = if let ty::TyInt(_) = from_ty.sty {
326 arg.as_ty(ty::TyUint(ast::UintTy::U32))
333 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
337 (&ty::TyRef(_, ty_from, from_mutbl), &ty::TyRef(_, ty_to, to_mutbl)) => {
339 if let (&ty::TySlice(slice_ty), &ty::TyStr) = (&ty_from.sty, &ty_to.sty);
340 if let ty::TyUint(ast::UintTy::U8) = slice_ty.sty;
341 if from_mutbl == to_mutbl;
343 let postfix = if from_mutbl == Mutability::MutMutable {
351 TRANSMUTE_BYTES_TO_STR,
353 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
359 "std::str::from_utf8{}({}).unwrap()",
361 snippet(cx, args[0].span, ".."),
367 if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
370 TRANSMUTE_PTR_TO_PTR,
372 "transmute from a reference to a reference",
373 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
374 let ty_from_and_mut = ty::TypeAndMut { ty: ty_from, mutbl: from_mutbl };
375 let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: to_mutbl };
376 let sugg_paren = arg.as_ty(cx.tcx.mk_ptr(ty_from_and_mut)).as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
377 let sugg = if to_mutbl == Mutability::MutMutable {
378 sugg_paren.mut_addr_deref()
380 sugg_paren.addr_deref()
382 db.span_suggestion(e.span, "try", sugg.to_string());
389 (&ty::TyRawPtr(_), &ty::TyRawPtr(to_ty)) => span_lint_and_then(
391 TRANSMUTE_PTR_TO_PTR,
393 "transmute from a pointer to a pointer",
394 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
395 let sugg = arg.as_ty(cx.tcx.mk_ptr(to_ty));
396 db.span_suggestion(e.span, "try", sugg.to_string());
399 (&ty::TyInt(ast::IntTy::I8), &ty::TyBool) | (&ty::TyUint(ast::UintTy::U8), &ty::TyBool) => {
402 TRANSMUTE_INT_TO_BOOL,
404 &format!("transmute from a `{}` to a `bool`", from_ty),
406 let arg = sugg::Sugg::hir(cx, &args[0], "..");
407 let zero = sugg::Sugg::NonParen(Cow::from("0"));
411 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
416 (&ty::TyInt(_), &ty::TyFloat(_)) | (&ty::TyUint(_), &ty::TyFloat(_)) => {
419 TRANSMUTE_INT_TO_FLOAT,
421 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
423 let arg = sugg::Sugg::hir(cx, &args[0], "..");
424 let arg = if let ty::TyInt(int_ty) = from_ty.sty {
429 .map_or_else(|| "size".to_string(), |v| v.to_string())
437 format!("{}::from_bits({})", to_ty, arg.to_string()),
451 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
452 /// not available , use
453 /// the type's `ToString` implementation. In weird cases it could lead to types
454 /// with invalid `'_`
455 /// lifetime, but it should be rare.
456 fn get_type_snippet(cx: &LateContext, path: &QPath, to_ref_ty: Ty) -> String {
457 let seg = last_path_segment(path);
459 if let Some(ref params) = seg.args;
460 if !params.parenthesized;
461 if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
462 GenericArg::Type(ty) => Some(ty),
463 GenericArg::Lifetime(_) => None,
465 if let TyKind::Rptr(_, ref to_ty) = to_ty.node;
467 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
471 to_ref_ty.to_string()