Skip to content

const checker confuses "pointer to static mut" with "local mutable variable that escapes this scope" #118447

Closed

Description

This code gets rejected, and (as far as I can tell) not for good reasons:

#![feature(const_mut_refs)]

#[repr(C)]
struct Foo {
    v: u32,
}

#[repr(C)]
struct Bar {
    foo: *mut Foo,
}

unsafe impl Sync for Bar {}

extern "C" {
    static mut foo: Foo;
}

fn do_it() {
    static BAR: Bar = Bar {
        foo: unsafe { core::ptr::addr_of_mut!(foo)},
    };
}

The error is

error[E0764]: raw mutable references are not allowed in the final value of statics
  --> src/lib.rs:21:23
   |
21 |         foo: unsafe { core::ptr::addr_of_mut!(foo)},
   |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |

This error is meant to catch cases like this

    static BAR: Bar = Bar {
        foo: &mut Foo { v: 0 },
    };

where a temporary (Foo { v: 0 }) escapes into the final value of the constant. However, for the original code there's no temporary, this is a pointer to a static.

Here's an executable pure Rust version (no extern).

It seems to me we could allow mutable pointers to already existing (mutable) allocations to leak out into the final const value. However we should carefully consider the consequences of this. I can't think of anything that would go wrong here right now, but that might be just a sign of sleep deprivation. ;)

Cc @rust-lang/wg-const-eval

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation (MIR interpretation)C-feature-requestCategory: A feature request, i.e: not implemented / a PR.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions