Repository navigation
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.
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
endWhen 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, usingast.type_manglefor each argument).- Example:
Pair[I64, String]becomesPair__I64__String. - Example:
Result[I64, String]becomesResult__I64__String. - Example:
Array[U8]inside a generic argument mangles asArr_U8;Ptr[U8]asPtr_U8;I64?asOpt_I64.
- Example:
- Generic
structandenuminstantiations 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_fnsqueue and drained iteratively until all transitive generic instantiations are emitted.
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)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, andenumtypes (matching original template name and storedorig_args) - Built-in containers and wrappers:
Array[T],Slice[T],Ptr[T],StaticArray[T, N], andT? - 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.
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
endA 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
endConformance is statically verified:
- For concrete types, during the compiler's declaration verification pass.
- For generic types (
struct Wrapper[T] < Describable), upon each concrete instantiation.
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 overheadFor each required method m in interface I, check_type_satisfies_interface verifies:
-
Method lookup: Searches first for a member method
Type__monT, and if none exists, falls back to a visible free UFCS functionm(self: T, ...)whose first parameter equalsT. -
@[nogc]contract: If the interface marksmas@[nogc], the implementation must also be@[nogc]. -
mut defcontract: If the interface marksmasmut def, the implementation must also bemut def(or aclassmethod, which is always mutable). - 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.
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) -> TApplying postfix ? to a Result[T, E] expression inside a function returning Result[U, E]:
- Inspects the enum tag.
- If
.ok(v), evaluates tov: Tand continues execution. - If
.err(e), executes all pending lexicaldeferandwith_arenacleanups in LIFO order (emit_cleanups_down_to(1)) and returns.err(e)as the enclosing function'sResult[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)
endThe 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.
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 toT. - If the value is
nil, all pendingdeferandwith_arenacleanups run in LIFO order and the enclosing function immediately returnsnil. - Using
?onT?inside a function that does not return an optionalU?is a compile-time error.
Next: Standard Library