From a469ee1061fbccd4dda79e07017d35189e367b0e Mon Sep 17 00:00:00 2001 From: Oliver Schneider Date: Mon, 27 Jun 2016 16:12:48 +0200 Subject: [PATCH] lint transmuting references to pointers --- clippy_lints/src/transmute.rs | 17 +++++++++++++++++ tests/compile-fail/transmute.rs | 15 +++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/clippy_lints/src/transmute.rs b/clippy_lints/src/transmute.rs index 718111bee65..0d68789e0be 100644 --- a/clippy_lints/src/transmute.rs +++ b/clippy_lints/src/transmute.rs @@ -72,6 +72,23 @@ impl LateLintPass for Transmute { e.span, &format!("transmute from a type (`{}`) to itself", from_ty), ), + (&TyRef(_, rty), &TyRawPtr(ptr_ty)) => span_lint_and_then( + cx, + USELESS_TRANSMUTE, + e.span, + "transmute from a reference to a pointer", + |db| { + if let Some(arg) = snippet_opt(cx, args[0].span) { + let sugg = if ptr_ty == rty { + format!("{} as {}", arg, to_ty) + } else { + format!("{} as {} as {}", arg, cx.tcx.mk_ptr(rty), to_ty) + }; + + db.span_suggestion(e.span, "try", sugg); + } + }, + ), (&TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint( cx, CROSSPOINTER_TRANSMUTE, diff --git a/tests/compile-fail/transmute.rs b/tests/compile-fail/transmute.rs index ad97410cf65..4cd19f9bec9 100644 --- a/tests/compile-fail/transmute.rs +++ b/tests/compile-fail/transmute.rs @@ -21,6 +21,21 @@ unsafe fn _generic<'a, T, U: 'a>(t: &'a T) { //~^ ERROR transmute from a type (`&'a T`) to itself let _: &'a U = core::intrinsics::transmute(t); + + let _: *const T = core::intrinsics::transmute(t); + //~^ ERROR transmute from a reference to a pointer + //~| HELP try + //~| SUGGESTION = t as *const T + + let _: *mut T = core::intrinsics::transmute(t); + //~^ ERROR transmute from a reference to a pointer + //~| HELP try + //~| SUGGESTION = t as *const T as *mut T + + let _: *const U = core::intrinsics::transmute(t); + //~^ ERROR transmute from a reference to a pointer + //~| HELP try + //~| SUGGESTION = t as *const T as *const U } #[deny(transmute_ptr_to_ref)]