rust/compiler/rustc_middle/src
Guillaume Gomez 66443a1852
Rollup merge of #96557 - nbdd0121:const, r=oli-obk
Allow inline consts to reference generic params

Tracking issue: #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
2022-05-06 20:05:37 +02:00
..
dep_graph
hir rustc: Panic by default in DefIdTree::parent 2022-05-02 01:56:50 +03:00
infer
middle rustc: Panic by default in DefIdTree::parent 2022-05-02 01:56:50 +03:00
mir Update ProjectionElem::Downcast documentation 2022-05-03 22:29:51 +02:00
query Add support for a new attribute #[debugger_visualizer] to support embedding debugger visualizers into a generated PDB. 2022-05-03 10:53:54 -07:00
thir
traits
ty Hide InlineConst's generic arg during print 2022-05-03 14:37:16 +01:00
util
arena.rs
lib.rs Stabilize bool::then_some 2022-05-04 13:22:08 +02:00
lint.rs
macros.rs
metadata.rs
tests.rs
thir.rs Make all thir types implement clone 2022-04-20 00:11:08 +02:00