Axle v0.22.0

Generics and traits

Generics let one declaration work over many types; a trait is the contract that says which types it may work over. Together they give you reusable, statically checked code with no boxing on the fast path.

This page covers:

  • the vocabulary — what a trait is, static vs dynamic dispatch, what monomorphisation means;
  • generic classes and the bounds on their type parameter, with the three ways to satisfy one;
  • the match type T compile-time type switch;
  • impl blocks, which equip a primitive, string, struct or enum with the trait;
  • @derive(...), which synthesises the standard boilerplate.

For trait declaration basics and dynamic dispatch see Object-oriented programming.

Concepts first — the vocabulary

If generics and traits are new to you, three ideas underpin everything below. This section explains them in plain terms; the syntax follows.

A trait is a capability contract

A trait names a set of methods a type promises to provide — a capability, not a data layout. trait Drawable { fn draw(self) : void; } says “anything Drawable can be drawn” and nothing about its fields. It is Axle’s equivalent of a Kotlin/Java interface, a Rust trait, or a TypeScript interface. A class bundles data (fields) with behaviour; a trait bundles behaviour only, and a class satisfies it by providing the methods.

ClassTrait
Carries fields (data)YesNo
Carries method bodiesYesOnly optional defaults
Can be instantiated (new)YesNo
Reads asis a thingcan do a thing

Trait declaration, default bodies, and dyn Trait live in the OOP recipe; this page uses traits as bounds on generics.

Static vs dynamic dispatch — and the vtable

Dispatch is the act of picking which method body a call runs. There are two ways:

  • Static dispatch — the compiler knows the concrete type at the call site and wires in the one body directly. Zero runtime overhead. A call on a class-typed receiver (point.draw()) dispatches statically.
  • Dynamic dispatch — the concrete type is known only at runtime, so the call reads a runtime type tag on the value and looks the body up in a table. A call on a trait-typed receiver (fn render(d : Drawable) calling d.draw()) dispatches dynamically — d may be any implementer.

The lookup table is the vtable (virtual method table): one row per concrete type, one column per trait method, each cell a function to call. Axle builds it at compile time and selects the row by the value’s runtime tag (__type_id) — the receiver stays a plain object pointer, no fat pointer:

trait Drawable { draw; area }         vtable rows (trait Drawable):

                          column:   draw          area
        Circle  ───────►  row:      Circle.draw   Circle.area
        Square  ───────►  row:      Square.draw   Square.area
                          ▲
    value's __type_id ────┘   picks the row; the method's position picks the column
Static dispatchDynamic dispatch
Concrete type known atCompile timeRuntime
CostNone (direct call)One tag read + one indexed load
Triggered byClass-typed receiverTrait-typed / dyn Trait receiver
Rust analogueGeneric / impl Traitdyn Trait

Monomorphisation — one compiled copy per type argument

A generic class or function is a template written once over a type parameter T. Monomorphisation is the strategy of stamping out a separate concrete copy for each distinct type argument actually used: Box<i32> and Box<string> compile to two independent bodies, each with T replaced by the real type.

class Box<T>  (one template)
      │
      ├── Box<i32>     → body with T = i32      (compiled)
      ├── Box<string>  → body with T = string   (compiled)
      └── Box<Point>   → body with T = Point    (compiled)

This is the opposite of type erasure (Java/Kotlin generics, where Box<Integer> and Box<String> share one Box<Object> body and the element type is forgotten at runtime). Axle monomorphises exactly like Rust and C++ templates: each instantiation is fully typed, its calls dispatch statically, and primitives are never boxed. The cost is code size (more copies); the benefit is zero abstraction overhead. TypeScript sits at neither extreme — its generics are erased and gone at runtime; Axle keeps and specialises them.

Note — generic free functions infer their type arguments, or take them explicitly. A free function may be generic — fn id<T>(v : T) : T — and the type argument is inferred from the call (id(42) instantiates T = i32). When a type parameter can’t be inferred — it appears only in the return type or only in the body (fn make<T>() : T, fn pick<T>() { match type T { … } }) — pass it explicitly with a turbofish call: make<i32>(). Inference with no usable position and no turbofish is refused with E0603; a turbofish on a non-generic function is E0608. Each distinct instantiation is monomorphised, exactly like a generic class.

Generic classes

A class may take one or more type parameters in <…>. Fields, the constructor, and methods use them directly, and each distinct instantiation is compiled on demand:

class Box<T> {
    value : T;
    constructor(value : T) {
        self.value = value;
    }
    pub fn get(self) : T {
        return self.value;
    }
}

fn main() : i32 {
    let intBox : Box<i32>    = new Box<i32>(42);
    let strBox : Box<string> = new Box<string>("hi");
    return intBox.get();                 // 42
}

Several type parameters are monomorphised independently:

class Pair<K, V> {
    key   : K;
    value : V;
    constructor(k : K, v : V) {
        self.key = k;
        self.value = v;
    }
    pub fn getKey(self)   : K {
        return self.key;
    }
    pub fn getValue(self) : V {
        return self.value;
    }
}

fn main() : i32 {
    let p : Pair<i32, i64> = new Pair<i32, i64>(7, 100);
    return p.getKey();
}

A generic class holding another

A generic class may name another generic class on its own type parameter. The instantiation follows the argument: Box<i32> holds a Wrapper<i32>, and Box<string> a Wrapper<string>, each allocated, read and torn down like any other instance. The class it names must be declared above it, as for any generic class a body uses:

class Wrapper<T> {
    value : T;
    constructor(value : T) {
        self.value = value;
    }
    pub fn get(self) : T {
        return self.value;
    }
}

class Box<T> {
    inner : Wrapper<T>;
    constructor(value : T) {
        self.inner = new Wrapper<T>(value);
    }
    pub fn get(self) : T {
        return self.inner.get();
    }
}

fn main() : i32 {
    let b : Box<i32> = new Box<i32>(7);
    return b.get();                      // 7
}

Generic bounds — <T : A + B>

A type parameter may carry one or more bounds: constraints that any type argument must satisfy before the class can be instantiated. Bounds are written after a :, with + separating several. A bound is an acceptance gate checked at the instantiation site:

trait Marker {
    fn mark(self) : i32;

    impl i32 : Marker {
        mark => markI32(self),   // i32 satisfies Marker through this block
    }
}

// The arm calls an ordinary function, passing the receiver value first.
fn markI32(x : i32) : i32 {
    return 1;
}

class Tagged<K : Marker> {
    v : K;
    constructor(v : K) {
        self.v = v;
    }
}

fn main() : i32 {
    let ok : Tagged<i32> = new Tagged<i32>(7);   // accepted: i32 is Marker
    return 0;
}

new Tagged<f64>(…) is rejected with E0601 — f64 does not satisfy Marker. The diagnostic points at the instantiation and names the missing bound.

Three ways to satisfy a bound

A type argument satisfies a bound by any of three paths; the compiler accepts the first match:

  1. Explicit : TraitName in the class header — the class declares the trait.
  2. impl block inside the trait — a primitive, string, struct or enum equipped there satisfies the trait without a : Trait clause (how i32 satisfies Marker above).
  3. Structural conformance — the class already has every method the trait declares, even without naming the trait. The compiler checks the signatures and accepts the match, and builds a real dispatch table for the class at the instantiation site, so a call through the type parameter dispatches correctly. The one exception is a method the class gets only from a trait default: a structurally conforming class that relies on a default without declaring the trait is refused with E0606. Declare the trait in the class header (: Trait) to take the default.

A bound also makes the trait’s methods callable through the type parameter: inside the class body item.mark() (where item : K and K : Marker) resolves against Marker’s contract and, at each instantiation, dispatches to the type argument’s own method — a class argument dispatches dynamically off its RTTI header, and a primitive argument dispatches to its impl-block body. A block may answer any number of contract methods; a class is not a block target (it carries its own : clause), and a generic trait is refused until a bound binds its arguments.

Monomorphisation

Axle generics are fully monomorphised: each distinct type-argument list produces its own compiled version of the class or function. The instantiation cache is keyed on the identity of the concrete argument list, so Box<Point> and Box<Task> are two instances with two bodies — they never share code.

Stdlib generic classes (HashMap<K, V>, ArrayList<T>, HashSet<T>) work the same way: their method bodies travel in the stdlib metadata and are instantiated locally in your compilation, so any type argument works without a fixed precompiled matrix — subject to the element rule in Limits.

FFI dimensions

A stdlib generic’s mangled symbol is spelled from a coarser tag than the argument list — its FFI dimension. This is an ABI detail, not a source rule: it lets two arguments that cross the boundary identically share a symbol name. There are six tags:

DimensionCovers
i32i8 / i16 / i32 / bool / char
u32u8 / u16 / u32
u64u64
i64i64, and every class argument — a handle or a heap pointer is 64-bit at the ABI level
f64f32 / f64
stringstring

Unsigned widths keep a tag of their own rather than sharing the signed slot of the same width: the dimension is part of the mangled name, so collapsing u32 onto i32 would compile ArrayList<u32> to read its elements as signed — it would sort four billion below one.

Storing a class-typed T in a field takes an own constructor parameter to move ownership into the field; the instance’s synthesised destructor then frees that concrete field exactly once at scope exit.

match type T — compile-time type switch

match type T { Pattern => arm, … } (a bare type, no angle brackets) selects a value by the static identity of a type, resolved entirely at compile time. It is the type-level counterpart of a value match, and is written inside a generic body — a class method or a free function — switching on a type parameter in scope. The arm arrow is =>.

class Tag<T> {
    v : T;
    constructor(v : T) {
        self.v = v;
    }

    pub fn name(self) : string {
        return match type T {
            i32    => "integer",
            f64    => "float",
            string => "text",
            _      => "other",
        };
    }
}

fn main() : i32 {
    let a : Tag<i32> = new Tag<i32>(5);
    let b : Tag<f64> = new Tag<f64>(2.0);
    println(a.name());          // "integer"
    println(b.name());          // "float"
    return 0;
}

Rules:

  • Concrete scrutinee — when T is known at the instantiation, the compiler folds the match to the matching arm; no runtime code is emitted (exact type first, then _).
  • Abstract scrutinee — in the un-instantiated template the switch is carried as an HIR node and resolved per instantiation.
  • An arm body may be unsupported "message" to produce a deliberate compile-time error for an unsupported type. Selecting such an arm is E0602.
  • A match type with no matching arm and no _ wildcard is a compile error (non-exhaustive).

An unsupported "msg" arm turns an unwanted type argument into a compile-time error at the instantiation that selects it:

class Width<T> {
    constructor() {}
    pub fn bytes(self) : i32 {
        return match type T {
            i32 => 4,
            i64 => 8,
            f64 => 8,
            _   => unsupported "Width: unsupported element type",
        };
    }
}

impl blocks — equipping a type with a trait

An impl Type : Trait { method => body } block, written inside the trait, lets a type carry the trait’s methods without a : Trait clause. It is how a primitive, a string, a struct or an enum satisfies a trait the trait’s own crate declares. Each arm names the contract method it answers, so a trait may declare any number of methods:

trait Doubler {
    fn double(self) : i32;
    fn triple(self) : i32;

    impl i32 : Doubler {
        double => self * 2,        // `self` is the receiver value
        triple => self * 3,
    }
}

fn main() : i32 {
    let x : i32 = 21;
    return x.double();             // 42
}

The header names the type and the trait. Inside the trait the trait name is repeated on purpose: it is the place a generic application will carry its arguments (impl i32 : Source<i32>), and it keeps the block readable when quoted outside the declaration. A class is not a target — it carries its own : Trait clause (E0784) — and a generic trait is refused for now (E0780).

A method with a default may be omitted; the default runs for that type. An arm body is an expression, a { block }, or unsupported "msg" (the target satisfies a bound, but a call to the method, direct or through the bound, is E0015). Delegation is an ordinary call: double => twice(self).

See OOP → impl blocks for the arm forms and the box path into a trait slot.

Conditional methods — when T : Bound

A when block gates a group of methods on a generic so they exist on an instantiation only when the bound holds, letting a generic class expose richer behaviour for capable type arguments without making the bound mandatory for every use. The gated methods are materialised onto each satisfying instantiation during monomorphisation; on a non-satisfying one the method is absent (a call is E0015).

trait Printable {
    fn print(self) : void;
}

class Label : Printable {
    text : string;
    constructor(t : string) {
        self.text = t;
    }
    pub fn print(self) : void {
        println(self.text);
    }
}

class Wrapper<T> {
    value : T;
    constructor(own v : T) {                 // `own` — a class-typed T moves into the field
        self.value = v;
    }

    pub fn get(self) : T {
        return self.value;
    }

    when T : Printable {
        // present only on an instantiation whose T satisfies Printable
        pub fn tag(self) : i32 {
            return 1;
        }
    }
}

fn main() : i32 {
    let w : Wrapper<Label> = new Wrapper<Label>(new Label("hi"));
    return w.tag();                          // 1 — Label is Printable, so tag() exists
}

On a non-satisfying instantiation the method is absent — new Wrapper<i32>(5).tag() is refused with E0015 (i32 is not Printable, so Wrapper<i32> never grows a tag method).

@derive(...) — synthesised boilerplate

@derive(Trait, …) on a class asks the compiler to synthesise the standard implementation of each listed trait. The expansion is field-by-field and happens at parse time, so the methods stay correct as the class evolves:

@derive(Eq, Ord, Hashable, ToString)
class Point {
    x : i32;
    y : i32;
    constructor(x : i32, y : i32) {
        self.x = x;
        self.y = y;
    }
}

fn main() : i32 {
    let a : Point = new Point(1, 2);
    let b : Point = new Point(1, 2);
    let c : Point = new Point(3, 4);

    if (a.equals(b)) {
        println("equal");
    }
    if (a.compareTo(c) < 0) {
        println("a < c");
    }
    println(a.toString());
    return 0;
}

Derivable traits:

TraitSynthesisesBehaviour
Eqequals(other : Class) : boolField-by-field ==, ANDed; true for a field-less class
OrdcompareTo(other : Class) : i32Lexicographic on fields; negative / zero / positive
HashablehashCode() : i64Field-by-field polynomial hash combination
ToStringtoString() : stringField-by-field string concatenation
Cloneclone() : ClassField-by-field copy through the constructor

clone() has a reader besides you. copy of a struct that holds an object duplicates that object by calling its class’s clone() — the derived one or one you wrote — so a class with @derive(Clone) can sit in a struct that is copied. See Structs: copy and own.

@derive applies to a concrete class only. The parser refuses it on an exception — an exception implements no trait — and on a generic class, whose synthesised members would have to carry the class’s own type arguments. On a struct or an enum sema rejects it with E0012, the same error an annotation on the wrong site earns anywhere else.

Three more parse errors surround it: a name that is not a derivable trait, a non-identifier argument (@derive("Eq")), and a collision with a hand-written method the trait would have synthesised — equals for Eq, compareTo for Ord, hashCode for Hashable, toString for ToString, clone for Clone.

Generic traits — class C : Iterator<i32>

A trait takes type parameters the way a class does, and a class that lists it states what they are. trait Iterator<T> declares fn next(self) : T; class Counter : Iterator<i32> makes that fn next(self) : i32.

The compiler checks the class’s next against the contract with T replaced by the i32 you wrote:

  • the wrong return type is refused (E0029);
  • the wrong number of arguments is refused (E0001), and so is none at all (: Iterator).
use std::collections::Iterator;

class Counter : Iterator<i32> {
    cursor : i32;
    stop   : i32;

    constructor(lo : i32, hi : i32) {
        self.cursor = lo;
        self.stop = hi;
    }

    pub fn hasNext(self) : bool {
        return self.cursor < self.stop;
    }

    pub fn next(mut self) : i32 {
        let v : i32 = self.cursor;
        self.cursor = v + 1;
        return v;
    }
}

fn main() : i32 {
    let mut total : i32 = 0;
    for (x of new Counter(0, 4)) {
        total = total + x;
    }
    return total;                        // 6
}

Iterating your own types

for (x of it) works over any class that declares an iteration protocol, and the stdlib’s Iterator<T> and Iterable<T> are those protocols written as traits:

ProtocolMethodsfor (x of it) is
Iterator<T>hasNext() : bool and next() : Twhile (it.hasNext()) { let x = it.next(); … }
Iterable<T>nextSlot(start : i64) : i64 and elementAt(slot : i64) : Tsearch a slot from the cursor, stop on a negative one, read it with elementAt

Counter above is iterable, and x is an i32 because that is what next returns:

// doc-check: skip — an excerpt continuing the `Counter` block above, which compiles the same loop
let mut c : Counter = new Counter(0, 4);
for (x of c) { println(x.toString()); }      // 0 1 2 3

The loop is the while written out:

  • the iterable advances in place: a break leaves it where it stopped and a second loop resumes there;
  • return, continue and nested loops behave as in any loop;
  • a tuple element takes a name list: for ([a, b] of pairs) is let (a, b) = pairs.next();;
  • an iterable that is a call (for (x of makeCounter())) is evaluated once and released when the loop ends.

Listing : Iterator<T> or : Iterable<T> is optional. The loop recognises the methods and their shapes; writing the clause has the compiler check them against the contract.

Iterable is the form for elements that live in storage with holes (a hash table, a sparse array): nextSlot skips them. ArrayList, HashSet and HashMap (over its keys) declare it, which is why for (x of list) works.

A trait-typed value (it : Iterator<i32>) is not iterable by for … of. Take the concrete class.

Limits / Uncabled

FeatureStateDetail / workaround
for … of over a trait-typed iterator (it : Iterator<i32>)Refused (E0517)Take the concrete class as the parameter type
@derive on a generic classRefused by the parserWrite the members by hand
@derive on an exception or on a struct / enumRefused (E0012 for struct / enum)Write the members by hand
Owned class element with a destructor in a stdlib collection (ArrayList<Owned>, HashMap<K, Owned>, HashSet<Owned>)Refused (E0604)Use Shared<T> as the element type, which is supported
A generic trait carrying an impl blockRefused (E0780)Apply the trait at the type site, or drop the type parameter
A class as an impl-block targetRefused (E0784)Declare : Trait on the class
Structural conformance that relies on a trait default, without declaring the traitRefused (E0606)Declare the trait in the class header (: Trait)
Trait with no implementor used as a value type (parameter, field, return, local)Refused (E0605)Add an implementer, or drop the trait-typed slot
exception declaration that names a trait after its base (exception E : Base, Trait)Refused (E0609)Keep the exception a plain class of its own
Stdlib handle class (a class whose instances are native registry handles) implementing a traitRefused (E0610)Wrap the handle in a plain class of your own
Trait-typed field whose trait has a class implementerRefused (E0709)Store the concrete class type in the field instead of the trait
when T : Bound method called on an instantiation that does not satisfy the boundAbsent, call refused (E0015)Check the bound, or instantiate with a satisfying type
Type argument on a non-generic function (f<i32>())Refused (E0608)Drop the turbofish
Type parameter not inferable from the argumentsRefused (E0603)Supply it with a turbofish: make<i32>()
Generic function called with a value typed by a generic class applied to the enclosing class’s T (show(self.inner) where inner : Wrapper<T>)Refused (E0001)Call a method of the value, or give the function a concrete parameter type

See also

  • OOP recipe — trait declaration, default bodies, impl blocks, dyn Trait, class : Base, Trait
  • Enums — value-type variants, payloads, methods, and trait implementation
  • Pattern matching — the value match that match type T mirrors
  • Collections recipe — using generic stdlib containers
  • Concept index — quick lookup for every keyword
genericstraitsboundsderivematch typedynwhen