Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion clippy_lints/src/transmute/transmuting_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_integer_const;
use clippy_utils::res::{MaybeDef, MaybeResPath};
use rustc_hir::{Expr, ExprKind};
use rustc_hir::{ConstBlock, Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::Ty;
use rustc_span::symbol::sym;
Expand Down Expand Up @@ -42,5 +42,23 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'t
return true;
}

// Catching:
// `std::mem::transmute({ 0 as *const u64 })` and similar const blocks
if let ExprKind::Block(block, _) = arg.kind
&& block.stmts.is_empty()
&& let Some(inner) = block.expr
{
// Run again with the inner expression
return check(cx, expr, inner, to_ty);
}

// Catching:
// `std::mem::transmute(const { u64::MIN as *const u64 });`
if let ExprKind::ConstBlock(ConstBlock { body, .. }) = arg.kind {
// Strip out the const and run again
let block = cx.tcx.hir_body(body).value;
return check(cx, expr, block, to_ty);
}

false
}
11 changes: 11 additions & 0 deletions tests/ui/transmuting_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,19 @@ fn transmute_const_int() {
}
}

fn transumute_single_expr_blocks() {
unsafe {
let _: &u64 = std::mem::transmute({ 0 as *const u64 });
//~^ transmuting_null

let _: &u64 = std::mem::transmute(const { u64::MIN as *const u64 });
//~^ transmuting_null
}
}

fn main() {
one_liners();
transmute_const();
transmute_const_int();
transumute_single_expr_blocks();
}
14 changes: 13 additions & 1 deletion tests/ui/transmuting_null.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,17 @@ error: transmuting a known null pointer into a reference
LL | let _: &u64 = std::mem::transmute(u64::MIN as *const u64);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 4 previous errors
error: transmuting a known null pointer into a reference
--> tests/ui/transmuting_null.rs:42:23
|
LL | let _: &u64 = std::mem::transmute({ 0 as *const u64 });
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: transmuting a known null pointer into a reference
--> tests/ui/transmuting_null.rs:45:23
|
LL | let _: &u64 = std::mem::transmute(const { u64::MIN as *const u64 });
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 6 previous errors