From 936d65359c063a722aad7e3d546f5d74f35a15e8 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 14:44:48 +0300 Subject: [PATCH] cli: convert source types to AIR iteratively --- docs/design/air-type-depth-audit.md | 8 + docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 6 + src/frontend/lower.zig | 248 ++++++++++++++++++++++++--- 4 files changed, 240 insertions(+), 24 deletions(-) diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index a8bfdd1..a9c8505 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -164,3 +164,11 @@ The 65,536-array invalid-atomic source's confirmed typeText abort is repaired by Independent shallow tests compare 3,696 canonical/diagnostic outputs and feature states against the old printer, covering every wrapper/leaf, nominal display-name fallbacks and zero/max-u64 array lengths. A 65,536-level mixed chain has independently assembled exact text in both modes. Allocation failures cover direct printing, diagnostics and local AIR emission, with arena cleanup and no fabricated diagnostic/partial instruction; constant leaves retain the allocation-free path. Units and format checks pass. Repair-advice/nonvalue/static-function CLI integration passes 299/635/25 checks; all 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage. The formerly aborting invalid-atomic check now returns exactly one E7005 at 2:9 without stderr; its complete found type is byte-identical to the independent 655,362-byte expectation. A separate correct 65,536-array parameter check accepts without output. A struct field containing 16,384 arrays then confirms remaining native recursion in source-to-AIR type conversion: 4,425 airType frames, exit -6, no JSON. Only child core capture is disabled, and no timeout ends a probe. Source-to-AIR repair, Ty equality and closing query paths keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic guard or accepted-depth limit is introduced. No fresh Claude review is claimed. + +## Source-to-AIR type conversion + +The confirmed 16,384-array struct-member airType failure is repaired by an iterative output-target cursor. Array/wrapper nodes are allocated in the original outer-to-inner order; each target is the local root or stable newly owned output storage, never source Ty storage. Only the completed root is returned. A failed allocation propagates host OutOfMemory without publishing a partial type/module; already allocated nodes remain in the caller's arena as before. There is no work buffer, new metadata allocation or API change. Leaf indices, wrappers, array lengths, feature/ownership effects and all source/verifier rules remain unchanged. + +Independent shallow comparison covers 2,352 leaf/array/wrapper shapes, every registered capability and internal wrapper, plus allocation-free leaves. A 65,536-level mixed conversion is inspected and freed iteratively; exactly one output allocation per constructor proves no additional work allocation or borrowed source node. Per-node request lengths/alignments, OOM points, byte/allocation counts and cleanup match the old recursive derivation on a 64-level mixed type. Arena backing growth is deliberately not an equivalence oracle: in-place resize availability can differ between two arenas. Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact corpus coverage and old/new checks/lowerings (1,421/506) pass. + +Complete checks of structs with 16,384 and 65,536 array levels now accept without output. A separate 65,536-level source return-equality input confirms the next native failure in Ty.eql (10,001 frames, exit -6, no JSON). Core capture alone is disabled; no timeout ends a probe. Source equality and closing query paths keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No normative/bundle/feature/code, runtime/effect/ownership or accepted-depth limit changes. No fresh Claude review is claimed. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index cceaef9..446f1bb 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -487,6 +487,8 @@ The [source nominal property increment](air-type-depth-audit.md#source-nominal-p The [source type text increment](air-type-depth-audit.md#source-type-text-repair) repairs the confirmed diagnostic printing failure with iterative prefix/suffix output and exact canonical/source naming. Host OOM propagates instead of supplying fabricated type strings. The deep invalid atomic now returns E7005 with its complete found type, and a correct 65,536-array parameter accepts. A 16,384-array struct member independently confirms the remaining airType native-stack failure. Source-to-AIR repair, Ty equality and closing query audits still keep Q-059 open. No semantic limit or rule changes. +The [source-to-AIR conversion increment](air-type-depth-audit.md#source-to-air-type-conversion) repairs airType using a constant-state target cursor with the same constructor allocations and host-error behavior. Deep struct-member checks now accept; an independent return-equality probe confirms Ty.eql native-stack exhaustion at 65,536 array levels. Source equality and closing query work keep Q-059 open; no accepted-depth limit or semantic rule changes. + ## Q-060 — Native recursion while materializing runtime values The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index c584c03..a38becc 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -484,3 +484,9 @@ Units/format checks, nominal/Copy-content/static-function integration (110/119/2 The [Q-059 source text increment](../design/air-type-depth-audit.md#source-type-text-repair) removes recursive and repeatedly copied ancestor strings, preserving exact spelling/source nominal names and resource feature discovery. Its internal fallible APIs propagate host OOM instead of generating shortened type facts or AIR. The formerly aborting deep invalid-atomic check returns one E7005 with the complete 655,362-byte found type. Units/format checks, 3,696 independent shallow comparisons, deep mixed output and failed-allocation/cleanup tests pass. Repair-advice/nonvalue/static-function integration (299/635/25) and old/new source checks/lowerings (1,421/506) pass; all 1,791 conformance cases pass with exact corpus coverage. A correct 65,536-array parameter accepts; a 16,384-array struct member independently confirms remaining airType native-stack failure. Source-to-AIR repair, Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. + +## Source-to-AIR type conversion (2026-10-10) + +The [Q-059 conversion increment](../design/air-type-depth-audit.md#source-to-air-type-conversion) replaces native recursion with an output-target cursor, preserving source/AIR type shape, constructor allocation order and error publication. Structs with 16,384/65,536 array levels now pass complete checking. Tests cover 2,352 independent shallow comparisons, 65,536-level construction without work allocation, and per-node OOM/order/cleanup equivalence. + +Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact coverage and old/new checks/lowerings (1,421/506) pass. A separate return-equality input confirms the next failure in Ty.eql at 65,536 array levels. Equality/closing query checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index a83dcfb..c1be946 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -580,30 +580,43 @@ const Lowerer = struct { for (l.fns.items) |f| try l.emitFunction(f); } - fn airType(l: *Lowerer, t: Ty) Error!air_module.Type { - return switch (t) { - .int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? }, - .named => |i| .{ .named = i }, - .cap => |k| .{ .cap = authority.kindIndex(k).? }, - .builtin => |b| .{ .builtin = b }, - .resource => |r| .{ .resource = r }, - .array => |a| blk: { - const out = try l.arena.create(air_module.Type.Array); - out.* = .{ .elem = try l.airType(a.elem), .len = a.len }; - break :blk .{ .array = out }; - }, - inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: { - const out = try l.arena.create(air_module.Type); - out.* = try l.airType(inner.*); - break :blk @unionInit(air_module.Type, @tagName(tag), out); - }, - .bool => .bool, - .void => .void, - .never => .never, - .region => .region, - .scope => .scope, - .shield => .shield, - }; + fn airType(l: *Lowerer, annotation: Ty) Error!air_module.Type { + var root: air_module.Type = undefined; + var target = &root; + var t = annotation; + // Allocate in the original outer-to-inner order. Only the completed + // root is returned; targets point at stable output storage, never Ty. + while (true) { + target.* = switch (t) { + .array => |a| { + const out = try l.arena.create(air_module.Type.Array); + out.len = a.len; + target.* = .{ .array = out }; + target = &out.elem; + t = a.elem; + continue; + }, + inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| { + const out = try l.arena.create(air_module.Type); + target.* = @unionInit(air_module.Type, @tagName(tag), out); + target = out; + t = inner.*; + continue; + }, + .int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? }, + .named => |i| .{ .named = i }, + .cap => |k| .{ .cap = authority.kindIndex(k).? }, + .builtin => |b| .{ .builtin = b }, + .resource => |r| .{ .resource = r }, + .bool => .bool, + .void => .void, + .never => .never, + .region => .region, + .scope => .scope, + .shield => .shield, + }; + return root; + } } fn checkRequirements(l: *Lowerer) Error!void { @@ -4652,3 +4665,190 @@ test "source type text OOM reaches diagnostics and emission without fallback tex try std.testing.expect(l.uses.contains(.resources)); try std.testing.expect(!failing.has_induced_failure); } + +// Independent old conversion, used only on shallow test types. +const ReferenceAirType = struct { + fn airType(l: *Lowerer, t: Ty) Error!air_module.Type { + return switch (t) { + .int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? }, + .named => |i| .{ .named = i }, + .cap => |k| .{ .cap = authority.kindIndex(k).? }, + .builtin => |b| .{ .builtin = b }, + .resource => |r| .{ .resource = r }, + .array => |a| blk: { + const out = try l.arena.create(air_module.Type.Array); + out.* = .{ .elem = try ReferenceAirType.airType(l, a.elem), .len = a.len }; + break :blk .{ .array = out }; + }, + inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: { + const out = try l.arena.create(air_module.Type); + out.* = try ReferenceAirType.airType(l, inner.*); + break :blk @unionInit(air_module.Type, @tagName(tag), out); + }, + .bool => .bool, + .void => .void, + .never => .never, + .region => .region, + .scope => .scope, + .shield => .shield, + }; + } +}; + +fn expectAirTypeMatches(a: Allocator, t: Ty) !void { + const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} }; + var original: Lowerer = .{ .arena = a, .m = m }; + var current: Lowerer = .{ .arena = a, .m = m }; + try std.testing.expect((try ReferenceAirType.airType(&original, t)).eql(try current.airType(t))); + try std.testing.expectEqualDeep(original.uses, current.uses); +} + +test "source AIR conversion matches the independent shallow derivation" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} }; + var builder: Lowerer = .{ .arena = a, .m = m }; + var leaves: std.ArrayList(Ty) = .empty; + for (int_types) |n| try leaves.append(a, .{ .int = n }); + try leaves.appendSlice(a, &.{ .bool, .void, .never, .region, .scope, .shield, .{ .named = 0 }, .{ .named = 123 } }); + for (authority.kinds) |kind| try leaves.append(a, .{ .cap = kind.name }); + inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) }); + inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) }); + var comparisons: usize = 0; + for (leaves.items) |leaf| { + try expectAirTypeMatches(a, leaf); + comparisons += 1; + for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| { + try expectAirTypeMatches(a, try builder.arrayOf(leaf, length)); + comparisons += 1; + } + inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) { + const wrapped = try builder.wrap(@field(std.meta.Tag(Ty), name), leaf); + try expectAirTypeMatches(a, wrapped); + try expectAirTypeMatches(a, try builder.arrayOf(wrapped, 123)); + try expectAirTypeMatches(a, try builder.wrap(@field(std.meta.Tag(Ty), name), try builder.arrayOf(leaf, 456))); + comparisons += 3; + }; + } + try std.testing.expectEqual(@as(usize, 2352), comparisons); +} + +test "source AIR conversion builds deep trees without work metadata" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} }; + var builder: Lowerer = .{ .arena = a, .m = m }; + var ty: Ty = .{ .int = "u8" }; + const count = 65_536; + for (0..count) |i| ty = if (i % 2 == 0) try builder.arrayOf(ty, i + 1) else try builder.wrap(.ref, ty); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + var output: Lowerer = .{ .arena = failing.allocator(), .m = m }; + const root = try output.airType(ty); + var current = root; + // Free output nodes in this test only; production uses the caller arena. + var remaining: usize = count; + while (remaining != 0) { + remaining -= 1; + if (remaining % 2 == 0) { + try std.testing.expect(current == .array); + const node = current.array; + try std.testing.expectEqual(@as(u64, remaining + 1), node.len); + current = node.elem; + failing.allocator().destroy(node); + } else { + try std.testing.expect(current == .ref); + const node = current.ref; + current = node.*; + failing.allocator().destroy(node); + } + } + try std.testing.expectEqual(air_module.IntType.u8, current.int); + try std.testing.expectEqual(@as(usize, count), failing.allocations); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + // No pointer in the output was borrowed from the source tree. + // Leaf-only conversion retains the allocation-free original path. + var no_alloc: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + var leaf: Lowerer = .{ .arena = no_alloc.allocator(), .m = m }; + try std.testing.expectEqual(@as(u32, 17), (try leaf.airType(.{ .named = 17 })).named); + try std.testing.expect(!no_alloc.has_induced_failure); +} + +test "source AIR conversion preserves allocation order and OOM publication" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} }; + var builder: Lowerer = .{ .arena = a, .m = m }; + var deep: Ty = .{ .resource = .file_read }; + for (0..64) |i| deep = if (i % 2 == 0) try builder.arrayOf(deep, std.math.maxInt(u64)) else try builder.wrap(.own, deep); + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index <= 64); + var old_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var new_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var old_nodes: AirConversionAllocations = .{ .backing = old_fail.allocator() }; + defer old_nodes.deinit(); + var new_nodes: AirConversionAllocations = .{ .backing = new_fail.allocator() }; + defer new_nodes.deinit(); + var original: Lowerer = .{ .arena = old_nodes.allocator(), .m = m }; + var current: Lowerer = .{ .arena = new_nodes.allocator(), .m = m }; + const before = ReferenceAirType.airType(&original, deep); + const after = current.airType(deep); + try std.testing.expectEqual(old_fail.has_induced_failure, new_fail.has_induced_failure); + if (new_fail.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, before); + try std.testing.expectError(error.OutOfMemory, after); + try std.testing.expect(current.property_module == null); + try std.testing.expect(current.problem == null); + } else { + try std.testing.expect((try before).eql(try after)); + } + try std.testing.expectEqual(old_nodes.count, new_nodes.count); + for (old_nodes.nodes[0..old_nodes.count], new_nodes.nodes[0..new_nodes.count]) |old_node, new_node| { + try std.testing.expectEqual(old_node.length, new_node.length); + try std.testing.expectEqual(old_node.alignment, new_node.alignment); + } + try std.testing.expectEqual(old_fail.allocated_bytes, new_fail.allocated_bytes); + try std.testing.expectEqual(old_fail.allocations, new_fail.allocations); + old_nodes.deinit(); + new_nodes.deinit(); + try std.testing.expectEqual(old_fail.allocated_bytes, old_fail.freed_bytes); + try std.testing.expectEqual(new_fail.allocated_bytes, new_fail.freed_bytes); + if (!new_fail.has_induced_failure) break; + } +} + +// Records direct node requests. Arena growth/resize decisions depend on the +// backing allocator and are not an oracle of constructor allocation order. +const AirConversionAllocations = struct { + backing: Allocator, + nodes: [128]struct { pointer: ?[*]u8, length: usize, alignment: std.mem.Alignment } = undefined, + count: usize = 0, + + fn allocator(self: *@This()) Allocator { + return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn alloc(raw: *anyopaque, length: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(raw)); + std.debug.assert(self.count < self.nodes.len); + const pointer = self.backing.rawAlloc(length, alignment, ret_addr); + self.nodes[self.count] = .{ .pointer = pointer, .length = length, .alignment = alignment }; + self.count += 1; + return pointer; + } + fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool { + return false; + } + fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 { + return null; + } + fn free(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize) void { + unreachable; // Conversion transfers nodes to the caller, never frees them. + } + fn deinit(self: *@This()) void { + for (self.nodes[0..self.count]) |node| if (node.pointer) |ptr| self.backing.rawFree(ptr[0..node.length], node.alignment, @returnAddress()); + self.count = 0; + } +};