Files
AILang/design/models/typeclasses.md
T
Brummel bcd41810f4 design/ + source rustdoc: replace opaque shorthand with content phrases + links
Reader-facing prose and rustdoc carried opaque shorthand like
"Decision 10", "clause-5", "mq.1", "ct.1", "eob.1", "rpe.1",
"post-mq.3", and "Iter 22b.1:" with no in-repo definition the reader
could follow. This commit replaces every such occurrence in the
durable tier the reader is most likely to land on (design/ ledger +
source //! module headers + the central /// public-item rustdoc) with
an inline content phrase plus, where applicable, a Markdown link to
the file that defines the referenced concept.

design/ ledger — 16 files:
  Definition-site headings demoted from "Decision N: <title>" to
  "<title>": authoring-surface, tail-calls, memory-model section in
  rc-uniqueness.md, dual-allocator section, typeclass design,
  effects "pure core + algebraic effects".
  Cross-reference sites: "Decision 1" -> canonical-schema principle
  (data-model); "Decision 3/4" -> effects + scope-boundaries; "Decision
  6" -> authoring-surface; "Decision 8" -> tail-calls; "Decision 9" ->
  rc-uniqueness (dual-allocator); "Decision 10" -> memory-model;
  "Decision 11" -> typeclasses (model). "clause-5" -> body-link
  durability gate. "clause-3" (in language-constraints) ->
  bug-class-reintroduction discriminator. "mq.1/2/3", "ct.1/4",
  "eob.1", "rpe.1" -> the canonical-form rule / the type-driven
  dispatch / the Str carve-out / etc. "post-mq.3" -> "type-driven".

design/contracts/feature-acceptance.md: file-local "clauses 1/2/3"
-> "criteria 1/2/3" (sprachliche Kohärenz mit der File-Überschrift
"Feature-acceptance criterion"); "the clause-3 mechanism" -> "the
bug-class-reintroduction discriminator".

Source //! module headers — 24 files:
  Stripped "Iter X.Y:" prefixes and "(Decision N)" / "(mq.X)" tags
  from spec_drift, uniqueness, reuse_shape, migrate_canonical_types,
  typeclass_22b{2,3,c}, suppress_filter, lift, mono, linearity,
  diagnostic, method_dispatch_pin, method_collision_pin,
  no_per_type_print_ops, mq3_multi_class_e2e, print_mono_body_shape,
  print_no_leak_pin, cli_diag_human_workspace_load_error,
  ct1_check_cli, prose snapshot, unbound_in_instance_method_pin,
  mono_xmod_ctor_pattern, desugar.

Central /// public-item rustdoc:
  ast.rs (full sweep — every "Iter X" + "Decision N" prefix
  reformulated; mode/Type::Fn rustdoc now points at memory-model.md;
  Constraint / SuperclassRef / InstanceDef / ClassDef rustdoc points
  at typeclasses contract).
  diagnostic.rs (all "(Iter X)" / "(mq.X)" tags on diagnostic codes
  removed).
  lib.rs (FORM_A_SPEC rustdoc points at authoring-surface.md
  instead of "Decision 6").
  canonical.rs (type_hash + Float-literal rustdoc).

Still outstanding (for a follow-up commit): ~500 inline `//`
code-body comments with `Iter X.Y` markers across the workspace, and
a handful of `///` rustdoc items in hash_pin / workspace_pin / lift /
mono / suppress_filter test-pin and internal-function bodies. Code
identifiers (test filenames like `mq3_multi_class_e2e.rs`, function
names like `iter18e_drop_iterative_default_preserves_hashes`) stay
verbatim per the user's "code identifiers stay verbatim" rule.

Tests: design_index_pin 5/5 + docs_honesty_pin 5/5; workspace builds
clean; full `cargo test --workspace` previously green (every
`test result: ok` line, no FAILED line).
2026-05-20 09:47:33 +02:00

8.2 KiB
Raw Blame History

Typeclasses — resolution and monomorphisation whitepaper

The schema-and-diagnostics contract for typeclasses lives in typeclasses; the call-site lookup rule in method dispatch; the built-in classes shipped in the prelude in prelude classes. This file covers the design choices and the resolution / monomorphisation algorithm.

The design — Haskell-lite, monomorphised, coherent

The design pass for typeclasses. Codified after the Feature-acceptance criterion was committed; the criterion is the explicit basis for the choices below.

AILang ships typeclasses to compress a real LLM-author redundancy: without them, every comparable function must be written per-type (int_eq, string_eq, bool_eq, int_show, string_show, …). With typeclasses behind a monomorphising compiler, the LLM author writes one signature with a class constraint and one method per concrete type, and the compiler emits the same machine code as the per-type version. No runtime cost, no dictionary passing, no vtables.

Choice. A deliberately narrow typeclass design — narrower than Haskell, narrower than Rust traits — calibrated to what an LLM author naturally produces. Five semantic axes are committed:

  1. Scope. Multi-method, single-parameter, optional defaults, single-superclass relation. No multi-param classes, no functional dependencies, no associated types.
  2. Constraints in signatures. Explicit and mandatory. A function that calls a class method must declare the constraint in its forall block. No constraint inference.
  3. Resolution. Orphan-free coherence. An instance C T may be declared only in the module of C or in the module of T. Resolution is global type-directed against a workspace-built registry; coherence makes the lookup unambiguous.
  4. Defaults. Opt-in via an explicit default keyword in the class body. Methods without default are abstract-required; methods with default may be overridden or inherited per instance.
  5. Class-parameter kind. Concrete types only (kind *). No higher-kinded class params; Functor/Monad-style abstractions over type constructors are not expressible. The LLM-natural pattern is List.map / Tree.map as separate functions per type, which monomorphisation handles directly.

The five axes follow from the Feature-acceptance criterion: each rejected mechanism (multi-param, higher-kinded, FunDeps, assoc types) is one an LLM author does not unprompted produce.

Resolution and monomorphisation

Constraint collection (per function body). During typechecking of a body, each method call generates a residual constraint of shape <Class> <Type> (the schema for these lives in Data model) where <Type> may still contain type variables. After local typechecking, residual constraints are checked against the function's declared constraints (modulo α-conversion and modulo auto-expansion through superclasses; see below). Any residual not covered by declared constraints fires MissingConstraint.

Instance registry (workspace-global). At workspace load (see crates/ailang-core/src/workspace.rs), all InstanceDef nodes across all reachable modules are collected into a registry keyed by (class-name, canonical-hash-of-instance-type). Registry build performs three checks:

  • Coherence. Each instance's module must be either the class's defining module or the instance type's defining module. Otherwise → OrphanInstance.
  • Uniqueness. No two entries share a key. Otherwise → DuplicateInstance.
  • Method completeness. Each instance specifies every required (non-default) method of its class. Otherwise → MissingMethod.

Registry build is a one-time-per-build pass that fires before any typechecking. Its errors are workspace-load errors, not per-call-site errors.

Resolution at call sites with concrete types. When the typechecker sees a method call where every type variable in the constraint is substituted to a concrete type, it queries the registry. Hit → resolved. Miss → NoInstance.

Resolution at polymorphic call sites. When type variables are still free, the constraint propagates into the surrounding function's constraint context — which the user MUST have declared explicitly (per axis 2). No constraint is implicitly hoisted.

Monomorphisation (post-typecheck, pre-codegen). A pass between typechecking and codegen replaces every call to a Type::Forall-quantified Def::Fn with a call to a synthesised monomorphic FnDef. Two source-body entry points share the same mechanics in one fixpoint:

  1. Class-method entry. For each unique (method, concrete-type) pair produced by a class-constraint residual, the pass looks up the resolved instance body via Registry::entries[(class, type-hash)], substitutes the class parameter to the concrete type, and synthesises a top-level FnDef named <method>__<type-surface-name>.
  2. Free-fn entry. For each call site to a polymorphic free Def::Fn with a fully-concrete substitution, the pass takes the source body directly from the polymorphic Def::Fn, applies rigid-var substitution on both the type AND the body (the body may contain inner Term::Lams whose param_tys reference the outer Forall vars), and synthesises a top-level FnDef named <name>__<type-surface-name-1>__<type-surface-name-2>__… (concatenated in Type::Forall.vars declaration order; the N-ary case extends the single-type-var class-method shape bit-stably).

Both arms share:

  • A fixpoint loop that keeps collecting targets until a round adds nothing new (a synthesised free-fn body may invoke class methods at concrete types, scheduling new class-method targets; a class-method body may invoke polymorphic free fns at concrete types, scheduling new free-fn targets).
  • A dedup cache keyed by (kind, base-name, type-hash-or-joined-hashes) where the first component ("class" / "free") guarantees disjoint keying across the two kinds.
  • A call-site rewrite walker that rewrites bare polymorphic call sites — class-method-named OR poly-free-fn-named — to their mono symbols before codegen runs. The walker advances a single cursor over interleaved class-method and free-fn slots emitted in synth's traversal order.

After this pass, the IR contains no polymorphism, no class machinery, no polymorphic call sites — only ordinary monomorphic functions and direct calls. Codegen sees no difference between a hand-written show_int and a synthesised show__Int.

Why mono, not virtual dispatch. Monomorphisation makes the call target visible to the optimiser, unlocking inlining and downstream loop transformations that virtual dispatch prevents in principle. On a saturating branch predictor with a monomorphic indirect target, the indirect call itself is comparable in cost to a non-inlined direct call — the win is in what the optimiser can do with the visible target, not in the call instruction. The end-to-end gain shrinks toward zero on larger callee bodies and cold call sites, but the architectural claim — "mono enables optimisations vdisp forbids" — holds across the spectrum (bench/mono_dispatch.py and the corresponding JOURNAL bench-notes entry record the measured ratios).

The separator is __ rather than # or @ because # and @ are invalid in LLVM IR global identifiers (the IR verifier rejects them inside @ail_<module>_<def> mangled names). __ is legal in both LLVM IR and the C ABI used by the runtime glue, and parses unambiguously into <method>__<type-surface-name> because neither component contains __ by project convention.

No runtime dispatch, no dictionary passing. The monomorphisation pass is the ONLY specialiser. Codegen sees only monomorphic Def::Fns and direct calls. A call that cannot be monomorphised — for instance, because a constraint remains unresolved at the entry point — is a static error, not a runtime one. This is the LLVM-friendly form and is consistent with the performance commitment of the RC + uniqueness memory model.