Skip to content

Commit 7b99112

Browse files
authored
Merge pull request #1859 from RalfJung/const-ref-to-mut
allow constants to refer to mutable/external memory, but reject such constants as patterns
2 parents 051f1e5 + 5910551 commit 7b99112

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/items/constant-items.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,36 @@ const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
4848
};
4949
```
5050

51-
r[items.const.final-value-immutable]
52-
The final value of a `const` item cannot contain references to anything mutable.
51+
r[items.const.no-mut-refs]
52+
The final value of a `const` item cannot contain any mutable references.
53+
54+
```rust
55+
# #![allow(static_mut_refs)]
56+
static mut S: u8 = 0;
57+
const C: &u8 = unsafe { &mut S }; // OK
58+
```
59+
60+
```rust
61+
# use core::sync::atomic::AtomicU8;
62+
static S: AtomicU8 = AtomicU8::new(0);
63+
const C: &AtomicU8 = &S; // OK
64+
```
65+
66+
```rust,compile_fail,E0080
67+
# #![allow(static_mut_refs)]
68+
static mut S: u8 = 0;
69+
const C: &mut u8 = unsafe { &mut S }; // ERROR not allowed
70+
```
71+
72+
> [!NOTE]
73+
> We also disallow, in the final value, shared references to mutable statics created in the initializer for a separate reason. Consider:
74+
>
75+
> ```rust,compile_fail,E0492
76+
> # use core::sync::atomic::AtomicU8;
77+
> const C: &AtomicU8 = &AtomicU8::new(0); // ERROR
78+
> ```
79+
>
80+
> Here, the `AtomicU8` is a temporary that is lifetime extended to `'static` (see [destructors.scope.lifetime-extension.static]), and references to lifetime-extended temporaries with interior mutability are not allowed in the final value of a constant expression (see [const-eval.const-expr.borrows]).
5381
5482
r[items.const.expr-omission]
5583
The constant expression may only be omitted in a [trait definition].

src/patterns.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -975,6 +975,9 @@ r[patterns.const.generic]
975975
In particular, the value of `C` must be known at pattern-building time (which is pre-monomorphization).
976976
This means that associated consts that involve generic parameters cannot be used as patterns.
977977

978+
r[patterns.const.immutable]
979+
The value of `C` must not contain any references to mutable statics (`static mut` items or interior mutable `static` items) or `extern` statics.
980+
978981
r[patterns.const.translation]
979982
After ensuring all conditions are met, the constant value is translated into a pattern, and now behaves exactly as-if that pattern had been written directly.
980983
In particular, it fully participates in exhaustiveness checking.

0 commit comments

Comments
 (0)