| @@ -0,0 +1,152 @@ |
| 1 | +# ADR 0047: Associated types |
| 2 | + |
| 3 | +**Status:** Proposed (2026-10-15, issue #234); needs engineering review (#44). The review should look in particular at the soundness argument for deferred equalities under GADT refinements, and at the termination rule for reduction. It reverses the "no associated types" alternative of [ADR 0018](0018-multi-parameter-traits-and-hkt.md). |
| 4 | + |
| 5 | +## Context |
| 6 | +[ADR 0018](0018-multi-parameter-traits-and-hkt.md) gave traits several parameters and higher kinds. It left out functional dependencies and associated types, to keep inference "HM plus a separate solving pass", and asked for evidence from use first. Several places pay for that: |
| 7 | +- **Every argument of a multi-parameter trait must be known at a call:** `show(convert(True))` is E0403. |
| 8 | +- **A trait cannot name a type its impls choose:** `trait Collection<c, e> { fn empty() -> c }` is rejected, because no call can determine `e`. |
| 9 | +- **Std has parallel per-collection APIs with no shared abstraction:** `list.fold`, `array.fold`, `dict.fold`, `bytes.to_list`, … A generic `sum` over collections cannot be written. |
| 10 | +- **[ADR 0019](0019-user-defined-derives.md) could not offer a type-level `Generic` derive,** because it needs a type computed from another. |
| 11 | + |
| 12 | +The owner chose associated types over functional dependencies, with generic associated types (GATs) and where-clause bindings, and a `Collection` trait in std. |
| 13 | + |
| 14 | +Associated types put functions on types into unification. They interact with the parts of the checker that are already delicate: GADT refinements, which are local to a `match` arm (ADR 0041); the separate solving pass; and generalization. The decision below is shaped by that. |
| 15 | + |
| 16 | +## Decision |
| 17 | + |
| 18 | +### Surface syntax |
| 19 | +Until the parser accepts it (the first implementation PR), this sample is marked `text`, so the documentation test does not parse it yet. |
| 20 | + |
| 21 | +```text |
| 22 | +pub trait Collection<c> { |
| 23 | + type Elem |
| 24 | + fn size(c: c) -> Int |
| 25 | + fn fold(c: c, acc: b, f: fn(b, Elem<c>) -> b / <e>) -> b / <e> |
| 26 | +} |
| 27 | + |
| 28 | +impl Collection<List<a>> { |
| 29 | + type Elem = a |
| 30 | + fn size(c) { list.length(c) } |
| 31 | + fn fold(c, acc, f) { list.fold(c, acc, f) } |
| 32 | +} |
| 33 | + |
| 34 | +impl Collection<Dict<k, v>> { |
| 35 | + type Elem = (k, v) |
| 36 | + fn size(d) { dict.size(d) } |
| 37 | + fn fold(d, acc, f) { dict.fold(d, acc, fn(a, k, v) { f(a, (k, v)) }) } |
| 38 | +} |
| 39 | + |
| 40 | +fn sum(c: c) -> Elem<c> where Collection<c>, Num<Elem<c>>, Default<Elem<c>> { |
| 41 | + fold(c, default(), fn(a, x) { a + x }) |
| 42 | +} |
| 43 | + |
| 44 | +fn total(c: c) -> Int where Collection<c, Elem = Int> { |
| 45 | + fold(c, 0, fn(a, x) { a + x }) |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +- **Declaring.** A trait declares an associated type with `type Name`. A generic associated type takes its own parameters: `type Mapped<x>`. |
| 50 | +- **Defining.** Every impl defines each associated type of its trait exactly once: `type Elem = a`, or `type Mapped<x> = List<x>`. A missing definition is E0407, and one the trait does not declare is E0406; both codes now say "item" rather than "method". |
| 51 | +- **Projecting.** A projection is written like a type applied to the trait's arguments, then the associated type's own: `Elem<c>`, `Mapped<c, x>`. |
| 52 | + - It is always fully applied, so it is never a type constructor: `Functor<Mapped<c>>` is a kind error. |
| 53 | + - Its kind is `Type`. |
| 54 | + - The kinds of its own parameters are inferred with the trait's methods, as ADR 0018 infers trait parameters, defaulting to `Type`. |
| 55 | +- **Namespace.** An associated type is in its module's type namespace and is exported with its trait. Two traits of one module cannot both declare `Elem`, as two traits cannot both declare a method of one name (E0106). Elsewhere it is qualified like any type: `collection.Elem<c>`. |
| 56 | +- **Where-bindings** fix an associated type in a constraint: `where Collection<c, Elem = Int>`. A GAT binding quantifies its parameters: `Functorish<c, Mapped<x> = List<x>>` holds for every `x`. Those names may not shadow the signature's type variables. |
| 57 | + |
| 58 | +### Rules on declarations |
| 59 | +- **A definition's right side may use the impl's type variables and the associated type's own parameters, nothing else.** |
| 60 | +- **Termination.** A projection inside a definition's right side must have the impl's head variables as its trait arguments, and no projection among its own arguments. Impl heads are named types applied to distinct variables (ADR 0018), so each reduction step replaces a trait argument by a proper part of it, and reduction terminates. A reduction depth and size guard backs this up. Hitting the guard is a compiler bug, not a user error. |
| 61 | +- **Well-formedness.** A projection `Elem<T>` in a signature needs `Collection<T>`: either among the signature's constraints, or solvable because `T` is concrete. Otherwise it is E0402 ("add `where Collection<c>`"). Every projection that inference introduces also adds that constraint as a wanted, so the impl's own `where` clause is checked: `Elem<List<F>>` reduces only if the impl for `List` applies to `F`. |
| 62 | +- **Where a projection may not appear:** |
| 63 | + - in an impl's head; |
| 64 | + - in the result index of a GADT constructor, where it is not injective, so the arm could not learn anything from it. |
| 65 | + |
| 66 | + It may appear in type-definition fields: `Send` ([ADR 0004](0004-actor-model.md), Revision 6) reduces it, or requires `where Send<Elem<c>>`. |
| 67 | +- **Derived traits.** A trait with associated types cannot be `@derivable` (E0412). |
| 68 | +- **Determinedness** (E0403 at the declaration), extending ADR 0018's rule: |
| 69 | + - A type variable that occurs only inside projections' arguments is not determined, because projections are not injective. So `fn new() -> Elem<c> where Collection<c>` is rejected: no call could find `c`. |
| 70 | + - A variable on the right side of a binding is determined when the projection's arguments are. So `fn show_all(xs: c) -> String where Collection<c, Elem = e>, Show<e>` is accepted. |
| 71 | + - The same check runs on inferred schemes. |
| 72 | +- **Givens are oriented and checked** at the declaration. A binding `Elem<c> = T` rewrites `Elem<c>` to `T`. The following are errors: |
| 73 | + - a binding whose right side mentions its own left side, even through other bindings (`Collection<c, Elem = List<Elem<c>>>`); |
| 74 | + - two bindings of one projection that disagree; |
| 75 | + - a binding that disagrees with the impl when `c` is concrete. |
| 76 | + |
| 77 | +### Inference |
| 78 | +**Representation.** |
| 79 | +- A projection is a type, `Ty::Proj(assoc, args)`. |
| 80 | +- A scheme gains a list of equalities, `(projection, type)`, separate from its constraints, which are matched by position. |
| 81 | +- An impl records its definitions, over its own type variables then the associated type's parameters. |
| 82 | + |
| 83 | +**Reduction** has two levels. |
| 84 | +- *Global:* the impl whose head matches the projection's trait arguments; failing that, the signature's bindings. |
| 85 | +- *Local to a `match` arm:* the arm's GADT refinements, then the bindings stored by the matched constructor (ADR 0041). |
| 86 | + |
| 87 | +A variable is only ever bound to a type reduced globally. Inference already binds variables to a rigid "as written" for the same reason: what an arm knows must not leak out of it. When an occurs or escape check fails, the binding is retried with the type normalized globally, since `Elem<Wrap<h>>` may reduce to `Int`. |
| 88 | + |
| 89 | +**Unification with a projection** that does not reduce: |
| 90 | +- **The same projection** (same associated type, arguments equal after substitution) unifies. |
| 91 | +- **Over signature variables only** (no inference variable, even through the arm's refinements), the projection is an opaque type: it unifies with a variable, and with nothing else. |
| 92 | +- **Otherwise the equality is deferred.** It is kept with the `match` arm it arose in, and with the place to report it. |
| 93 | + |
| 94 | +**Deferred equalities** are retried when inference learns more: |
| 95 | +- **Retried only under their own arm.** One arm's refinement can contradict another's. If arm A knows `r = List<String>` and arm B knows `r = List<Int>`, then `Elem<r> ~ Int` from A must not succeed under B's assumptions. |
| 96 | +- **Drained when their arm ends,** before its refinements are retracted. |
| 97 | +- **Re-examined in a final pass** under each one's arm, rebuilt from the arm's recorded refinements, as the trait solver already rebuilds them (`traits::Local`). |
| 98 | +- **Unified with each other.** Two deferred equalities of the same projection under the same arm chain have their right sides unified, because a projection is a function of its arguments. |
| 99 | + |
| 100 | +**Generalizing an unannotated function:** |
| 101 | +1. Retry the deferred equalities to a fixpoint. |
| 102 | +2. Bind each variable left equal to a projection to that projection. |
| 103 | +3. Collect the free variables. |
| 104 | +4. Turn the remaining equalities over free variables into the scheme's equalities: `fn(a) -> Int where Collection<a, Elem = Int>`. |
| 105 | +5. Solve the trait constraints. |
| 106 | +6. Check determinedness. |
| 107 | + |
| 108 | +Anything still undecided is E0403 ("annotate"). That includes a GAT equality at a particular instance, which no binding can express, since bindings quantify. |
| 109 | + |
| 110 | +**At a call,** a scheme's equalities become equalities to unify, and its GAT bindings are unified with fresh scoped rigids standing for their parameters. A variable that captures one of those fails the escape check. This is sound because impl definitions are parametric in the associated type's own parameters. |
| 111 | + |
| 112 | +**In the body of a function with bindings,** they are given rewrite rules. |
| 113 | + |
| 114 | +**The trait solver** reduces projections before choosing an impl. In its shapes, a projection still containing inference variables is *unknown*, and one over signature variables only is *rigid*, so it needs a given. |
| 115 | + |
| 116 | +**After checking,** every type stored for later phases (expression types, capability sites, schemes) is fully normalized. Core lowering, exhaustiveness and `Send` see the reduced type wherever it reduces. What remains is a projection over a signature's variables, which they treat like the variable. |
| 117 | + |
| 118 | +### Printing |
| 119 | +The checker and the language server print a projection as `Elem<c>`, and equalities back inside their constraint: `Collection<a, Elem = Int>`. A printed signature is valid source: the language server inserts them. |
| 120 | + |
| 121 | +### The standard library |
| 122 | +`std/collection` (not the prelude) declares `pub trait Collection<c>` with: |
| 123 | +- `type Elem`; |
| 124 | +- the methods `size`, `fold`, `to_list` and `iter` (an `Iter<Elem<c>, e>`, [std/iter](../../std/iter.lse)); |
| 125 | +- impls for `List`, `Array`, `Dict` (`Elem = (k, v)`) and `Bytes` (`Elem = Int`); |
| 126 | +- the generic helpers `count`, `contains` (`where Eq<Elem<c>>`) and `sum` (`where Num<Elem<c>>, Default<Elem<c>>`: `Num` has no zero). |
| 127 | + |
| 128 | +The per-type modules keep their functions. [ADR 0026](0026-functors-and-monads-in-std.md)'s position, no Functor/Monad tower, is unchanged: `Collection` is about elements, not effects. |
| 129 | + |
| 130 | +## Consequences |
| 131 | +- **Inference is no longer "HM plus a separate solving pass".** Unification may defer equalities, and solving may unify. This is the cost ADR 0018 named. It is paid only by programs that use projections: |
| 132 | + - code without them never creates a deferred equality; |
| 133 | + - its generated C is unchanged; |
| 134 | + - its checking time changes only by the projection checks on every type walk. |
| 135 | +- **Arm-local reasoning gets a second consumer.** Deferred equalities follow the same arm discipline as the trait solver. A bug there is a soundness bug, hence the tests below and the review request. |
| 136 | +- **Before this ADR, Core lowering re-read stored types for three decisions** that inference had made from refined types: the field index, an HTML attribute's kind, and an HTML child's kind. Inside a GADT arm, the stored type is the unrefined rigid. Projections reduced only in an arm would make this more frequent. Issue #233's stack therefore records those decisions where inference makes them, before this feature lands. |
| 137 | +- **E0406/E0407 now speak of items. New codes, from E0413:** |
| 138 | + - an invalid definition's right side; |
| 139 | + - an invalid or cyclic where-binding; |
| 140 | + - a projection where none may appear. |
| 141 | +- **Tests:** |
| 142 | + - `tests/ui/assoc_types.lse` covers declaration errors, determinedness, cycles, and the cross-arm case above; |
| 143 | + - `tests/run/assoc_types.lse`, `tests/run/gats.lse` and `tests/run/collection.lse` run on both backends; |
| 144 | + - unit tests cover reduction and the termination guard; |
| 145 | + - the evidence tests cover impl choice through projections. |
| 146 | + |
| 147 | +## Alternatives considered |
| 148 | +- **Functional dependencies** (ADR 0018's other alternative). A first plan of this work used them. They improve inference with one extra solver step, and they need no normalization. But they cannot name a type in a signature (`fn sum(c: c) -> Elem<c>`), they cannot express GATs, and their consistency and coverage conditions sit awkwardly with ADR 0018's impl heads. The owner chose associated types. |
| 149 | +- **Flattening every projection into a fresh variable plus a wanted constraint (GHC's approach).** It is uniform, but the trait solver would have to unify and iterate on every program, including those without projections. Lazy reduction with deferred equalities costs nothing until a projection appears. |
| 150 | +- **Rust's `<T as Trait>::Elem` syntax.** It is unambiguous, but long in signatures, and Louise has no `Self`. `Elem<c>` reads like the rest of Louise's types. A clash between two traits' `Elem` is resolved by modules, as clashes between their methods are. |
| 151 | +- **Requiring no trait constraint for a projection,** as GHC's type families do. It is shorter, but the error then appears at a distant use instead of at the signature. |
| 152 | +- **Defaults for associated types, and associated consts.** They are left out. They can be added without changing the rules above. |