Generics

Generics let one declaration describe a family of concrete structs, choices or functions. Moth specialises each use statically and doesn't expose erased generic values at runtime.

Ordinary type inference uses immediate arguments and receiving types. A bounded numeric-origin exception can carry an existing numeric value through a generic signature to later exact uses in the same body. It never searches callee bodies or the whole program.

Choose the explanation level: Generic declarations

Generic declarations

A generic declaration describes a family of types or functions using a placeholder type.

A generic struct

Box type A = |
    value A,
|

A stands for some concrete type. Later you can make a Box of I32, a Box of String and so on.

A generic function

identity type A |value A| -> A:
    return value
;

identity returns whatever type it receives.

The placeholder is scoped

The parameter name is meaningful only inside that declaration. You cannot use A as a value or refer to it from another declaration.

Generics form declaration-site type abstractions for top-level structs, choices and free functions. A generic parameter acts as a compile-time placeholder that stands for a concrete type selected later.

Generic declaration syntax

identity type A |value A| -> A:
    return value
;

Box type A = |
    value A,
|

Maybe type A ::
    Some | value A |,
    Empty,
;

Generic parameters follow the declaration name after type. Multiple parameters are separated by commas.

Exact generic declaration contract

  • Generic parameters are introduced with type after the declaration name.
  • Supported declaration owners are top-level structs, choices and free functions.
  • Parameter names use type-name casing.
  • Parameters are scoped to the declaration.
  • Parameters are compile-time placeholders, not runtime values.
  • Each parameter name must be unique within the declaration.
  • Parameters cannot collide with visible concrete types, type aliases, external package types, builtins or other type-position names.
  • A generic body may use active parameters in local type annotations.
  • Inline parameter sugar such as |value type A| is rejected.
  • Generic parameters do not create type values.
  • Generic declarations are resolved before HIR.
  • Implicit failure follows the closed module boundary: an exported generic without an error slot must handle it locally, while a private generic propagates it within the same module. See Errors.
  • A generic function may declare -> !. The contract is exact after specialisation, like any other callable.

Multiple parameters

Pair type A, B = |
    first A,
    second B,
|

Unused parameters

A generic parameter must be used in the public type shape of the declaration. An unused parameter is rejected.

-- Error: parameter 'A' is declared but never used
identity type A |value String| -> String:
    return value
;

No inline parameter sugar

Generic parameters belong in the declaration header, not inside ordinary parameter lists.

-- Error
identity |value type A| -> A:
    return value
;

Compiler stage note

Header parsing records generic parameter lists and declaration metadata. AST resolves generic signatures to canonical type identities, validates generic bodies against unconstrained parameters and emits concrete instances before HIR generation. HIR never carries unresolved generic calls.

Concepts related to generic declarations

Choose the explanation level: Type application

Type application

Use of to choose the concrete type for a generic declaration.

One argument

Box type A = |
    value A,
|

text_box Box of String = Box("hello")

Several arguments

Pair type A, B = |
    first A,
    second B,
|

item Pair of String, I32 = Pair("count", 3)

Concrete aliases

When a type would need nested of applications, name an intermediate alias.

StringIntPair as Pair of String, I32
value Box of StringIntPair = Box(Pair("count", 3))

Concrete generic instances are created with of in type position.

of takes its meaning from the head before it. This reference owns ordinary generic application. Compiler-owned Wire and Route heads instead describe parameter capabilities under the Wiring reference. They do not become ordinary type arguments or change generic nesting rules.

Type application syntax

number_box Box of I32 = Box(42)
text_box Box of String = Box("hello")

Pair type A, B = |
    first A,
    second B,
|

item Pair of String, I32 = Pair("count", 3)

Exact type application contract

  • of applies concrete type arguments in type position.
  • Argument count must match the generic declaration.
  • Each argument must be a valid concrete type.
  • Different concrete argument lists produce different semantic types.
  • Constructors use ordinary constructor syntax.
  • Explicit generic free-function call type arguments are not supported.

Nested of boundary

Nested inline of applications are rejected. Use a named concrete alias for any nested shape the current compiler rejects.

-- Error
value Box of Pair of String, I32 = Box(Pair("count", 3))

Work around the limit with an intermediate alias:

StringIntPair as Pair of String, I32
value Box of StringIntPair = Box(Pair("count", 3))

The collection element exception allows one inline of application inside a collection element annotation, such as {Box of String}. Nested of applications inside a collection element are rejected for the same reason as nested of in any other type position: use a named concrete alias.

Concrete generic aliases

A type alias may name a fully applied generic instance. The alias remains transparent.

StringBox as Box of String

box StringBox = Box("docs")
raw Box of String = box

Constructed forms are compiler-owned

Public Option of T, Result of T, E, Option.Some and Result.Ok are not language syntax. Options and collections have their own compiler-owned type forms and source syntax. Function success slots and the separate error channel do not manufacture a semantic Result or tuple type.

Concepts related to type application

Choose the explanation level: Generic inference

Generic inference

Generic calls use ordinary syntax. Immediate evidence selects generic types. An existing numeric origin can also stay linked through a generic signature until an exact receiving use resolves it within the same body.

Inference from an argument

identity type A |value A| -> A:
    return value
;

value = identity(42)

With no other exact numeric constraint in the body, the whole-number origin defaults to I32, so A resolves to I32.

Inference from the result type

empty type A || -> {A}:
    return {}
;

items {I32} = empty()

The immediate receiving type says the result is {I32}, so A becomes I32.

Generic calls use ordinary syntax. Ordinary type parameters come from immediate evidence. A bounded numeric-origin exception lets an existing numeric unknown pass through a generic signature's parameter and result before the caller body defaults it.

Inference sources

identity type A |value A| -> A:
    return value
;

empty type A || -> {A}:
    return {}
;

accept_u64 |value U64|:
;

value = identity(42)
typed_value I32 = identity(42)
items {I32} = empty()

forwarded = identity(1)
accept_u64(forwarded)

Ordinary generic types come from immediate arguments or an immediate expected result shape. When an argument already contains a numeric origin, a signature such as A -> A may share that origin between parameter and result. Eligible exact receivers can resolve the retained origin through direct uses later in the same function body, including connected copies and writes. In the final call above, the generic signature alone carries the whole-number origin to the U64 parameter receiver. See Numeric literals for the full inference contract.

The compiler does not inspect the callee body or search trait evidence to select a numeric type. Generic declarations, instances and public interfaces contain declared type parameters or completed exact types, never pending numeric identities.

What inference does not use

-- Error: T has no immediate evidence and no numeric origin.
values = empty()

Outside the bounded numeric-origin relation above, later use does not infer a generic parameter. In particular, inference does not search:

  • later mutation or later reads to create an otherwise missing type
  • whole-program uses, another function body or HIR
  • borrow validation or trait implementations
  • distant return uses
  • an outer call's parameter context into a nested generic call
  • backward from an operation result into already named operands

An existing numeric origin can be shared through a known collection, map, nominal/generic or optional shape while the shape, capacity, key restrictions, constructor identity and nonnumeric types remain fixed. This does not infer anonymous structure or turn an empty container into a numeric origin.

Use an intermediate annotation when a nested generic call has no immediate evidence.

empty type A || -> {A}:
    return {}
;

consume |values {I32}|:
;

-- Rejected: the outer parameter context does not solve the nested call.
consume(empty())

-- Valid: annotate the nested result first.
items {I32} = empty()
consume(items)

Never generic calls

A generic function declared -> ! has no result shape. Inference uses the immediate arguments only. There is no expected result type to solve a parameter.

abort type A |value A| -> !:
    assert(false, "aborted")
;

abort("unreachable")

A Never call remains a standalone statement, so it cannot sit at a typed receiving site that would otherwise supply result evidence.

Optional and fallible generic returns

Generic functions may return optional or fallible values when the concrete envelope is solved by immediate evidence.

wrap_optional type T |value T| -> T?:
    return value
;

always_fail type T, E |fallback T, err E| -> T, E!:
    return! err
;

maybe_name String? = wrap_optional("Priya")

value = always_fail(7, Error("bad")) catch |err| then 0

A bare none cannot infer an otherwise unknown parameter by itself.

Imported generic functions

Visible imported generic functions use the same local inference rules. There is no explicit call-site type argument syntax.

Cast boundary

A cast target does not constrain the source type. Resolve the generic call's source independently from eligible exact receivers for its retained numeric origin, then apply the ordinary default if none resolves it. The cast classifies the completed source/target pair.

Generic error parameter inference

A concrete callee error type does not specialise an otherwise unsolved generic error parameter merely because it appears inside the generic body. Immediate declaration and call-site evidence must still solve the parameter.

-- Rejected: E is not solved by the concrete Error inside the body.
generic_fail type E || -> I32, E!:
    return! Error("bad")
;

A generic error parameter must be solved by immediate call-site evidence, like any other generic parameter.

Explicit call-site syntax is rejected

All of these are rejected:

identity of I32(42)
identity<I32>(42)
identity[I32](42)
identity(42 I32)

Concepts related to generic inference

Choose the explanation level: Generic instances

Generic instances

When you apply concrete types to a generic declaration, you get a concrete instance.

A concrete generic struct

Box type A = |
    value A,
|

int_box Box of I32 = Box(42)
string_box Box of String = Box("hello")

Box of I32 and Box of String are different types. You cannot assign one to the other.

A concrete generic choice

Maybe type A ::
    Some | value A |,
    Empty,
;

name Maybe of String = Maybe::Some("Priya")

Maybe of String stores a String payload. Maybe of I32 stores an I32 payload.

Generic shapes stay fixed while eligible numeric origins in their known fields can resolve within one body. This doesn't infer an unknown shape or a nonnumeric type argument. See Generic inference.

A concrete generic instance substitutes the generic parameters with concrete type arguments. The resulting type is ordinary: it has fields, constructors and the same access rules as any other type.

Field and payload substitution

Box type A = |
    value A,
|

int_box Box of I32 = Box(42)
string_box Box of String = Box("hello")

Box of I32 and Box of String are different semantic types. The field value has type I32 in the first and String in the second.

Generic choices

Maybe type A ::
    Some | value A |,
    Empty,
;

name Maybe of String = Maybe::Some("Priya")
missing Maybe of String = Maybe::Empty

Choice payload matching uses the substituted payload types.

Instance identity

Same constructor plus same concrete arguments yields the same instance type. Different arguments yield incompatible instance types.

Box type A = |
    value A,
|

a Box of I32 = Box(1)
b Box of I32 = Box(2)
-- c Box of String = a -- would be an error

Constructor inference

Generic struct and choice constructors infer type arguments from immediate arguments and the immediate receiving type. A constructor may preserve an existing numeric origin through its known generic field shape until eligible exact receivers resolve it through direct uses in the same function body, including connected copies and writes. This does not infer other type arguments or structure from later uses. See Numeric literals for the full inference contract. No explicit constructor type arguments are supported.

Box type A = |
    value A,
|

-- Inferred from the constructor argument.
value = Box(42)

-- Inferred from the receiving type.
text_box Box of String = Box("hello")

Aligned receiver methods

A receiver method may be declared on a generic type when the method's generic parameters align exactly with the receiver constructor's parameters.

Box type A = |
    value A,
|

get type A |this Box of A| -> A:
    return this.value
;

box Box of I32 = Box(42)
value = box.get()

Receiver methods on one concrete generic instance remain rejected.

Generic bounds and evidence

Concrete instantiation with trait bounds requires reusable evidence for each concrete argument. See Generic trait bounds.

Deferred and rejected surfaces

  • Recursive generic nominal types are rejected.
  • Receiver methods on concrete instances are rejected.
  • Generic external package functions and types are deferred.

Implicit failure follows the closed module boundary: an exported generic instance without an error slot must discharge it. See Errors for failure delivery.

Concepts related to generic instances

Choose the explanation level: Generic limits

Generic limits

Generic code can move an unknown type around, but it needs a bound before calling type-specific behaviour.

Moving values around

identity type A |value A| -> A:
    return value
;

identity does not need to know anything about A. It returns what it got.

Needing a bound

DISPLAY_TEXT must:
    display |This| -> String
;

render type Item is DISPLAY_TEXT |item Item| -> String:
    return item.display()
;

render can call .display() because the bound promises that Item provides it.

Unconstrained generic code can move values around but cannot assume type-specific behaviour.

What unconstrained generic code may do

  • pass values through
  • return them
  • store them in generic structs or choices
  • forward them to another generic function when immediate evidence solves the call
  • use generic parameters in local annotations

What unconstrained generic code cannot assume

  • arithmetic
  • equality or ordering
  • field access
  • string-like template interpolation
  • external or IO behaviour
  • arbitrary receiver methods

A trait bound may enable the unique receiver behaviour provided by its static contract.

DISPLAY_TEXT must:
    display |This| -> String
;

render type Item is DISPLAY_TEXT |item Item| -> String:
    return item.display()
;

Current implementation limits

  • explicit call-site generic syntax
  • inline generic parameter sugar such as |value type A|
  • recursive generic types
  • receiver methods on concrete instances
  • generic external package functions and types
  • nested inline of applications beyond the accepted single application
  • public Option/Result constructors

Outside generic design scope

  • generic function values
  • higher-order polymorphism
  • type values
  • type-returning functions
  • type-level #if
  • compile-time type inspection
  • where clauses
  • file-local evidence-backed bound dispatch
  • parameterized aliases
  • partial type application
  • higher-kinded types
  • user const generics beyond fixed collection capacity
  • lifetime parameters
  • specialization
  • associated types

Deferred surfaces may land in future Alpha iterations. Outside-scope surfaces require an explicit language-philosophy change before they can be added.

General closures, generic function values and higher-order polymorphism remain outside scope. A narrower design for references to named, monomorphic, non-capturing functions remains an open question rather than deferred generic work.

Concepts related to generic limits