Skip to content

Generics and Interfaces

Buntos edited this page Dec 5, 2026 · 1 revision

Generics and Interfaces

H supports compile-time monomorphized generics on struct, class, enum, and def declarations, static interface contracts with explicit conformance (<), constrained type parameters ([T: Bound]), and ergonomic error propagation via Result[T, E] and the postfix ? operator.


1. Monomorphized Generics

Generic type parameters are uppercase identifiers listed inside [...]:

struct Pair[A, B]
  first: A
  second: B
end

class Box[T]
  val: T

  def initialize(@val: T)
  end

  def get() -> T
    @val
  end

  def set(v: T) -> Void
    @val = v
  end
end

enum OptionPair[A, B]
  empty
  both(A, B)
end

def identity[T](x: T) -> T
  x
end

Zero-Boxing Specialization & Name Mangling

When a generic declaration is instantiated with concrete type arguments, the compiler specializes its layout and methods into native LLVM IR types and functions with zero boxing or runtime type descriptors:

  • Concrete generic types and functions are deduplicated by their mangled name (Name__Arg1__Arg2, using ast.type_mangle for each argument).
    • Example: Pair[I64, String] becomes Pair__I64__String.
    • Example: Result[I64, String] becomes Result__I64__String.
    • Example: Array[U8] inside a generic argument mangles as Arr_U8; Ptr[U8] as Ptr_U8; I64? as Opt_I64.
  • Generic struct and enum instantiations preserve their exact inline value layout (unboxed structs and { i32, [W x i64] } tagged unions).
  • Non-entry module generic types and functions include their module prefix (mod__Name__Args) to avoid link-time symbol collisions.
  • Instantiated generic function and method bodies are appended to the compiler's pending_mono_fns queue and drained iteratively until all transitive generic instantiations are emitted.

2. Type Argument Inference & Generic UFCS

Generic types (Pair[I64, String].new(...), Box[I64].new(10), Result[I64, String].ok(42)) specify type arguments explicitly at construction sites.

Generic functions support both explicit type arguments and automatic type argument inference from call arguments (including UFCS receivers):

def map_vec[T, U](xs: Array[T], f: Fn(T) -> U) -> Array[U]
  out = Array[U].new()
  i: Usize = 0
  while i < xs.len
    out.push(f(xs[i]))
    i += 1
  end
  out
end

# Explicit type arguments
a = identity[I64](42)

# Inferred type arguments
b = identity(123)
c = identity("ok")

# Inferred via UFCS chaining (`T = I64`, `U = I64` inferred from `nums` and closure)
nums = [1, 2, 3, 4]
squares = nums.map_vec(fn(v: I64) -> I64 do v * v end)

Structural Unification Rules (unify_type_arg)

When type arguments are omitted on a generic function call, the compiler evaluates the call arguments and recursively unifies each parameter pattern against the actual argument type across:

  • Bare type parameters (T)
  • Nested generic struct, class, and enum types (matching original template name and stored orig_args)
  • Built-in containers and wrappers: Array[T], Slice[T], Ptr[T], StaticArray[T, N], and T?
  • Function types: Fn(P1, P2) -> R (unifying parameter types and return type)

If any type parameter cannot be determined from the call arguments, the compiler emits a compile-time error instructing which type parameter could not be inferred.


3. Interfaces & Conformance Bounds

Declaring an interface

An interface lists the method signatures a conforming type must provide, including optional mut def and @[nogc] requirements:

interface Describable
  def describe() -> String
end

interface Resettable
  @[nogc]
  mut def reset() -> Void
end

Explicit Conformance (< Interface)

A struct or class can declare conformance to one or more interfaces (comma-separated) after <:

struct Point < Describable
  x: I64
  y: I64

  def describe() -> String
    "(#{@x},#{@y})"
  end
end

Conformance is statically verified:

  • For concrete types, during the compiler's declaration verification pass.
  • For generic types (struct Wrapper[T] < Describable), upon each concrete instantiation.

Constrained Type Parameters ([T: Bound])

Generic def, struct, class, and enum declarations may constrain any type parameter with an interface bound:

def render[T: Describable](item: T) -> String
  item.describe()
end

pt = Point.new(3, 4)
text = render(pt)   # "(3,4)" — statically verified and monomorphized, zero vtable overhead

How Satisfaction Is Verified

For each required method m in interface I, check_type_satisfies_interface verifies:

  1. Method lookup: Searches first for a member method Type__m on T, and if none exists, falls back to a visible free UFCS function m(self: T, ...) whose first parameter equals T.
  2. @[nogc] contract: If the interface marks m as @[nogc], the implementation must also be @[nogc].
  3. mut def contract: If the interface marks m as mut def, the implementation must also be mut def (or a class method, which is always mutable).
  4. Signature equality: Parameter count, every parameter type, and the return type must match exactly.

Because interface bounds are checked at monomorphization time, calls through bounded type parameters compile to direct static function calls with zero dynamic dispatch or vtable overhead.


4. Result[T, E] & Postfix ? Error Propagation

std/result defines the standard generic result enum and helper functions:

enum Result[T, E]
  ok(T)
  err(E)
end

def is_ok[T, E](r: Result[T, E]) -> Bool
def is_err[T, E](r: Result[T, E]) -> Bool
def unwrap_or[T, E](r: Result[T, E], fallback: T) -> T

Propagating Result[T, E] with ?

Applying postfix ? to a Result[T, E] expression inside a function returning Result[U, E]:

  1. Inspects the enum tag.
  2. If .ok(v), evaluates to v: T and continues execution.
  3. If .err(e), executes all pending lexical defer and with_arena cleanups in LIFO order (emit_cleanups_down_to(1)) and returns .err(e) as the enclosing function's Result[U, E].
import result

def checked_div(a: I64, b: I64) -> Result[I64, String]
  if b == 0
    return Result[I64, String].err("zero")
  end
  Result[I64, String].ok(a / b)
end

def div_pipeline(x: I64, y: I64, z: I64) -> Result[I64, String]
  a = checked_div(x, y)?
  b = checked_div(a, z)?
  Result[I64, String].ok(b * 2)
end

The compiler verifies that the enclosing function returns a matching enum with an err(E) variant whose error type E matches the operand's error type. Any user-defined enum with single-payload ok(T) and err(E) variants works with ? under the same rule.

Propagating Optionals (T?) with ?

Postfix ? also works on nullable T? values inside any function returning an optional U?:

def add_opts(a: I64?, b: I64?) -> I64?
  x = a?
  y = b?
  x + y
end
  • If the value is non-nil, expr? unwraps it to T.
  • If the value is nil, all pending defer and with_arena cleanups run in LIFO order and the enclosing function immediately returns nil.
  • Using ? on T? inside a function that does not return an optional U? is a compile-time error.

Next: Standard Library

Clone this wiki locally