Skip to content

Commit

Permalink
Rollup merge of rust-lang#96557 - nbdd0121:const, r=oli-obk
Browse files Browse the repository at this point in the history
Allow inline consts to reference generic params

Tracking issue: rust-lang#76001

The RFC says that inline consts cannot reference to generic parameters (for now), same as array length expressions. And expresses that it's desirable for it to reference in-scope generics, when array length expressions gain that feature as well.

However it is possible to implement this for inline consts before doing this for all anon consts, because inline consts are only used as values and they won't be used in the type system. So we can have:
```rust
fn foo<T>() {
    let x = [4i32; std::mem::size_of::<T>()];   // NOT ALLOWED (for now)
    let x = const { std::mem::size_of::<T>() }; // ALLOWED with this PR!
    let x = [4i32; const { std::mem::size_of::<T>() }];   // NOT ALLOWED (for now)
}
```

This would make inline consts super useful for compile-time checks and assertions:
```rust
fn assert_zst<T>() {
    const { assert!(std::mem::size_of::<T>() == 0) };
}
```

This would create an error during monomorphization when `assert_zst` is instantiated with non-ZST `T`s. A error during mono might sound scary, but this is exactly what a "desugared" inline const would do:
```rust
fn assert_zst<T>() {
    struct F<T>(T);
    impl<T> F<T> {
        const V: () = assert!(std::mem::size_of::<T>() == 0);
    }
    let _ = F::<T>::V;
}
```

It should also be noted that the current inline const implementation can already reference the type params via type inference, so this resolver-level restriction is not any useful either:
```rust
fn foo<T>() -> usize {
    let (_, size): (PhantomData<T>, usize) = const {
        const fn my_size_of<T>() -> (PhantomData<T>, usize) {
            (PhantomData, std::mem::size_of::<T>())
        }
        my_size_of()
    };
    size
}
```

```@rustbot``` label: F-inline_const
  • Loading branch information
GuillaumeGomez authored May 6, 2022
2 parents 7cd86aa + f0c2ac8 commit 13e8ace
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion tests/ui/indexing_slicing_index.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0080]: evaluation of `main::{constant#3}::<&i32>` failed
error[E0080]: evaluation of `main::{constant#3}` failed
--> $DIR/indexing_slicing_index.rs:31:14
|
LL | const { &ARR[idx4()] }; // Ok, let rustc handle const contexts.
Expand Down

0 comments on commit 13e8ace

Please sign in to comment.