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

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.

How it runs: specialized at known types, dispatched otherwise

  1. Specialization (src/mono.rs). Take a call like dot(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.
  2. 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.
  3. 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

| 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