Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 113 additions & 8 deletions src/items/constant-items.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,35 +49,135 @@ const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
```

r[items.const.no-mut-refs]
The final value of a `const` item cannot contain any mutable references.
The final value of a `const` item, after the initializer is evaluated to a value that has the declared type of the constant, cannot contain any mutable references except as described below.

```rust
# #![allow(static_mut_refs)]
static mut S: u8 = 0;
const C: &u8 = unsafe { &mut S }; // OK
const _: &u8 = unsafe { &mut S }; // OK.
// ^^^^^^
// Allowed since this is coerced to `&S`.
```

```rust
# use core::sync::atomic::AtomicU8;
static S: AtomicU8 = AtomicU8::new(0);
const C: &AtomicU8 = &S; // OK
const _: &AtomicU8 = &S; // OK.
// ^^
// Allowed even though the shared reference is to an interior
// mutable value.
```

```rust,compile_fail,E0080
# #![allow(static_mut_refs)]
static mut S: u8 = 0;
const C: &mut u8 = unsafe { &mut S }; // ERROR not allowed
const _: &mut u8 = unsafe { &mut S }; // ERROR.
// ^^^^^^
// Not allowed as the mutable reference appears in the final value.
```

> [!NOTE]
> We also disallow, in the final value, shared references to mutable statics created in the initializer for a separate reason. Consider:
> Constant initializers can be thought of, in most cases, as being inlined wherever the constant appears. If a constant whose value contains a mutable reference to a mutable static were to appear twice, and this were to be allowed, that would create two mutable references, each having `'static` lifetime, to the same place. This could produce undefined behavior.
>
> Constants that contain mutable references to temporaries whose scopes have been extended to the end of the program have that same problem and an additional one.
>
> ```rust,compile_fail,E0764
> const _: &mut u8 = &mut 0; // ERROR.
> // ^^^^^^
> // Not allowed as the mutable reference appears in the final value and
> // because the constant expression contains a mutable borrow of an
> // expression whose temporary scope would be extended to the end of
> // the program.
> ```
>
> Here, the value `0` is a temporary whose scope is extended to the end of the program (see [destructors.scope.lifetime-extension.static]). Such temporaries cannot be mutably borrowed in constant expressions (see [const-eval.const-expr.borrows]).
>
> To allow this, we'd have to decide whether each use of the constant creates a new `u8` value or whether each use shares the same lifetime-extended temporary. The latter choice, though closer to how `rustc` thinks about this today, would break the conceptual model that, in most cases, the constant initializer can be thought of as being inlined wherever the constant is used. Since we haven't decided, and due to the other problem mentioned, this is not allowed.

```rust,compile_fail,E0080
# #![allow(static_mut_refs)]
static mut S: u8 = 0;
const _: &dyn Send = &unsafe { &mut S }; // ERROR.
// ^^^^^^
// Not allowed as the mutable reference appears in the final value,
// even though type erasure occurs.
```

Mutable references where the referent is a value of a [zero-sized type] are allowed.

```rust
# #![allow(static_mut_refs)]
static mut S: () = ();
const _: &mut () = unsafe { &mut S }; // OK.
// ^^ This is a zero-sized type.
```

```rust
# #![allow(static_mut_refs)]
static mut S: [u8; 0] = [0; 0];
const _: &mut [u8; 0] = unsafe { &mut S }; // OK.
// ^^^^^^^ This is a zero-sized type.
```

> [!NOTE]
> This is allowed as, for a value of a zero-sized type, no bytes can actually be mutated. We must accept this as `&mut []` is [promoted].
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that this is the first time in the reference that we document that mutable references to zero-length arrays can be promoted.

Note that this only works with zero-length arrays. Also, this promotion does not seem to always happen, see rust-lang/rust#140126

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this only works with zero-length arrays. Also, this promotion does not seem to always happen, see rust-lang/rust#140126

Look at the bottom note in https://doc.rust-lang.org/nightly/reference/const_eval.html#constant-expressions and rust-lang/rust#143129.


Values of [union type] are not considered to contain any references; for this purpose, a value of union type is treated as a sequence of untyped bytes.

```rust
# #![allow(static_mut_refs)]
union U { f: &'static mut u8 }
static mut S: u8 = 0;
const _: U = unsafe { U { f: &mut S }}; // OK.
// ^^^^^^^^^^^^^^^
// This is treated as a sequence of untyped bytes.
```

Mutable references contained within a [mutable static] may be referenced in the final value of a constant.

```rust
# #![allow(static_mut_refs)]
static mut S: &mut u8 = unsafe { static mut I: u8 = 0; &mut I };
const _: &&mut u8 = unsafe { &S }; // OK.
// ^^^^^^^
// This mutable reference comes from a `static mut`.
```

> [!NOTE]
> This is allowed as it's separately not allowed to read from a mutable static during constant evaluation. See [const-eval.const-expr.path-static].

Mutable references contained within an [external static] may be referenced in the final value of a constant.

```rust
# #![allow(static_mut_refs)]
unsafe extern "C" { static S: &'static mut u8; }
const _: &&mut u8 = unsafe { &S }; // OK.
// ^^^^^^^
// This mutable references comes from an extern static.
```

> [!NOTE]
> This is allowed as it's separately not allowed to read from an external static during constant evaluation. See [const-eval.const-expr.path-static].

> [!NOTE]
> As described above, we accept, in the final value of constant items, shared references to static items whose values have interior mutability.
>
> ```rust
> # use core::sync::atomic::AtomicU8;
> static S: AtomicU8 = AtomicU8::new(0);
> const _: &AtomicU8 = &S; // OK.
> ```
>
> However, we disallow similar code when the interior mutable value is created in the initializer.
>
> ```rust,compile_fail,E0492
> # use core::sync::atomic::AtomicU8;
> const C: &AtomicU8 = &AtomicU8::new(0); // ERROR
> const _: &AtomicU8 = &AtomicU8::new(0); // ERROR.
> ```
>
> 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]).
> Here, the `AtomicU8` is a temporary whose scope is extended to the end of the program (see [destructors.scope.lifetime-extension.static]). Such temporaries with interior mutability cannot be borrowed in constant expressions (see [const-eval.const-expr.borrows]).
>
> To allow this, we'd have to decide whether each use of the constant creates a new `AtomicU8` or whether each use shares the same lifetime-extended temporary. The latter choice, though closer to how `rustc` thinks about this today, would break the conceptual model that, in most cases, the constant initializer can be thought of as being inlined wherever the constant is used. Since we haven't decided, this is not allowed.

r[items.const.expr-omission]
The constant expression may only be omitted in a [trait definition].
Expand Down Expand Up @@ -154,10 +254,15 @@ fn unused_generic_function<T>() {
[const_eval]: ../const_eval.md
[associated constant]: ../items/associated-items.md#associated-constants
[constant value]: ../const_eval.md#constant-expressions
[external static]: items.extern.static
[free]: ../glossary.md#free-item
[static lifetime elision]: ../lifetime-elision.md#const-and-static-elision
[trait definition]: traits.md
[underscore imports]: use-declarations.md#underscore-imports
[`Copy`]: ../special-types-and-traits.md#copy
[value namespace]: ../names/namespaces.md
[promotion]: ../destructors.md#constant-promotion
[mutable static]: items.static.mut
[promoted]: destructors.scope.const-promotion
[promotion]: destructors.scope.const-promotion
[union type]: type.union
[zero-sized type]: layout.properties.size