Generic Derive Function
A @comptime fn that receives a typeinfo descriptor can produce output for
any type — struct or enum — without knowing the type in advance. This is exactly
the seam a future derive(Trait) plugs into: the function receives
typeinfo(Self) and emits an impl. Here one function generates a one-line type
signature for both structs and enums.
A single @comptime fn signature branches on info.kind to emit a field list for structs and a variant union for enums — demonstrating one function that works for both Point and Shape.
09-derive-generic.zolo
// Use case 6 — GENERIC DERIVE (the N2 substrate)
//
// One `@comptime fn` consumes `typeinfo` and works for ANY declared type —
// struct OR enum. This is exactly the seam a future `derive(Trait)` plugs into:
// the macro receives `typeinfo(Self)` and emits an impl. Here we "derive" a
// one-line type signature for two unrelated types with the same code.
@comptime
fn signature(info) -> str {
if info.kind == "enum" {
var s = info.name + " = "
var first = true
for v in info.variants {
if first == false { s = s + " | " }
s = s + v.name
first = false
}
return s
}
var s = info.name + "("
var first = true
for f in info.fields {
if first == false { s = s + ", " }
s = s + f.name + ": " + f.type.name
first = false
}
return s + ")"
}
struct Point { x: int, y: int }
enum Shape { Circle, Square, Triangle }
let sig_struct = comptime signature(typeinfo(Point))
let sig_enum = comptime signature(typeinfo(Shape))
print(sig_struct)
// expected: Point(x: int, y: int)
print(sig_enum)
// expected: Shape = Circle | Square | Triangle
See also