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')`
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
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
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:
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();
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();
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;
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);
166 pub TRANSMUTE_INT_TO_FLOAT,
168 "transmutes from an integer to a float"
171 pub struct Transmute;
173 impl LintPass for Transmute {
174 fn get_lints(&self) -> LintArray {
176 CROSSPOINTER_TRANSMUTE,
177 TRANSMUTE_PTR_TO_REF,
180 TRANSMUTE_INT_TO_CHAR,
181 TRANSMUTE_BYTES_TO_STR,
182 TRANSMUTE_INT_TO_BOOL,
183 TRANSMUTE_INT_TO_FLOAT
188 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
189 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
190 if let ExprCall(ref path_expr, ref args) = e.node {
191 if let ExprPath(ref qpath) = path_expr.node {
192 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
193 if match_def_path(cx.tcx, def_id, &paths::TRANSMUTE) {
194 let from_ty = cx.tables.expr_ty(&args[0]);
195 let to_ty = cx.tables.expr_ty(e);
197 match (&from_ty.sty, &to_ty.sty) {
198 _ if from_ty == to_ty => span_lint(
202 &format!("transmute from a type (`{}`) to itself", from_ty),
204 (&ty::TyRef(_, rty), &ty::TyRawPtr(ptr_ty)) => span_lint_and_then(
208 "transmute from a reference to a pointer",
209 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
210 let sugg = if ptr_ty == rty {
213 arg.as_ty(cx.tcx.mk_ptr(rty)).as_ty(to_ty)
216 db.span_suggestion(e.span, "try", sugg.to_string());
219 (&ty::TyInt(_), &ty::TyRawPtr(_)) | (&ty::TyUint(_), &ty::TyRawPtr(_)) => {
224 "transmute from an integer to a pointer",
225 |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
226 db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
230 (&ty::TyFloat(_), &ty::TyRef(..)) |
231 (&ty::TyFloat(_), &ty::TyRawPtr(_)) |
232 (&ty::TyChar, &ty::TyRef(..)) |
233 (&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
237 &format!("transmute from a `{}` to a pointer", from_ty),
239 (&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
241 CROSSPOINTER_TRANSMUTE,
244 "transmute from a type (`{}`) to the type that it points to (`{}`)",
249 (_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
251 CROSSPOINTER_TRANSMUTE,
254 "transmute from a type (`{}`) to a pointer to that type (`{}`)",
259 (&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_ref_ty)) => span_lint_and_then(
261 TRANSMUTE_PTR_TO_REF,
264 "transmute from a pointer type (`{}`) to a reference type \
270 let arg = sugg::Sugg::hir(cx, &args[0], "..");
271 let (deref, cast) = if to_ref_ty.mutbl == Mutability::MutMutable {
277 let arg = if from_pty.ty == to_ref_ty.ty {
280 arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty.ty)))
283 db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
286 (&ty::TyInt(ast::IntTy::I32), &ty::TyChar) |
287 (&ty::TyUint(ast::UintTy::U32), &ty::TyChar) => span_lint_and_then(
289 TRANSMUTE_INT_TO_CHAR,
291 &format!("transmute from a `{}` to a `char`", from_ty),
293 let arg = sugg::Sugg::hir(cx, &args[0], "..");
294 let arg = if let ty::TyInt(_) = from_ty.sty {
295 arg.as_ty(ty::TyUint(ast::UintTy::U32))
302 format!("std::char::from_u32({}).unwrap()", arg.to_string()),
306 (&ty::TyRef(_, ref ref_from), &ty::TyRef(_, ref ref_to)) => {
308 if let (&ty::TySlice(slice_ty), &ty::TyStr) = (&ref_from.ty.sty, &ref_to.ty.sty);
309 if let ty::TyUint(ast::UintTy::U8) = slice_ty.sty;
310 if ref_from.mutbl == ref_to.mutbl;
312 let postfix = if ref_from.mutbl == Mutability::MutMutable {
320 TRANSMUTE_BYTES_TO_STR,
322 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
328 "std::str::from_utf8{}({}).unwrap()",
330 snippet(cx, args[0].span, ".."),
338 (&ty::TyInt(ast::IntTy::I8), &ty::TyBool) | (&ty::TyUint(ast::UintTy::U8), &ty::TyBool) => {
341 TRANSMUTE_INT_TO_BOOL,
343 &format!("transmute from a `{}` to a `bool`", from_ty),
345 let arg = sugg::Sugg::hir(cx, &args[0], "..");
346 let zero = sugg::Sugg::NonParen(Cow::from("0"));
350 sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
355 (&ty::TyInt(_), &ty::TyFloat(_)) | (&ty::TyUint(_), &ty::TyFloat(_)) => {
358 TRANSMUTE_INT_TO_FLOAT,
360 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
362 let arg = sugg::Sugg::hir(cx, &args[0], "..");
363 let arg = if let ty::TyInt(int_ty) = from_ty.sty {
368 .map_or_else(|| "size".to_string(), |v| v.to_string())
376 format!("{}::from_bits({})", to_ty, arg.to_string()),
390 /// Get the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
391 /// not available , use
392 /// the type's `ToString` implementation. In weird cases it could lead to types
393 /// with invalid `'_`
394 /// lifetime, but it should be rare.
395 fn get_type_snippet(cx: &LateContext, path: &QPath, to_ref_ty: Ty) -> String {
396 let seg = last_path_segment(path);
398 if let Some(ref params) = seg.parameters;
399 if !params.parenthesized;
400 if let Some(to_ty) = params.types.get(1);
401 if let TyRptr(_, ref to_ty) = to_ty.node;
403 return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
407 to_ref_ty.to_string()