|
| 1 | +# ❗🔙 Opaque and transparent associated constants |
| 2 | + |
| 3 | +As we want to be able to use associated constants in types, we have to look into them for unification. |
| 4 | + |
| 5 | +```rust |
| 6 | +trait Encode { |
| 7 | + const LENGTH: usize; |
| 8 | + fn encode(&self) -> [u8; Self::LENGTH]; |
| 9 | +} |
| 10 | + |
| 11 | +struct Dummy<const N: usize>; |
| 12 | +impl<const N: usize> for Dummy<N> { |
| 13 | + const LENGTH: usize = N + 1; |
| 14 | + fn encode(&self) -> [u8; Self::LENGTH] { |
| 15 | + [0; N + 1] |
| 16 | + } |
| 17 | +} |
| 18 | +``` |
| 19 | + |
| 20 | +For this to compile, we have to unify `Self::LENGTH` with `N + 1`. That means that we have to look into |
| 21 | +this associated constant, i.e. we have to treat it as transparent. |
| 22 | + |
| 23 | +Treating all associated constants causes some concerns however. |
| 24 | + |
| 25 | +#### Additional stability requirements |
| 26 | + |
| 27 | +Consider a library which has a public associated constant |
| 28 | + |
| 29 | +```rust |
| 30 | +use std::mem::size_of; |
| 31 | +trait WithAssoc { |
| 32 | + const ASSOC: usize; |
| 33 | +} |
| 34 | + |
| 35 | +struct MyType<T>(Vec<T>); |
| 36 | +impl<T> WithAssoc for MyType<T> { |
| 37 | + const ASSOC: usize = size_of::<Vec<T>>(); |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +In a new minor version, they've cleaned up their code and changed the associated constant to `size_of::<Self>()`. |
| 42 | +Without transparent associated constant, this can't break anything. If `ASSOC` is treated transparently, |
| 43 | +this change is now theoretically breaking. |
| 44 | + |
| 45 | +#### Overly complex associated constants |
| 46 | + |
| 47 | +Our abstract representation used during unification will not be able to represent arbitrary user code. |
| 48 | +This means that there will be some - potentially already existing - associated constants we cannot convert |
| 49 | +to this abstract representation. |
| 50 | + |
| 51 | +It is unclear how much code is affected by this and what the right solution for this would be. |
| 52 | +We should probably either silently keep these associated constants opaque or keep them opaque and emit a warning. |
| 53 | + |
| 54 | +### Keeping some associated constants opaque |
| 55 | + |
| 56 | +Still undecided how this should be handled. We can make transparent constants opt-in, potentially making associated constants |
| 57 | +used in some other type of the trait impl transparent by default. We could also make constants transparent by default |
| 58 | +and keep constants for which the conversion failed opaque, either emitting a warning or just silently. |
| 59 | + |
| 60 | +## Status |
| 61 | + |
| 62 | +**Blocked**: We should wait for `feature(generic_const_exprs)` to be closer to stable before thinking about this. |
0 commit comments