diff options
| author | Michael Goulet <michael@errs.io> | 2025-06-26 20:15:17 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-06-26 20:15:17 -0400 |
| commit | 36cde678948400f2dcda71ed09e2072f093b63d5 (patch) | |
| tree | 1469a5fcbd2aa647383a6ce2e1a08c9541b905ba /compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp | |
| parent | 0446a0d14bb378dbe9a59f0f3e30a2f14aabd80d (diff) | |
| parent | bade3fd0580815f1a5a4abd33244982dc458d54d (diff) | |
| download | rust-36cde678948400f2dcda71ed09e2072f093b63d5.tar.gz rust-36cde678948400f2dcda71ed09e2072f093b63d5.zip | |
Rollup merge of #140942 - RalfJung:const-ref-to-mut, r=oli-obk
const-eval: allow constants to refer to mutable/external memory, but reject such constants as patterns
This fixes https://github.com/rust-lang/rust/issues/140653 by accepting code such as this:
```rust
static FOO: AtomicU32 = AtomicU32::new(0);
const C: &'static AtomicU32 = &FOO;
```
This can be written entirely in safe code, so there can't really be anything wrong with it.
We also accept the much more questionable following code, since it looks very similar to the interpreter:
```rust
static mut FOO2: u32 = 0;
const C2: &'static u32 = unsafe { &mut FOO2 };
```
Using this without causing UB is at least very hard (the details are unclear since it is related to how the aliasing model deals with the staging of const-eval vs runtime code).
If a constant like `C2` is used as a pattern, we emit an error:
```
error: constant BAD_PATTERN cannot be used as pattern
--> $DIR/const_refs_to_static_fail.rs:30:9
|
LL | BAD_PATTERN => {},
| ^^^^^^^^^^^
|
= note: constants that reference mutable or external memory cannot be used as pattern
```
(If you somehow manage to build a pattern with constant `C`, you'd get the same error, but that should be impossible: we don't have a type that can be used in patterns and that has interior mutability.)
The same treatment is afforded for shared references to `extern static`, for the same reason: the const evaluation is entirely fine with it, we just can't build a pattern for it -- and when using interior mutability, this can be totally sound.
We do still not accept anything where there is an `&mut` in the final value of the const, as that should always require unsafe code and it's hard to imagine a sound use-case that would require this.
Diffstat (limited to 'compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp')
0 files changed, 0 insertions, 0 deletions
