Traits (roadmap #19)
trait Describe:
fn describe(self) -> Str
impl Describe for Int:
fn describe(self) -> Str: "int " + str(self)
impl Describe for List[a] where a: Describe:
fn describe(self) -> Str: ... # may call describe(x) on elements
fn both(x, y): # inferred: (a, b) -> Str where a: Describe, b: Describe
describe(x) + " & " + describe(y)
What exists
- User traits. A trait declares methods that take
self. An impl can be for a built-in type (Int,Str,List[a], …) or a user type, including generic ones such asOption[a]. - An impl's own requirements are writtenwhere a: Describe. - If an impl leaves a method out, or only works for one particular type when it must work for any, the error says what is wrong and how to fix it. - Built-in traits replace the v0 workarounds.
Num,Add,OrdandSizedused to fall back toIntat the end of each function. They are now real requirements on type variables. The checker infers them and they become part of the inferred type: -insert : (Tree[a], a) -> Tree[a] where a: Ord-dot : (List[a], List[a], a) -> a where a: Num
The tree from #15 now works for Str and Float without changes. A requirement falls back to Int only when no signature mentions the type, as in Haskell. Otherwise the checker asks for an annotation.
- No annotations are needed. Requirements are inferred from use and shown in
trine check. - Trait methods are ordinary values:
let f = describeworks.
How it runs: specialized at known types, dispatched otherwise
- Specialization (
src/mono.rs). Take a call likedot(xs, ys, 0.0), where all the types are known. The callee gets its own copy,dot<List[Float], List[Float], Float, Float>: an ordinary function whose parameters are annotated with those types. - Type checking then gives the copy concrete types, so arithmetic is unboxed (#41) and trait calls inside it go straight to the right impl. - The step repeats while new copies appear. It is bounded at 6 rounds and 200 copies. - Dispatch. Code that is still generic calls a dispatcher, which picks the impl by the value's run-time type. Every Trine value carries its type tag, so the impl is always found, including for an empty list or
None. The checker has already proven that an impl exists for every use. - The interpreter runs the original, unspecialized program, and so does the VM's naive strategy. The differential fuzzer therefore checks specialization and dispatch against each other, in every case.
Evidence
- Golden program
examples/traits.tr. It produces identical output in the interpreter, all VM strategies and native code, with 0 leaked objects, with and without specialization. The testtraits_infer_requirements_and_specializechecks: - the inferred types; - that the specialized copies exist; - thatmainnever goes through a dispatcher. - Five trait error tests: a missing impl, a missing method, a missing
where, an impl that isn't general enough, and a type with no impl. - Fuzzer coverage. Every generated program carries traits with impls for a scalar, a data type, lists,
Optionand a user generic type. Dispatch is reached directly and through generic helpers. - 60,000 program cases ran clean (interpreter vs 5 VM strategies). - 1,500 native cases and 30,000 syntax mutations ran clean. - Speed. A generic
doton 2,000 Floats, called 3,000 times natively:
| version | time | |---|---:| | specialized | 8.5 ms | | hand-annotated List[Float] | 8.2 ms | | dispatched (TRINE_NO_SPECIALIZE=1) | 17.4 ms |
So generic code costs nothing once specialized. The benchmark suite shows no regressions.
Honest notes
- Polymorphic recursion isn't supported, even with annotations. Standard Hindley–Milner inference rejects it. This also means specialization can't loop forever, though it is bounded anyway.
- **Dispatch is only on
self.** Methods whose behaviour depends only on the return type, such asdefault() -> Self, are not possible yet. - The fuzzer is slower: about 195 cases per second, down from 400. The generated programs now carry a trait prelude, and specialization re-checks the program once per round. Compiling a program still takes milliseconds.
- Not done yet: user impls of the built-in operator traits (making
<or==work on your own types), default methods, and supertraits. Records (#16) are the natural place for==on user types.