tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

164 lignes · 15936 octetsBrut · Historique

ADR 0018: Multi-parameter traits and higher-kinded types

Status: Accepted by the project owner on 2026-10-12; proposed 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44). Revision 1 (2026-10-12, tuple heads) is Proposed and also needs that review. It extends ADR 0007, which deferred both features.

Context

ADR 0007 made traits single-parameter, with Haskell 98-shaped impls, and noted that more could be added later without breaking code. Two common needs fall outside it:

  • Relations between types: Convert<a, b> (conversions), Store<c, k> (a collection and its keys), heterogeneous operators.
  • Abstraction over type constructors: Functor<f> for List, Option and Result<e>.

The checker must stay predictable, terminate, and keep coherence (one impl per instance, no orphans).

Decision

Multi-parameter traits

  • A trait has one or more distinct type parameters: trait Convert<a, b> { fn convert(x: a) -> b }. A constraint names one type per parameter: where Convert<a, String>.
  • Impls keep the Haskell 98 shape, per argument: impl Convert<List<a>, List<b>> where Convert<a, b>.
    • Every trait argument is a named type applied to type variables (E0409).
    • No variable appears twice in the whole head, so impl Convert<Option<a>, List<a>> and impl Convert<a, Int> are rejected.
    • The named type at the head of each argument is the impl's head: [List, List] above.
  • Overlap: two impls of a trait overlap exactly when their heads are equal, because their argument patterns then always unify. The duplicate check (E0404) is therefore the overlap check.
  • Solving Trait<T1, ..., Tn> extends ADR 0007's steps:
    1. A given that matches exactly.
    2. If every Ti has a named type at its head, the impl with those heads, whose own constraints are solved recursively. Matching is one-way: impl variables are distinct, so no unification is needed, and chains still shrink the types and terminate.
    3. If some Ti is still an inference variable, the constraint is stuck. If all its variables are generalized, it becomes a constraint of the inferred scheme (fn convert_each(xs) { list.map(xs, convert) } has type fn(List<a>) -> List<b> where Convert<a, b>). Otherwise it is ambiguous (E0403).
    4. If some Ti is a signature's type variable and no given matches, the signature lacks a where (E0402).

Ambiguity: every parameter is determined at use sites

There are no functional dependencies and no associated types. A call chooses an impl only from types already known from its arguments, its expected result, or annotations.

fn known :: -> Int {
  convert True
} // Convert<Bool, Int>
fn unknown :: -> String {
  show (convert True)
} // E0403: `Convert<Bool, _>` has unknown types
  • Why: this is the simplest sound rule. It needs no improvement step in the solver: a constraint never changes a type, so inference stays HM plus a separate solving pass, and error messages stay local.
  • The cost: some annotations that functional dependencies would infer. Given the evidence from use, they can be added later without breaking code: a dependency only makes more programs check.

Declarations are checked too, so that the error appears where the problem is, not at every call:

  • every type variable of a signature's where clause must appear in its type. In fn through(x: a) -> c where Convert<a, b>, Convert<b, c>, nothing can determine b (E0403);
  • every trait method must mention every parameter of its trait. trait Collection<c, e> { fn empty() -> c } is rejected (E0403), since a call to empty could never determine e.

Coherence: the orphan rule, generalized

An impl must live in the module of its trait or in the module of one of its head types (E0405). For one parameter, this is ADR 0007's rule.

Why this is enough for global uniqueness:

  • An impl's module names its trait and all its head types.
  • Imports are acyclic (E0105). If two different modules each defined the same impl, each would have to be the home of one of the impl's items and name the other's. So each would import the other, which is a cycle.
  • Only one module can therefore hold a given impl, and the whole-program duplicate check (E0404) catches two in the same module.

Unlike Rust's rule (RFC 2451), no ordering condition on the arguments is needed, because impl arguments are never bare type variables.

Dictionaries

Nothing changes after type checking: a constraint still has one piece of evidence, and an impl is still one dictionary. Multi-parameter dictionaries work in both backends unchanged:

  • the trait's own constraint comes first in each method's scheme;
  • Core lowering, the interpreter, Perceus and the C backend are untouched, except for the impl names shown in Core (dict Convert<List, List>).

Higher-kinded type parameters

A type parameter may stand for a type constructor:

trait Functor<f> {
  fn map :: x: f<a> g: fn(a) -> b / <e> -> f<b> / <e>
}

impl Functor<List> {
  fn map :: xs g {
    list.map xs g
  }
}

fn double_all :: x: f<Int> -> f<Int> where Functor<f> {
  map x fn n { n * 2 }
}

Kinds. The checker gives every type a kind:

  • Int and List<Int> have kind Type;
  • List and Result<a> have kind Type -> Type;
  • Result has kind Type -> Type -> Type;
  • effect rows have their own kind, Row, so a variable cannot be both a row and a type.

The kinds of type parameters are inferred, never written:

  • Type definitions and traits: from their constructors, alias bodies and method signatures, all together, since they may refer to each other. Unknown kinds then default to Type. So type Twice<f, a> { Twice(f<a>, f<a>) } gives f the kind Type -> Type, and trait Functor<f> does the same through map.
  • Signatures and impls: each from its own type syntax and where clause, using the kinds of the definitions it names.

A type of the wrong kind is an error (E0213). A constructor missing arguments where a Type is expected is E0201, as before.

First-order only:

  • A type variable is applied to types only: f<a> requires a : Type. So every variable's kind is Type -> ... -> Type, and t<List> is rejected.

  • There are no type lambdas: a constructor is partially applied only in the order of its parameters.

  • Unification of an application f<a1..an> with a named type T<t1..tm> (m >= n):

    • it binds f to T<t1..t(m-n)> and unifies the last n arguments pairwise;
    • against another application, the one with fewer arguments is matched against the other's last arguments;
    • it fails if one of T's last n parameters is not of kind Type, because f takes only types;
    • function types and tuples are not named types, so f<a> never matches them.

    Without type lambdas the solution is unique, so inference stays principal: fn twice_map(x, g) { map(map(x, g), g) } gets fn(a<b>, fn(b) -> b / <e>) -> a<b> / <e> where Functor<a>.

  • Representation: an application whose head is a variable is Ty::App(head, args). Once the head is known to be a named type, it becomes an ordinary Con with the arguments appended (in shallow, zonk and substitution). Phases after type checking never see App.

Consequence for Result. The prelude declares Result<a, e> with the value type first. So Result<a> fixes the value type, and impl Functor<Result<a>> maps over errors (see tests/run/hkt.lse). Mapping over values would need a type lambda, or Haskell's order (Either e a). Changing the prelude's order would break every Result annotation; the engineering team should decide whether that is worth it before v1 freezes the standard library.

Impls of higher-kinded traits keep the shape above. Each argument is a named type applied to distinct variables, now possibly fewer than its parameters (impl Functor<Result<a>>), and its kind must be the trait parameter's. A derived impl requires the trait only of the parameters of kind Type.

Effects are unchanged. map's effect polymorphism is ordinary row polymorphism on the method's signature:

  • The row variable e belongs to map's scheme, like a and b. Each call instantiates it to the effects of the function passed: map(names, fn(s) { io.println(s); s }) performs io.
  • Each impl's map is checked against that signature. It may call g, and so perform e, but nothing else.
  • Each trait method declares its own row. A method should write / <e> as above if it accepts effectful callbacks. A method declared without a row is total, and so are the callbacks it accepts. This is the rule for any declared function type (ADR 0008). Kinds do not interact with rows.
  • Not expressible: an effect row as a trait's parameter, such as a monad whose type carries its effects. Rows have kind Row, and traits take only types and type constructors.

Consequences

  • Constraint holds a list of types and ImplInfo a list of heads. The language server prints constraints and impls with all their arguments.
  • Programs that checked before still check, with one exception: a signature whose where clause has a variable that appears nowhere else is now rejected at the declaration (E0403). Such a function could never be called without an ambiguity error.
  • TypeRef::Var keeps its type arguments (f<a>); before, the HIR dropped them silently.
  • Kind inference adds one pass over type definitions and trait methods before schemes are declared. Error messages about kinds show Type -> Type, never * -> *.
  • Tests:
    • tests/run/multitraits.lse and tests/run/hkt.lse run on both backends. hkt.lse covers Functor and a Monad-like trait over List, Option and Result<a>, a type with a higher-kinded parameter, an inferred higher-kinded scheme, and an effectful map;
    • tests/ui/multitraits.lse covers ambiguity, overlap, shape, arity, missing givens and orphans; tests/ui/kinds.lse covers kind errors and inferred higher-kinded schemes;
    • crates/louise_types/tests/coherence.rs checks the orphan rule across modules;
    • evidence.rs checks the impl tree chosen by both arguments.

Alternatives considered

  • Functional dependencies (trait Convert<a, b> | a -> b). They improve inference, but need an improvement step in the solver and a consistency check between impls. The engineering team should decide whether they are worth it after use.
  • Associated types. They are more expressive and are what Rust chose, but they add type-level functions, and therefore normalization, to unification.
  • Flexible impl heads (repeated variables, bare-variable arguments such as impl Into<a, Option<a>>). Overlap would need unification of impl heads, and matching would interact with unknown types. They can be added later if needed.
  • Rust's orphan rule with uncovered type parameters. It is unnecessary here, since arguments are never bare variables.
  • Type lambdas, or partial application in any order (Result<_, e>). Unification of f<a> with Result<Int, String> would then have two solutions, so inference would no longer be principal (higher-order unification).
  • Written kind annotations (trait Functor<f: Type -> Type>). Inference finds every kind that first-order use allows, so annotations would only add syntax. They can be added if error messages need them.
  • Kind polymorphism. A parameter its own definition does not use gets one kind: from the definitions that use it, or Type. Using it at two kinds is an error. That is rare, and Haskell 98 has no kind polymorphism either.
  • Higher-rank or higher-order kinds for variables (t<List>, a variable of kind (Type -> Type) -> Type). They are not needed for Functor or Monad. Restricting variables to Type -> ... -> Type is what lets unification check kinds with a table of which parameters are higher-kinded, instead of tracking a kind for every inference variable.

Revision 1 — 2026-10-12: tuples as impl heads (Proposed, issue #106)

Context. () and tuples had no Eq, Ord, Show, Debug or Hash, because an impl argument had to be a named type. So assert_equal could not compare Ok(()) or a list of header pairs, and programs turned values into text first (the demo did).

Decision.

  • An impl argument may also be a tuple of distinct type variables: impl Eq<(a, b)> where Eq<a>, Eq<b>, and impl Eq<()>. Its head is the tuple's arity, shown (_, _). Elements must be variables of kind Type: impl Eq<(a, a)> and impl Eq<(a, Int)> are rejected (E0409). A tuple is a type, so a trait parameter of a higher kind rejects it (E0213).
  • Matching, overlap and solving are unchanged in kind. A tuple pattern matches a tuple of the same length one way, binding its variables. Two impls overlap exactly when their heads are equal, so arity is part of the head. A constraint on a tuple type is solved like one on a named type.
  • Coherence: a tuple has no module. Its home can only be the trait's module, or that of another named head. An impl whose heads are all tuples therefore lives with its trait (E0405), and the uniqueness argument above holds as written: every home is named by the impl.
  • The prelude implements Eq, Ord, Show, Debug, Hash and Default for () and tuples of 2 to 12 elements. These are generated by scripts/gen-tuple-impls.py; CI checks the block is current.
    • Tuples compare element by element (Ord is lexicographic, through <> on Order).
    • They show as (1, a) and debug as (1, "a").
    • Hashing folds hash_combine from 0, as derived impls do.
    • Twelve matches Rust. A thirteen-element tuple has no impls; the cap can be raised by changing one constant.
  • No tag switches in the impls. They use .0, .1..., because the interpreter cannot switch on a tuple's tag.

Consequences.

  • @derive now accepts fields of tuple type, and assert_equal works on Result<(), e> and List<(String, String)>.
  • The cost is about 7 ms more per compile. The 66 impls add to every program's front end: on hello, parse, resolve and typecheck take about 3 ms more, and lowering, specialisation and Perceus about 4 ms more, because those passes still process every function (#114 would remove that part). louise check of std_tour goes from about 14 to 18 ms. Linking still dominates a build.
  • Tests: tests/run/tuple_traits.lse on both backends; tests/ui/multitraits.lse covers shape, overlap and the orphan rule for tuple heads; tests/ui/kinds.lse covers the kind error.

Alternatives considered.

  • Impls built into the solver, with no prelude text. They are invisible to readers and to the language server, and they need a new kind of evidence in the solver, in lowering and in both backends.
  • Derive-style generation by the compiler. It needs the same head change, plus a tuple path through both derive passes, since derived code switches on tags.

Note — 2026-10-15: associated types (issue #234)

Status: Proposed; needs engineering review (#44).

ADR 0047 adds associated types, which this ADR left out. Its rules for impl heads, overlap and coherence are unchanged: an impl's definitions of associated types ride on the impl, so there is still exactly one per trait and head types. Two statements above change:

  • "A call chooses an impl only from types already known from its arguments, its expected result, or annotations" still holds for choosing impls. But a type in a signature may now be computed from another: Elem<c> is known once c is.
  • "Every trait method must mention every parameter of its trait" now counts a parameter as mentioned only outside projections' arguments, since Elem<c> alone does not determine c.