Skip to content

Commit

Permalink
Auto merge of rust-lang#130540 - veera-sivarajan:fix-87525, r=estebank
Browse files Browse the repository at this point in the history
Add a Lint for Pointer to Integer Transmutes in Consts

Fixes rust-lang#87525

This PR adds a MirLint for pointer to integer transmutes in const functions and associated consts. The implementation closely follows this comment: rust-lang#85769 (comment). More details about the implementation can be found in the comments.

Note: This could break some sound code as mentioned by RalfJung in rust-lang#85769 (comment):

> ... technically const-code could transmute/cast an int to a ptr and then transmute it back and that would be correct -- so the lint will deny some sound code. Does not seem terribly likely though.

References:
1. https://doc.rust-lang.org/std/mem/fn.transmute.html
2. https://doc.rust-lang.org/reference/items/associated-items.html#associated-constants
  • Loading branch information
bors committed Oct 6, 2024
2 parents a0653c5 + 98b59a1 commit d050730
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
9 changes: 6 additions & 3 deletions tests/ui/transmutes_expressible_as_ptr_casts.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ fn issue_10449() {
}

// Pointers cannot be cast to integers in const contexts
#[allow(ptr_to_integer_transmute_in_consts, reason = "This is tested in the compiler test suite")]
const fn issue_12402<P>(ptr: *const P) {
unsafe { transmute::<*const i32, usize>(&42i32) };
unsafe { transmute::<fn(*const P), usize>(issue_12402) };
let _ = unsafe { transmute::<_, usize>(ptr) };
// This test exists even though the compiler lints against it
// to test that clippy's transmute lints do not trigger on this.
unsafe { std::mem::transmute::<*const i32, usize>(&42i32) };
unsafe { std::mem::transmute::<fn(*const P), usize>(issue_12402) };
let _ = unsafe { std::mem::transmute::<_, usize>(ptr) };
}
9 changes: 6 additions & 3 deletions tests/ui/transmutes_expressible_as_ptr_casts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ fn issue_10449() {
}

// Pointers cannot be cast to integers in const contexts
#[allow(ptr_to_integer_transmute_in_consts, reason = "This is tested in the compiler test suite")]
const fn issue_12402<P>(ptr: *const P) {
unsafe { transmute::<*const i32, usize>(&42i32) };
unsafe { transmute::<fn(*const P), usize>(issue_12402) };
let _ = unsafe { transmute::<_, usize>(ptr) };
// This test exists even though the compiler lints against it
// to test that clippy's transmute lints do not trigger on this.
unsafe { std::mem::transmute::<*const i32, usize>(&42i32) };
unsafe { std::mem::transmute::<fn(*const P), usize>(issue_12402) };
let _ = unsafe { std::mem::transmute::<_, usize>(ptr) };
}

0 comments on commit d050730

Please sign in to comment.