1# Const Generics23## Kinds of const arguments45Most of the kinds of `ty::Const` that exist have direct parallels to kinds of types that exist, for example `ConstKind::Param` is equivalent to `TyKind::Param`.67The main interesting points here are:8- [`ConstKind::Unevaluated`], which is equivalent to `TyKind::Alias` and in the long term should be renamed (as well as introducing an `AliasConstKind` to parallel `ty::AliasKind`).9- [`ConstKind::Value`], which is the final value of a `ty::Const` after monomorphization.10 This is somewhat similar to fully concrete things like `TyKind::Str` or `TyKind::ADT`.1112For a complete list of *all* kinds of const arguments and how they are actually represented in the type system, see the [`ConstKind`] type.1314Inference Variables are quite boring and treated equivalently to type inference variables almost everywhere.15Const Parameters are also similarly boring and equivalent to uses of type parameters almost everywhere.16However, there are some interesting subtleties with how they are handled during parsing, name resolution, and AST lowering: [ambig-unambig-ty-and-consts].1718## Anon Consts1920Anon Consts (short for anonymous const items) are how arbitrary expression are represented in const generics, for example an array length of `1 + 1` or `foo()` or even just `0`.21These are unique to const generics and have no real type equivalent.2223### Desugaring2425```rust26struct Foo<const N: usize>;27type Alias = [u8; 1 + 1];28```2930In this example we have a const argument of `1 + 1` (the array length) which is represented as an *anon const*. The desugaring would look something like:31```rust32struct Foo<const N: usize>;3334const ANON: usize = 1 + 1;35type Alias = [u8; ANON];36```3738Where the array length in `[u8; ANON]` isn't itself an anon const containing a usage of `ANON`, but a kind of "direct" usage of the `ANON` const item ([`ConstKind::Unevaluated`]).3940Anon consts do not inherit any generic parameters of the item they are inside of:41```rust42struct Foo<const N: usize>;43type Alias<T: Sized> = [T; 1 + 1];4445// Desugars To;4647struct Foo<const N: usize>;4849const ANON: usize = 1 + 1;50type Alias<T: Sized> = [T; ANON];51```5253Note how the `ANON` const has no generic parameters or where clauses, even though `Alias` has both a type parameter `T` and a where clauses `T: Sized`.54This desugaring is part of how we enforce that anon consts can't make use of generic parameters.5556While it's useful to think of anon consts as being desugared to real const items, the compiler does not actually implement things this way.5758At AST lowering time we do not yet know the *type* of the anon const, so we can't desugar to a real HIR item with an explicitly written type.59To work around this, we have [`DefKind::AnonConst`] and [`hir::Node::AnonConst`],60which are used to represent these anonymous const items that can't actually be desugared.6162The types of these anon consts are obtainable from the [`type_of`] query.63However, the `type_of` query does not actually contain logic for computing the type (and, in fact, it just ICEs when called).64Instead, HIR Ty lowering is responsible for *feeding* the value of the `type_of` query for any anon consts that get lowered.65HIR Ty lowering can determine the type of the anon const by looking at the type of the Const Parameter that the anon const is an argument to.6667TODO: write a chapter on query feeding and link it here6869In some sense the desugarings from the previous examples are to:70```rust71struct Foo<const N: usize>;72type Alias = [u8; 1 + 1];7374// sort-of desugars to pseudo-rust:75struct Foo<const N: usize>;7677const ANON = 1 + 1;78type Alias = [u8; ANON];79```8081When we go through HIR ty lowering for the array type in `Alias`, we will lower the array length too, and feed `type_of(ANON) -> usize`.82This will effectively set the type of the `ANON` const item during some later part of the compiler rather than when constructing the HIR.8384After all of this desugaring has taken place the final representation in the type system (ie as a `ty::Const`) is a `ConstKind::Unevaluated` with the `DefId` of the `AnonConst`. This is equivalent to how we would representa a usage of an actual const item if we were to represent them without going through an anon const (e.g. when `min_generic_const_args` is enabled).8586This allows the representation for const "aliases" to be the same as the representation of `TyKind::Alias`. Having a proper HIR body also allows for a *lot* of code re-use, e.g. we can reuse HIR typechecking and all of the lowering steps to MIR where we can then reuse const eval.8788### Enforcing lack of Generic Parameters8990There are three ways that we enforce anon consts can't use generic parameters:911. Name Resolution will not resolve paths to generic parameters when inside of an anon const922. HIR Ty lowering will error when a `Self` type alias to a type referencing generic parameters is encountered inside of an anon const933. Anon Consts do not inherit where clauses or generics from their parent definition (ie [`generics_of`] does not contain a parent for anon consts)9495```rust96// *1* Errors in name resolution97type Alias<const N: usize> = [u8; N + 1];98//~^ ERROR: generic parameters may not be used in const operations99100// *2* Errors in HIR Ty lowering:101struct Foo<T>(T);102impl<T> Foo<T> {103 fn assoc() -> [u8; { let a: Self; 0 }] {}104 //~^ ERROR: generic `Self` types are currently not permitted in anonymous constants105}106107// *3* Errors due to lack of where clauses on the desugared anon const108trait Trait<T> {109 const ASSOC: usize;110}111fn foo<T>() -> [u8; <()>::ASSOC]112//~^ ERROR: no associated item named `ASSOC` found for unit type `()`113where114 (): Trait<T> {}115```116117The second point is particularly subtle as it is very easy to get HIR Ty lowering wrong and not properly enforce that anon consts can't use generic parameters.118The existing check is too conservative and accidentally permits some generic parameters to wind up in the body of the anon const [#144547](https://github.com/rust-lang/rust/issues/144547).119120Erroneously allowing generic parameters in anon consts can sometimes lead to ICEs but can also lead to accepting illformed programs.121122The third point is also somewhat subtle, by not inheriting any of the where clauses of the parent item we can't wind up with the trait solving inferring inference variables to generic parameters based off where clauses in scope that mention generic parameters.123For example, inferring `?x=T` from the expression `<() as Trait<?x>>::ASSOC` and an in-scope where clause of `(): Trait<T>`.124125This also makes it much more likely that the compiler will ICE or atleast incidentally emit some kind of error if we *do* accidentally allow generic parameters in an anon const, as the anon const will have none of the necessary information in its environment to properly handle the generic parameters.126127#### Array repeat expressions128The one exception to all of the above is repeat counts of array expressions.129As a *backwards compatibility hack*, we allow the repeat count const argument to use generic parameters.130131```rust132fn foo<T: Sized>() {133 let a = [1_u8; size_of::<T>()];134}135```136137However, to avoid most of the problems involved in allowing generic parameters in anon const const arguments we require that the constant be evaluated before monomorphization (e.g. during type checking). In some sense we only allow generic parameters here when they are semantically unused.138139In the previous example the anon const can be evaluated for any type parameter `T` because raw pointers to sized types always have the same size (e.g. `8` on 64bit platforms).140141When detecting that we evaluated an anon const that syntactically contained generic parameters, but did not actually depend on them for evaluation to succeed, we emit the [`const_evaluatable_unchecked` FCW][cec_fcw].142This is intended to become a hard error once we stabilize more ways of using generic parameters in const arguments, for example `min_generic_const_args` or (the now dead) `generic_const_exprs`.143144The implementation for this FCW can be found here: [`const_eval_resolve_for_typeck`]145146### Incompatibilities with `generic_const_parameter_types`147148Supporting const parameters such as `const N: [u8; M]` or `const N: Foo<T>` does not work very nicely with the current anon consts setup.149There are two reasons for this:1501. As anon consts cannot use generic parameters, their type *also* can't reference generic parameters.151 This means it is fundamentally not possible to use an anon const as an argument to a const parameter whose type still references generic parameters.152153 ```rust154 #![feature(adt_const_params, generic_const_parameter_types)]155156 fn foo<const N: usize, const M: [u8; N]>() {}157158 fn bar<const N: usize>() {159 // There is no way to specify the const argument to `M`160 foo::<N, { [1_u8; N] }>();161 }162 ```1631642. We currently require knowing the type of anon consts when lowering them during HIR ty lowering.165 With generic const parameter types it may be the case that the currently known type contains inference variables (ie may not be fully known yet).166167 ```rust168 #![feature(adt_const_params, generic_const_parameter_types)]169170 fn foo<const N: usize, const M: [u8; N]>() {}171172 fn bar() {173 // The const argument to `N` must be explicitly specified174 // even though it is able to be inferred175 foo::<_, { [1_u8; 3] }>();176 }177 ```178179It is currently unclear what the right way to make `generic_const_parameter_types` work nicely with the rest of const generics is.180181`generic_const_exprs` would have allowed for anon consts with types referencing generic parameters, but that design wound up unworkable.182183`min_generic_const_args` will allow for some expressions (for example array construction) to be representable without an anon const and therefore without running into these issues, though whether this is *enough* has yet to be determined.184185## Checking types of Const Arguments186187In order for a const argument to be well formed it must have the same type as the const parameter it is an argument to.188For example, a const argument of type `bool` for an array length is not well formed, as an array's length parameter has type `usize`.189190```rust191type Alias<const B: bool> = [u8; B];192//~^ ERROR:193```194195To check this, we have [`ClauseKind::ConstArgHasType(ty::Const, Ty)`][const_arg_has_type], where,196for each Const Parameter defined on an item,197we also desugar an equivalent `ConstArgHasType` clause into its list of where cluases.198This ensures that whenever we check wellformedness of anything by proving all of its clauses,199we also check happen to check that all of the Const Arguments have the correct type.200201```rust202fn foo<const N: usize>() {}203204// desugars to in pseudo-rust205206fn foo<const N>()207where208// ConstArgHasType(N, usize)209 N: usize, {}210```211212Proving `ConstArgHasType` goals is implemented by first computing the type of the const argument, then equating it with the provided type.213A rough outline of how the type of a Const Argument may be computed:214- [`ConstKind::Param(N)`][`ConstKind::Param`] can be looked up in the [`ParamEnv`] to find a `ConstArgHasType(N, ty)` clause215- [`ConstKind::Value`] stores the type of the value inside itself so can trivially be accessed216- [`ConstKind::Unevaluated`] can have its type computed by calling the `type_of` query217- See the implementation of proving `ConstArgHasType` goals for more detailed information218219`ConstArgHasType` is *the* soundness critical way that we check Const Arguments have the correct type.220However, we do *indirectly* check the types of Const Arguments a different way in some cases.221222```rust223type Alias = [u8; true];224225// desugars to226227const ANON: usize = true;228type Alias = [u8; ANON];229```230231By feeding the type of an anon const with the type of the Const Parameter,232we guarantee that the `ConstArgHasType` goal involving the anon const will succeed.233In cases where the type of the anon const doesn't match the type of the Const Parameter,234what actually happens is a *type checking* error when type checking the anon const's body.235236Looking at the above example, this corresponds to `[u8; ANON]` being a well formed type because `ANON` has type `usize`, but the *body* of `ANON` being illformed and resulting in a type checking error because `true` can't be returned from a const item of type `usize`.237238[ambig-unambig-ty-and-consts]: ./ambig-unambig-ty-and-consts.md239[`ConstKind`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ConstKind.html240[`ConstKind::Infer`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ConstKind.html#variant.Infer241[`ConstKind::Param`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ConstKind.html#variant.Param242[`ConstKind::Unevaluated`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ConstKind.html#variant.Unevaluated243[`ConstKind::Value`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ConstKind.html#variant.Value244[const_arg_has_type]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.ClauseKind.html#variant.ConstArgHasType245[`ParamEnv`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.ParamEnv.html246[`generics_of`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#impl-TyCtxt%3C'tcx%3E/method.generics_of247[`type_of`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.type_of248[`DefKind::AnonConst`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/def/enum.DefKind.html#variant.AnonConst249[`hir::Node::AnonConst`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.Node.html#variant.AnonConst#250[cec_fcw]: https://github.com/rust-lang/rust/issues/76200251[`const_eval_resolve_for_typeck`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.const_eval_resolve_for_typeck
Findings
✓ No findings reported for this file.