comptime VM: Phase 3 — register_type write side + payloadless-enum fixes
The mutating compiler-API, minting types LAZILY at lowering time (single pass,
the existing runComptimeTypeFunc path — so the write side is legacy-only; the
VM isn't wired at lowering time, and the read-side readers stay dual-path):
declare_type(name) -> Type forward nominal handle (≈ declare)
pointer_to(t) -> Type build *T references
register_type(handle, kind, members) ONE kind-branching fill (≈ unified define)
register_type branches on kind IN THE COMPILER (subsuming define's per-kind
dispatch); codes match type_kind: 1 struct, 2 actual .@"enum", 3 tagged_union,
4 tuple. Members are {name: string, ty: Type}. A non-generic `-> Type` builder is
now flagged is_comptime (decl.zig) so its dead body permits the welded calls.
Graph support: forward declare_type handles + pointer_to express a mutually-
recursive A<->B graph (*A, *B, B-by-value) before bodies are filled. register_type
is idempotent — re-filling a nominal slot (a minting module reached via two import
edges) re-mints identically rather than erroring (nominalIdent reads identity from
any nominal kind).
Fixes (issue 0142):
- A fully payloadless comptime-minted enum was minted as an all-void tagged_union,
whose IR size disagrees with its LLVM size -> verifySizes panic. Now mints a real
.@"enum" (register_type kind 2 AND the metatype defineEnum).
- Bare `EnumType.variant` qualified construction of a payloadless variant wasn't
supported (failed for hand-written enums too — the type name lowered to a Type
value). Added in lowerFieldAccess via isPayloadlessVariant; payload-carrying
variants keep their call form.
Examples: 0631 (graph + actual enum + reflection), 0632 (make_enum all-void),
0633/0634/0635 (namespaced / bare / multi-edge import of a minted type), 0187
(qualified variant construction). Unit tests added.
Parity 697/697 (gate OFF and -Dcomptime-flat).
This commit is contained in:
@@ -54,8 +54,20 @@ pub const bound_fns = [_]BoundFn{
|
||||
.{ .sx_name = "type_field_type", .handler = handleTypeFieldType },
|
||||
.{ .sx_name = "type_kind", .handler = handleTypeKind },
|
||||
.{ .sx_name = "type_field_value", .handler = handleTypeFieldValue },
|
||||
// ── write side (lowering-time, mints into the type table) ────────────────
|
||||
.{ .sx_name = "declare_type", .handler = handleDeclareType },
|
||||
.{ .sx_name = "pointer_to", .handler = handlePointerTo },
|
||||
.{ .sx_name = "register_type", .handler = handleRegisterType },
|
||||
};
|
||||
|
||||
// Kind codes accepted by `register_type` — mirror `TypeTable.kindCode`. An
|
||||
// enum-like type is minted as a `tagged_union` (the general payload-carrying
|
||||
// form, as `define` does), so both 2 (`enum`) and 3 (`tagged_union`) are taken.
|
||||
const kind_struct: i64 = 1;
|
||||
const kind_enum: i64 = 2;
|
||||
const kind_tagged_union: i64 = 3;
|
||||
const kind_tuple: i64 = 4;
|
||||
|
||||
/// Look up a compiler function by its sx name. Returns null when the name is not
|
||||
/// on the export list.
|
||||
pub fn findFn(sx_name: []const u8) ?*const BoundFn {
|
||||
@@ -170,3 +182,128 @@ fn handleTypeFieldValue(interp: *Interpreter, args: []const Value) InterpError!V
|
||||
const v = interp.module.types.memberValue(tid, args[1].int) orelse return error.TypeError;
|
||||
return Value{ .int = v };
|
||||
}
|
||||
|
||||
// ── write side: declare_type / pointer_to / register_type ───────────────────
|
||||
//
|
||||
// These MINT into the type table, so they only make sense at LOWERING time —
|
||||
// where the compiler still resolves references to the new types and the `mint`
|
||||
// target is open (`runComptimeTypeFunc`). They take/return real `Type` values
|
||||
// (`.type_tag`), the comptime-native form, matching meta.sx's `StructField` /
|
||||
// `declare` / `define`. This is the unified re-expression of the metatype:
|
||||
// `declare_type` ≈ `declare`, `register_type` ≈ a single kind-branching `define`,
|
||||
// and `pointer_to` builds `*T` references so a graph of types can refer to each
|
||||
// other (forward handles + pointers) before their bodies are filled.
|
||||
|
||||
/// `declare_type(name: string) -> Type` — mint a NEW empty forward nominal type
|
||||
/// named `name` (or return the existing slot, so a self/sibling reference by name
|
||||
/// resolves to the same one). Mirrors the `declare` builtin: the forward slot is
|
||||
/// an empty `tagged_union` until `register_type` fills it.
|
||||
fn handleDeclareType(interp: *Interpreter, args: []const Value) InterpError!Value {
|
||||
if (args.len != 1 or args[0] != .string) return error.TypeError;
|
||||
const tbl = mintTable(interp);
|
||||
const name_id = tbl.internString(args[0].string);
|
||||
if (tbl.findByName(name_id)) |existing| return Value{ .type_tag = existing };
|
||||
const info: types.TypeInfo = .{ .tagged_union = .{ .name = name_id, .fields = &.{}, .tag_type = .i64 } };
|
||||
return Value{ .type_tag = tbl.internNominal(info, 0) };
|
||||
}
|
||||
|
||||
/// `pointer_to(t: Type) -> Type` — intern `*t`. Lets a member reference a type by
|
||||
/// pointer (e.g. a recursive `*A`) from a `Type` handle.
|
||||
fn handlePointerTo(interp: *Interpreter, args: []const Value) InterpError!Value {
|
||||
if (args.len != 1 or args[0] != .type_tag) return error.TypeError;
|
||||
const tbl = mintTable(interp);
|
||||
return Value{ .type_tag = tbl.intern(.{ .pointer = .{ .pointee = args[0].type_tag } }) };
|
||||
}
|
||||
|
||||
/// `register_type(handle: Type, kind: i64, members: []Member) -> Type` — fill a
|
||||
/// `declare_type`'d forward slot, branching on `kind` IN THE COMPILER (subsuming
|
||||
/// `define`'s per-kind dispatch). `Member` is `{ name: string, ty: Type }`:
|
||||
/// struct → fields `{ name, ty }` (dup names rejected)
|
||||
/// enum/t-union → variants `{ name, payload = ty }` (minted as a tagged_union)
|
||||
/// tuple → positional element types (names ignored)
|
||||
/// Returns the (now completed) handle. Every malformed input is a loud error.
|
||||
fn handleRegisterType(interp: *Interpreter, args: []const Value) InterpError!Value {
|
||||
if (args.len != 3 or args[0] != .type_tag or args[1] != .int) return error.TypeError;
|
||||
const handle = args[0].type_tag;
|
||||
const kind = args[1].int;
|
||||
const elems = interp_mod.decodeVariantElements(args[2]) orelse return error.TypeError;
|
||||
if (elems.len == 0) return error.TypeError; // a type with no members is never valid
|
||||
const tbl = mintTable(interp);
|
||||
// The slot's nominal identity. Accept the forward `tagged_union` from
|
||||
// `declare_type` AND an already-completed nominal of the same name — so
|
||||
// re-evaluating the same type-fn (e.g. a minting module reached via two
|
||||
// import edges) RE-FILLS the slot idempotently instead of erroring. A
|
||||
// non-nominal handle is rejected (not a `declare_type`'d slot).
|
||||
const ident = nominalIdent(tbl.get(handle)) orelse return error.TypeError;
|
||||
|
||||
if (kind == kind_tuple) {
|
||||
var tys = std.ArrayList(types.TypeId).empty;
|
||||
for (elems) |elem| {
|
||||
const m = memberPair(elem) orelse return error.TypeError;
|
||||
tys.append(interp.alloc, m.ty) catch return error.CannotEvalComptime;
|
||||
}
|
||||
tbl.replaceKeyedInfo(handle, .{ .tuple = .{ .fields = tys.items, .names = null } });
|
||||
return Value{ .type_tag = handle };
|
||||
}
|
||||
|
||||
if (kind == kind_enum) {
|
||||
// An ACTUAL (payloadless) enum: members are variant NAMES. A non-void
|
||||
// payload means the caller wants a payload-carrying variant — that's a
|
||||
// tagged_union (kind 3), so reject it loudly rather than dropping it.
|
||||
var variants = std.ArrayList(StringId).empty;
|
||||
for (elems) |elem| {
|
||||
const m = memberPair(elem) orelse return error.TypeError;
|
||||
if (m.ty != .void) return error.TypeError; // payload variant → use kind 3 (tagged_union)
|
||||
const name_id = tbl.internString(m.name);
|
||||
for (variants.items) |existing| if (existing == name_id) return error.TypeError; // dup variant
|
||||
variants.append(interp.alloc, name_id) catch return error.CannotEvalComptime;
|
||||
}
|
||||
tbl.replaceKeyedInfo(handle, .{ .@"enum" = .{ .name = ident.name, .variants = variants.items, .nominal_id = ident.nominal_id } });
|
||||
return Value{ .type_tag = handle };
|
||||
}
|
||||
|
||||
// struct / tagged_union collect `{ name, ty }` fields.
|
||||
var fields = std.ArrayList(types.TypeInfo.StructInfo.Field).empty;
|
||||
for (elems) |elem| {
|
||||
const m = memberPair(elem) orelse return error.TypeError;
|
||||
const name_id = tbl.internString(m.name);
|
||||
for (fields.items) |existing| if (existing.name == name_id) return error.TypeError; // dup member name
|
||||
fields.append(interp.alloc, .{ .name = name_id, .ty = m.ty }) catch return error.CannotEvalComptime;
|
||||
}
|
||||
const full: types.TypeInfo = switch (kind) {
|
||||
kind_struct => .{ .@"struct" = .{ .name = ident.name, .fields = fields.items, .nominal_id = ident.nominal_id } },
|
||||
kind_tagged_union => .{ .tagged_union = .{ .name = ident.name, .fields = fields.items, .tag_type = .i64, .nominal_id = ident.nominal_id } },
|
||||
else => return error.TypeError, // unknown kind code
|
||||
};
|
||||
tbl.replaceKeyedInfo(handle, full);
|
||||
return Value{ .type_tag = handle };
|
||||
}
|
||||
|
||||
/// The nominal identity (`name` + stable `nominal_id`) of a declare_type'd slot —
|
||||
/// from the forward `tagged_union` OR an already-completed nominal (so a re-fill
|
||||
/// preserves identity). A `tuple` is structural (no nominal name); null for a
|
||||
/// non-nominal handle (not a `declare_type` result).
|
||||
fn nominalIdent(info: types.TypeInfo) ?struct { name: StringId, nominal_id: u32 } {
|
||||
return switch (info) {
|
||||
.tagged_union => |u| .{ .name = u.name, .nominal_id = u.nominal_id },
|
||||
.@"enum" => |e| .{ .name = e.name, .nominal_id = e.nominal_id },
|
||||
.@"struct" => |s| .{ .name = s.name, .nominal_id = s.nominal_id },
|
||||
.tuple => .{ .name = StringId.empty, .nominal_id = 0 }, // structural; name vestigial
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// Decode one `Member` value — a `{ name: string, ty: Type }` aggregate.
|
||||
fn memberPair(elem: Value) ?struct { name: []const u8, ty: types.TypeId } {
|
||||
const f = switch (elem) {
|
||||
.aggregate => |a| a,
|
||||
else => return null,
|
||||
};
|
||||
if (f.len != 2) return null;
|
||||
const name = switch (f[0]) {
|
||||
.string => |s| s,
|
||||
else => return null,
|
||||
};
|
||||
const ty = f[1].asTypeId() orelse return null;
|
||||
return .{ .name = name, .ty = ty };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user