Skip to content

Commit c2dd413

Browse files
committed
Auto merge of #12403 - samueltardieu:issue-12402, r=blyxyas
Pointers cannot be converted to integers at compile time Fix #12402 changelog: [`transmutes_expressible_as_ptr_casts`]: do not suggest invalid const casts
2 parents aceeb54 + 6e5332c commit c2dd413

File tree

4 files changed

+17
-1
lines changed

4 files changed

+17
-1
lines changed

clippy_lints/src/transmute/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ impl<'tcx> LateLintPass<'tcx> for Transmute {
592592
| (eager_transmute::check(cx, e, arg, from_ty, to_ty));
593593

594594
if !linted {
595-
transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, from_ty_adjusted, to_ty, arg);
595+
transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, from_ty_adjusted, to_ty, arg, const_context);
596596
}
597597
}
598598
}

clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@ pub(super) fn check<'tcx>(
1818
from_ty_adjusted: bool,
1919
to_ty: Ty<'tcx>,
2020
arg: &'tcx Expr<'_>,
21+
const_context: bool,
2122
) -> bool {
2223
use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
2324
let mut app = Applicability::MachineApplicable;
2425
let mut sugg = match check_cast(cx, e, from_ty, to_ty) {
26+
Some(FnPtrAddrCast | PtrAddrCast) if const_context => return false,
2527
Some(PtrPtrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) => {
2628
Sugg::hir_with_context(cx, arg, e.span.ctxt(), "..", &mut app)
2729
.as_ty(to_ty.to_string())

tests/ui/transmutes_expressible_as_ptr_casts.fixed

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,10 @@ fn issue_10449() {
8282

8383
let _x: u8 = unsafe { *(f as *const u8) };
8484
}
85+
86+
// Pointers cannot be cast to integers in const contexts
87+
const fn issue_12402<P>(ptr: *const P) {
88+
unsafe { transmute::<*const i32, usize>(&42i32) };
89+
unsafe { transmute::<fn(*const P), usize>(issue_12402) };
90+
let _ = unsafe { transmute::<_, usize>(ptr) };
91+
}

tests/ui/transmutes_expressible_as_ptr_casts.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,10 @@ fn issue_10449() {
8282

8383
let _x: u8 = unsafe { *std::mem::transmute::<fn(), *const u8>(f) };
8484
}
85+
86+
// Pointers cannot be cast to integers in const contexts
87+
const fn issue_12402<P>(ptr: *const P) {
88+
unsafe { transmute::<*const i32, usize>(&42i32) };
89+
unsafe { transmute::<fn(*const P), usize>(issue_12402) };
90+
let _ = unsafe { transmute::<_, usize>(ptr) };
91+
}

0 commit comments

Comments
 (0)