rust-lang / reference

The Rust Reference
https://doc.rust-lang.org/nightly/reference/
Apache License 2.0
1.25k stars 491 forks source link

Document restrictions on use of generics in const contexts in type position #1581

Closed traviscross closed 3 months ago

traviscross commented 3 months ago

As raised here:

...related to the language:

Const contexts that are used as parts of types (array type and repeat length expressions as well as const generic arguments) can only make restricted use of surrounding generic type and lifetime parameters.

We should document what these restrictions are precisely.

Here's an example of what doesn't work:

fn foo<const C: usize>() {
    let _ = [(); const { C + 1 }];
    //~^ ERROR generic parameters may not be used in const operations
}

Similarly:

trait Tr {
    const C: usize;
}

impl Tr for () {
    const C: usize = 0;
}

fn foo<T: Tr>() {
    let _ = [(); const { T::C }];
    //~^ ERROR constant expression depends on a generic parameter
}

cc @RalfJung @ehuss @BoxyUwU

RalfJung commented 3 months ago

We should probably also emit more specific errors -- it is not wrong for "constant expression [to depend] on a generic parameter", it's just wrong in this specific case where that expression occurs in a type.

Also, strange that the two examples above lead to different errors that say the same thing in different words -- they must be caught by different checks, somehow?