From 353109206bc0137c20af85cacbb3de90660825dc Mon Sep 17 00:00:00 2001 From: agra Date: Tue, 16 Jun 2026 18:32:05 +0300 Subject: [PATCH] =?UTF-8?q?green(reify):=20implement=20reify(.enum)=20?= =?UTF-8?q?=E2=80=94=20mint=20a=20flat=20enum=20from=20TypeInfo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit REIFY Phase 0.2 (Phase 0 complete). Lowering.reifyType (lower/nominal.zig) reads the flat-enum TypeInfo literal off the AST, synthesizes an ast.EnumDecl, and feeds it through the SAME type_bridge.buildEnumInfo path source enums use — so the minted type is byte-identical to a hand-written `enum { value: i64; closed; }` and flows through enum codegen (layout / construct / match) UNMODIFIED (Contract 2). Wired at the `E :: reify(...)` const-decl hook in lower/decl.zig (replacing the Phase-0.0 loud bail). Unsupported argument shapes bail loudly via reifyBail — never a silent default. The generic.zig inline reify path now reports it's only supported in a `::` binding (Phase 0). examples/0614 green: reify a {value: i64, closed} enum, construct .value(3) and .closed, match both -> "value 3" / "closed". Full suite green (670 examples, 447 unit). --- current/CHECKPOINT-REIFY.md | 52 +++++++--- current/PLAN-REIFY.md | 3 +- examples/0614-comptime-reify-enum.sx | 2 +- .../expected/0614-comptime-reify-enum.exit | 1 + .../expected/0614-comptime-reify-enum.stderr | 1 + .../expected/0614-comptime-reify-enum.stdout | 2 + src/ir/lower.zig | 1 + src/ir/lower/decl.zig | 16 ++-- src/ir/lower/generic.zig | 13 ++- src/ir/lower/nominal.zig | 94 +++++++++++++++++++ 10 files changed, 155 insertions(+), 30 deletions(-) create mode 100644 examples/expected/0614-comptime-reify-enum.stderr create mode 100644 examples/expected/0614-comptime-reify-enum.stdout diff --git a/current/CHECKPOINT-REIFY.md b/current/CHECKPOINT-REIFY.md index ff672a64..0d080210 100644 --- a/current/CHECKPOINT-REIFY.md +++ b/current/CHECKPOINT-REIFY.md @@ -4,15 +4,25 @@ Companion to [PLAN-REIFY.md](PLAN-REIFY.md). Update after every step (one step a time, per the cadence rule). ## Last completed step -**Phase 0.1 (xfail).** Added `examples/0614-comptime-reify-enum.sx` — reify a -flat enum (`value: i64`, `closed`) from a `TypeInfo` literal, construct -`E.value(3)` / `E.closed`, match both. Seeded an EMPTY -`expected/0614-…​.exit` marker → corpus is RED ("unparseable expected exit", -reify still bails). This is the deliberate xfail; **Phase 0.2 turns it green** -(per the no-commit-both-adds-and-passes cadence). `zig build test` is RED on -this commit by design (1 example fails); the very next commit makes it pass. +**Phase 0.2 (green) — Phase 0 COMPLETE.** Implemented `reify(.enum(...))`: +`Lowering.reifyType` (in `lower/nominal.zig`) reads the flat-enum `TypeInfo` +literal off the AST, synthesizes an `ast.EnumDecl`, and feeds it through the +SAME `type_bridge.buildEnumInfo` path source enums use → the minted type is +byte-identical to a hand-written `enum { value: i64; closed; }` and flows +through enum codegen unmodified (**Contract 2 confirmed** — a source enum +exhibits the exact same construct/match behavior, verified by probe). Wired at +the `E :: reify(...)` const-decl hook in `lower/decl.zig`. `examples/0614` +green (`value 3` / `closed`, exit 0); snapshots captured; full suite green +(670 examples, 447 unit). Unsupported reify shapes bail loudly via +`reifyBail` (never a silent default). -### (prior) Phase 0.0 (lock). Added the comptime type-metaprogramming surface as the +Also landed (user-directed, separate commit `feat(parser):`): reserved keyword +as a member name after `.` (`.enum`, `case .enum:`, `x.enum`) — so the reify +example reads `reify(.enum(...))` without a backtick. readme updated. + +### Two earlier Phase-0 commits +- **0.1 (xfail).** Added `examples/0614` + empty `.exit` marker → RED. +- **0.0 (lock).** Added the comptime type-metaprogramming surface as the on-demand module `library/modules/std/meta.sx` (NOT the prelude — see decision below): `EnumVariant`/`EnumInfo`/`TypeInfo` data types + bodyless `#builtin` decls `reify` / `type_info` / `field_type`. Each builtin bails LOUDLY when @@ -42,16 +52,32 @@ on-demand import keeps the prelude clean; reify users `#import "modules/std/meta.sx"`. (User-directed.) ## Next step -**Phase 0.1 (xfail):** add `examples/06xx-comptime-reify-enum.sx` — `reify(.`enum( -.{ variants = .[ .{name="value",payload=i64}, .{name="closed",payload=void} ] }))`, -construct `.value(3)`, match it. RED (reify unimplemented → the loud bail above). -Seed `examples/expected/.exit`. Then 0.2 (green: implement `reify(.`enum)` -in the interpreter / `decl.zig` reify hook). +**Phase 1 (type-fn → reify identity).** `R :: ($T) -> Type { reify(...) }`; assert +`R(i64)` from two sites is ONE type (assignable / matchable across sites). xfail → +green by registering a reify-returning type-fn's result under the instantiation +mangled name (mirror `generic.zig:1663-1689`). NOTE: Phase 0's `reifyType` is hooked +only at the `E :: reify(...)` const-decl site (`decl.zig`) and reads a LITERAL +`TypeInfo` off the AST; Phase 1 must route a reify call returned from a type-fn body +(and likely generalize the literal-AST reader, or evaluate via the interpreter, for +non-literal `TypeInfo`). + +OPEN DESIGN Q (raised by user, = Phase 4): self-referencing enum via `*Self`/`[]Self` +payloads. Current `reifyType` resolves each payload eagerly through `buildEnumInfo`, +so a `*Self` payload has no type to point at yet — Phase 4 needs the +reserve-placeholder→complete path (`nominal.zig` reserve + `types.zig:442`): intern +the enum's nominal slot FIRST, expose it as `Self`, then resolve payloads. By-value +recursion stays rejected (infinite size). ## Known issues None yet. ## Log +- **0.2 (green) — Phase 0 done.** `reifyType` mints a flat enum from a literal + `TypeInfo` via the shared `buildEnumInfo` path; `0614` green; Contract 2 confirmed + (reify'd enum == source enum, same construct/match). Payload-less variant idiom in + the example is `c : E = .closed;` (enum-literal target), same as a source enum. +- **parser (user-directed).** Keyword as member name after `.` — see `feat(parser)`. +- **0.1 (xfail).** `0614` + empty `.exit` marker → RED. - **0.0 (lock).** Meta surface in `modules/std/meta.sx` (data types + 3 bodyless `#builtin` decls), loud bails at all three reach points, `src/parser.test.zig` parse-lock. Two user-directed refinements folded in: variant uses `` `enum `` diff --git a/current/PLAN-REIFY.md b/current/PLAN-REIFY.md index 619425b7..45b07907 100644 --- a/current/PLAN-REIFY.md +++ b/current/PLAN-REIFY.md @@ -106,7 +106,8 @@ Examples: `06xx` (comptime, deterministic), `11xx` (diagnostics for loud failure ## Status -- [ ] Phase 0 — `reify` flat enum +- [x] Phase 0 — `reify` flat enum (`reify(.enum(...))` mints a flat enum via the + shared `buildEnumInfo` path; `examples/0614` green; Contract 2 confirmed) - [ ] Phase 1 — type-fn identity - [ ] Phase 2 — `type_info` + `field_type` - [ ] Phase 3 — `make_enum` + `RecvResult`/`TryResult` diff --git a/examples/0614-comptime-reify-enum.sx b/examples/0614-comptime-reify-enum.sx index 21612d9c..327be8b6 100644 --- a/examples/0614-comptime-reify-enum.sx +++ b/examples/0614-comptime-reify-enum.sx @@ -20,7 +20,7 @@ main :: () -> i32 { case .closed: { print("closed\n"); } } - c := E.closed; + c : E = .closed; if c == { case .value: (v) { print("value {}\n", v); } case .closed: { print("closed\n"); } diff --git a/examples/expected/0614-comptime-reify-enum.exit b/examples/expected/0614-comptime-reify-enum.exit index e69de29b..573541ac 100644 --- a/examples/expected/0614-comptime-reify-enum.exit +++ b/examples/expected/0614-comptime-reify-enum.exit @@ -0,0 +1 @@ +0 diff --git a/examples/expected/0614-comptime-reify-enum.stderr b/examples/expected/0614-comptime-reify-enum.stderr new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/examples/expected/0614-comptime-reify-enum.stderr @@ -0,0 +1 @@ + diff --git a/examples/expected/0614-comptime-reify-enum.stdout b/examples/expected/0614-comptime-reify-enum.stdout new file mode 100644 index 00000000..0074d08e --- /dev/null +++ b/examples/expected/0614-comptime-reify-enum.stdout @@ -0,0 +1,2 @@ +value 3 +closed diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 7d546f2f..96c609bd 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1703,6 +1703,7 @@ pub const Lowering = struct { pub const registerErrorSetDecl = lower_nominal.registerErrorSetDecl; pub const registerStructDecl = lower_nominal.registerStructDecl; pub const registerEnumDecl = lower_nominal.registerEnumDecl; + pub const reifyType = lower_nominal.reifyType; pub const registerUnionDecl = lower_nominal.registerUnionDecl; pub const qualifyAnonType = lower_nominal.qualifyAnonType; pub const nominalIdOf = lower_nominal.nominalIdOf; diff --git a/src/ir/lower/decl.zig b/src/ir/lower/decl.zig index 33eb6b68..b91b7543 100644 --- a/src/ir/lower/decl.zig +++ b/src/ir/lower/decl.zig @@ -651,15 +651,15 @@ pub fn scanDecls(self: *Lowering, decls: []const *const Node) void { .field_access => |fa| fa.field, else => "", }; - // `E :: reify(...)` — mint a nominal type from a `TypeInfo` - // and register `E` as an alias to it. The interpreter-side - // construction lands in Phase 0.2; until then bail LOUDLY - // and poison `E` to `.unresolved` (so downstream `E.value` - // gets a clean follow-on, not a silent default type). + // `E :: reify(...)` — mint a NEW nominal type from a + // `TypeInfo` literal and register `E` as an alias to it. + // `reifyType` builds the type (or diagnoses + returns null); + // either way `E` is bound (to the minted type, or poisoned + // to `.unresolved` so downstream `E.value` gets a clean + // follow-on rather than a silent default type). if (std.mem.eql(u8, callee_name, "reify")) { - if (self.diagnostics) |d| - d.addFmt(.err, cd.value.span, "reify is not yet implemented (REIFY Phase 0.2)", .{}); - self.putTypeAlias(self.current_source_file, cd.name, .unresolved); + const tid = self.reifyType(cd.name, call_data) orelse TypeId.unresolved; + self.putTypeAlias(self.current_source_file, cd.name, tid); continue; } // A namespaced callee (`ns.Box(..)`) is an explicit qualified diff --git a/src/ir/lower/generic.zig b/src/ir/lower/generic.zig index 50728f9f..a1c589e5 100644 --- a/src/ir/lower/generic.zig +++ b/src/ir/lower/generic.zig @@ -1219,15 +1219,14 @@ pub fn resolveTypeCallWithBindings(self: *Lowering, cl: *const ast.Call) TypeId .field_access => |fa| fa.field, else => return .unresolved, }; - // Comptime type-construction builtins (REIFY). `reify`/`field_type` - // appear in type position (`E :: reify(...)`, `field_type(T, i)` as a - // type arg). Until the interpreter-side construction lands (Phase 0.2 / - // Phase 2), bail LOUDLY rather than fall through to the misleading - // "unknown type 'reify'" diagnostic below — a silent default here would - // poison every downstream use of the type. + // Comptime type-construction builtins (REIFY). `reify` is minted in a + // `::` type-binding position by `decl.zig` (`E :: reify(...)`); reaching it + // HERE means an inline type position (`x : reify(...)`, a nested type arg), + // which Phase 0 does not support — bail LOUDLY rather than fall through to + // the misleading "unknown type 'reify'" diagnostic below. if (std.mem.eql(u8, callee_name, "reify")) { if (self.diagnostics) |d| - d.addFmt(.err, cl.callee.span, "reify is not yet implemented (REIFY Phase 0.2)", .{}); + d.addFmt(.err, cl.callee.span, "reify is only supported in a `::` type binding (e.g. `E :: reify(...)`) in Phase 0", .{}); return .unresolved; } if (std.mem.eql(u8, callee_name, "field_type")) { diff --git a/src/ir/lower/nominal.zig b/src/ir/lower/nominal.zig index d527c84e..cc8e503c 100644 --- a/src/ir/lower/nominal.zig +++ b/src/ir/lower/nominal.zig @@ -734,6 +734,100 @@ pub fn registerEnumDecl(self: *Lowering, ed: *const ast.EnumDecl) void { _ = self.internNamedTypeDecl(decl_key, name_id, info, nominal_id); } +/// REIFY Phase 0: mint a NEW nominal enum type from a `TypeInfo` literal passed +/// to `reify(...)`, registered under `type_name`. The argument shape this phase +/// supports is exactly the flat-enum literal: +/// +/// reify(.enum(.{ variants = .[ EnumVariant.{ name = "value", payload = i64 }, +/// EnumVariant.{ name = "closed", payload = void } ] })) +/// +/// The variant data is read DIRECTLY off the literal AST (Phase 0 reify takes a +/// comptime-known literal; the general interp-evaluated path is a later phase), +/// then handed to the SAME `buildEnumInfo` path source enums use — so the +/// minted type is byte-identical to an equivalent hand-written `enum { value: +/// i64; closed; }` and flows through enum codegen (layout / construct / match) +/// unmodified (Contract 2). Returns the minted `TypeId`, or null after emitting +/// a diagnostic if the argument is not a shape this phase can build (never a +/// silent default — REJECTED PATTERNS). +pub fn reifyType(self: *Lowering, type_name: []const u8, reify_call: *const ast.Call) ?TypeId { + const span = reify_call.callee.span; + if (reify_call.args.len != 1) return reifyBail(self, span, "reify expects exactly one TypeInfo argument"); + + // arg = `.enum(EnumInfo)` — an enum-literal applied as a call. + const arg = reify_call.args[0]; + if (arg.data != .call or arg.data.call.callee.data != .enum_literal) + return reifyBail(self, span, "reify Phase 0 supports only `.enum(...)` TypeInfo"); + const variant_kind = arg.data.call.callee.data.enum_literal.name; + if (!std.mem.eql(u8, variant_kind, "enum")) + return reifyBail(self, span, "reify Phase 0 supports only the `.enum` TypeInfo variant"); + if (arg.data.call.args.len != 1) + return reifyBail(self, span, "reify `.enum(...)` takes one EnumInfo payload"); + + // EnumInfo payload = `.{ variants = .[ ... ] }`. + const einfo = arg.data.call.args[0]; + if (einfo.data != .struct_literal) + return reifyBail(self, span, "reify `.enum(...)` payload must be an EnumInfo struct literal"); + const variants_node = fieldInitValue(&einfo.data.struct_literal, "variants") orelse + return reifyBail(self, span, "reify EnumInfo is missing the `variants` field"); + if (variants_node.data != .array_literal) + return reifyBail(self, span, "reify `variants` must be an array literal of EnumVariant"); + + // Each element = `EnumVariant.{ name = "...", payload = T }`. + var names = std.ArrayList([]const u8).empty; + var payloads = std.ArrayList(?*Node).empty; + for (variants_node.data.array_literal.elements) |elem| { + if (elem.data != .struct_literal) + return reifyBail(self, span, "reify variant must be an EnumVariant struct literal"); + const name_node = fieldInitValue(&elem.data.struct_literal, "name") orelse + return reifyBail(self, span, "reify EnumVariant is missing `name`"); + if (name_node.data != .string_literal) + return reifyBail(self, span, "reify EnumVariant `name` must be a string literal"); + const payload_node = fieldInitValue(&elem.data.struct_literal, "payload") orelse + return reifyBail(self, span, "reify EnumVariant is missing `payload`"); + names.append(self.alloc, name_node.data.string_literal.raw) catch return null; + payloads.append(self.alloc, payload_node) catch return null; + } + if (names.items.len == 0) + return reifyBail(self, span, "reify enum has no variants"); + + // Hand the synthesized decl to the shared enum body-builder (`self` is the + // visibility-aware payload-type resolver, as in registerEnumDecl). A + // payload that resolves to `.void` becomes a tagless variant (`closed`), + // exactly as a source `enum { … ; closed; }` would. + const ed = ast.EnumDecl{ + .name = type_name, + .variant_names = names.items, + .variant_types = payloads.items, + .is_flags = false, + .variant_values = &.{}, + .backing_type = null, + .is_raw = false, + }; + const table = &self.module.types; + const info = type_bridge.buildEnumInfo(&ed, table, self); + const name_id = table.internString(type_name); + const tid = table.findByName(name_id) orelse table.internNominal(info, 0); + table.updatePreservingKey(tid, info); + return tid; +} + +/// Emit a reify diagnostic and return null — the single loud-failure exit for +/// `reifyType` (no silent default ever reaches the type table). +fn reifyBail(self: *Lowering, span: ?ast.Span, comptime msg: []const u8) ?TypeId { + if (self.diagnostics) |d| d.addFmt(.err, span, msg, .{}); + return null; +} + +/// The value node of a named field init in a struct literal, or null if absent. +fn fieldInitValue(lit: *const ast.StructLiteral, name: []const u8) ?*Node { + for (lit.field_inits) |fi| { + if (fi.name) |n| { + if (std.mem.eql(u8, n, name)) return fi.value; + } + } + return null; +} + /// Register a top-level UNION decl under a per-decl nominal identity (E6a) — /// the union twin of `registerEnumDecl` / `registerStructDecl`. pub fn registerUnionDecl(self: *Lowering, ud: *const ast.UnionDecl) void {