External Publication
Visit Post

Reducing Raw Pointer Footguns: Preventing Reference Aliasing Violations at Compile Time

Rust Internals [Unofficial] May 17, 2026
Source

I just added the #[guard] attribute and the guard_block!({ ... }) macro to improve the guard

Previously, the guard did not cover this. Now, it covers this:

#[guard]
fn a(guard: &AliasingGuardMut<Vec<i32>>) {
    let direct_ptr = guard.as_ptr();
    let mutable_reference = guard.mutable_reference();
    unsafe { *direct_ptr = vec![1] };
    *mutable_reference = vec![1];
}

fn main() {

    let mut s = vec![1, 2, 3];

    let mut guard = AliasingGuardMut::from_reference(&mut s);

    guard_block!({
        let b = &raw mut s;
        let a = guard.mutable_reference();
        unsafe { *b = vec![1] };
        *a = vec![1];
    });

}

It produces the following compile time error:

There is still case that can not be covered yet, it is when the declaration is ouside the guard. This is because, during macro expansion, we do not know whether the dereferenced variable is a pointer or a reference. Once compile time reflection is available, we will be able to determine the variable’s type at compile time and cover this case as well

fn main() {

    let mut s = vec![1, 2, 3];

    let mut guard = AliasingGuardMut::from_reference(&mut s);
    let b = &raw mut s;

    guard_block!({
        let a = guard.mutable_reference();
        unsafe { *b = vec![1] };
        *a = vec![1];
    });

}

Discussion in the ATmosphere

Loading comments...