Generics on user types (roadmap #15)
type Tree[a] =
| Leaf
| Node(Tree[a], a, Tree[a])
fn parse_int(s: Str) -> Result[Int, Str]:
var n = 0
for c in chars(s):
n = n * 10 + digit(c)? # an Err returns from parse_int right here
Ok(n)
What exists
- **Type parameters on
typedefinitions.** Writingtype Tree[a] = ...declares the parameters. If a field uses a type variable that isn't declared, the error says how to declare it. Recursive generic types work, and so do generic types nested inside each other. - **
Option[a]andResult[a, e]come built in** as ordinary prelude definitions (Some/None,Ok/Err). If a program defines a type or constructor with one of those names, its own definition wins. - Inference stays annotation-free. For example: -
unwrap_or : (Option[a], a) -> a-map_option : (Option[a], (a) -> b) -> Option[b]-add_strings : (Str, Str) -> Result[Int, Str]
None of these needed annotations.
- **The
?operator.**e?unwrapsSome(v)orOk(v)tov. Otherwise it returns theNoneorErr(x)from the enclosing function or lambda. - The checker enforces that the enclosing function returns an Option, or a Result with the same error type. The error type must match because the success type may differ, but the error must flow through unchanged. - When neither the operand nor the return type is known yet, the decision waits until they are. If it is still ambiguous, the checker asks for an annotation. - At run time, the value that fails is returned as it is.NoneandErr(x)are represented the same way whatever the success type is, so no conversion code is needed. - Hashing. Type parameter names count as local names, like variable names:
type Pair[k, v] = P(k, v)hashes the same astype Pair[a, b] = P(a, b). Swapping the field types gives a different hash. Prelude types are hashed but not listed or stored.
Bugs and improvements found along the way
- **
returninside a lambda left the enclosing function** in the interpreter, while the IR engines (correctly) left the lambda. The checker also typed it against the enclosing function.?made this easy to hit. All engines now agree, and there is a regression test. The fuzzer never generatedreturninside a lambda, which is why it missed this. - Drop-reuse now handles Koka's classic tree insert. It used to give up when the rebuild happened in both branches of an
if. Now one reuse token serves both branches, since exactly one of them runs. Ingenerics.tr, building a 2,000-node tree now updates nodes in place: 37,654 nodes are reused and allocations fall from 39,889 to 2,235.
Evidence
- New golden program
examples/generics.tr. It produces identical output in the interpreter, all 4 VM strategies and native code, with 0 leaked objects. With the full pipeline, 100% of refcount overhead is removed. - Error tests: -
?with the wrong enclosing return type; -?on a non-Option value; - mismatched error types; - an undeclared type variable; - the wrong number of type arguments; -Box[Int]mixed withBox[Str]. - Fuzzer coverage. The differential fuzzer now generates
Option[Int],Result[Int, Int]and a user genericG[List[Int]], plus calls to polymorphic helpers. About 12% of generated programs use?, inside functions that return Option or Result. - 100,000 program cases (6 engines each) ran clean. - 1,500 native cases and 20,000 syntax mutations ran clean.
Honest notes
- Monomorphization is not needed yet, so it isn't done. Without traits, a generic function can't compute on its type parameters. It can only move them around, and moving a boxed value is cheap. Code that pulls a concrete value out of an Option is already typed concretely at that point, so it still uses unboxed
Int/Float. Monomorphization becomes worthwhile with traits (#19). - **The real cost is allocating the
Somecell.** In a worst-case microbenchmark, 5M calls each returnOption[Int]from a 4-element search, and the cost is 52 ms against 30 ms with a sentinel-1. On a realistic 64-element search the difference disappears (26 ms against 29 ms). The fix is a representation change, not monomorphization: small enums such asOption[Int]should be returned in registers (new roadmap item #42). - Ord and Num still fall back to Int (this is #19's job). Inferring
insertfrom the example with no annotations gives(Tree[Int], Int) -> Tree[Int], because<falls back to Int, so aTree[Str]can't use the sameinsertyet. This is the main argument for doing #19 next.