rust/tests/ui/static/raw-ref-deref-without-unsafe.rs
Jubilee Young 3fdd8d5ef3 compiler: treat &raw (const|mut) UNSAFE_STATIC implied deref as safe
The implied deref to statics introduced by HIR->THIR lowering is only
used to create place expressions, it lacks unsafe semantics.
It is also confusing, as there is no visible `*ident` in the source.
For both classes of "unsafe static" (extern static and static mut)
allow this operation.

We lack a clear story around `thread_local! { static mut }`, which
is actually its own category of item that reuses the static syntax but
has its own rules. It's possible they should be similarly included, but
in the absence of a good reason one way or another, we do not bless it.
2024-07-22 14:54:36 -07:00

19 lines
678 B
Rust

#![feature(const_mut_refs)]
use std::ptr;
// This code should remain unsafe because of the two unsafe operations here,
// even if in a hypothetical future we deem all &raw (const|mut) *ptr exprs safe.
static mut BYTE: u8 = 0;
static mut BYTE_PTR: *mut u8 = ptr::addr_of_mut!(BYTE);
// An unsafe static's ident is a place expression in its own right, so despite the above being safe
// (it's fine to create raw refs to places!) the following derefs the ptr before creating its ref!
static mut DEREF_BYTE_PTR: *mut u8 = ptr::addr_of_mut!(*BYTE_PTR);
//~^ ERROR: use of mutable static
//~| ERROR: dereference of raw pointer
fn main() {
let _ = unsafe { DEREF_BYTE_PTR };
}