interp: materialize zero values with explicit continuations

This commit is contained in:
dev committed 2026-10-09 21:38:59 +03:00
1 parent 9549a3dec6
commit b1b9b4cf03
6 files changed
+354 -19

No files matched your search

+146 -17
View File
@@ -1514,23 +1514,55 @@ const Machine = struct {
return out;
}
fn zeroValue(m: *Machine, t: air.Type) std.mem.Allocator.Error!Value {
return switch (t) {
.int => |it| .{ .int = .{ .ty = it, .bits = 0 } },
.bool => .{ .boolean = false },
.array => |a| blk: {
const items = try m.heap().alloc(Value, a.len);
for (items) |*x| x.* = try m.zeroValue(a.elem);
break :blk .{ .array = items };
},
.named => |i| blk: {
const fields = m.module.types[i].kind.@"struct";
const out = try m.heap().alloc(Value, fields.len);
for (fields, out) |fd, *o| o.* = try m.zeroValue(fd.ty);
break :blk .{ .aggregate = .{ .decl = i, .variant = 0, .fields = out } };
},
else => unreachable, // verified zeroable
};
fn zeroValue(m: *Machine, initial: air.Type) std.mem.Allocator.Error!Value {
// Payloads live in the execution heap; traversal state is temporary
// host bookkeeping, discarded before the instruction's safe point.
// Only pending siblings need a continuation, not single-child edges.
const ZeroFrame = struct { ty: air.Type, out: []Value, next: usize };
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer tmp.deinit();
var frames: std.ArrayList(ZeroFrame) = .empty;
var result: Value = undefined;
var out = &result;
var ty = initial;
while (true) {
switch (ty) {
.int => |it| out.* = .{ .int = .{ .ty = it, .bits = 0 } },
.bool => out.* = .{ .boolean = false },
.array => |a| {
const items = try m.heap().alloc(Value, a.len);
out.* = .{ .array = items };
if (items.len != 0) {
if (items.len > 1) try frames.append(tmp.allocator(), .{ .ty = ty, .out = items, .next = 1 });
ty = a.elem;
out = &items[0];
continue;
}
},
.named => |i| {
const fields = m.module.types[i].kind.@"struct";
const items = try m.heap().alloc(Value, fields.len);
out.* = .{ .aggregate = .{ .decl = i, .variant = 0, .fields = items } };
if (items.len != 0) {
if (items.len > 1) try frames.append(tmp.allocator(), .{ .ty = ty, .out = items, .next = 1 });
ty = fields[0].ty;
out = &items[0];
continue;
}
},
else => unreachable, // verified zeroable
}
if (frames.items.len == 0) return result;
const f = &frames.items[frames.items.len - 1];
out = &f.out[f.next];
ty = switch (f.ty) {
.array => |a| a.elem,
.named => |i| m.module.types[i].kind.@"struct"[f.next].ty,
else => unreachable,
};
f.next += 1;
if (f.next == f.out.len) _ = frames.pop();
}
}
fn placePtr(p: Value.Place) *Value {
@@ -2535,6 +2567,103 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
const h = "module t\nair 0\nlang 0.1\nfeatures []\n";
test "zero construction handles deep arrays and named structures with pending siblings" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const depth = 32768;
const chain = try arena.alloc(air.Type, depth + 1);
const arrays = try arena.alloc(air.Type.Array, depth);
chain[0] = .{ .int = .u8 };
for (chain[1..], arrays, 1..) |*ty, *a, i| {
a.* = .{ .elem = chain[i - 1], .len = 1 };
ty.* = .{ .array = a };
}
var module: air.Module = .{ .name = "zero", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) };
m.exec_heap.space = .init(std.testing.allocator);
defer m.exec_heap.space.deinit();
var v = try m.zeroValue(chain[depth]);
for (0..depth) |_| {
try std.testing.expect(v == .array and v.array.len == 1);
v = v.array[0];
}
try std.testing.expect(v == .int and v.int.ty == .u8 and v.int.bits == 0);
// Each frame has heterogeneous siblings after its deep first field;
// the leaf also covers an empty record and a multi-element array.
const declarations = try arena.alloc(air.TypeDecl, depth + 1);
const three_bytes: air.Type.Array = .{ .elem = chain[0], .len = 3 };
declarations[0] = .{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } };
for (declarations[1..], 1..) |*decl, i| {
const fields = try arena.alloc(@import("../air/module.zig").Field, 3);
fields[0] = .{ .name = "child", .ty = .{ .named = @intCast(i - 1) } };
fields[1] = .{ .name = "flag", .ty = .bool };
fields[2] = .{ .name = "bytes", .ty = .{ .array = &three_bytes } };
decl.* = .{ .name = "Node", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = fields } };
}
module.types = declarations;
m.module = module;
v = try m.zeroValue(.{ .named = depth });
var i: usize = depth;
while (i != 0) : (i -= 1) {
try std.testing.expect(v == .aggregate and v.aggregate.decl == i and v.aggregate.variant == 0);
const fields = v.aggregate.fields;
try std.testing.expectEqual(@as(usize, 3), fields.len);
try std.testing.expect(fields[1] == .boolean and !fields[1].boolean);
try std.testing.expectEqual(@as(usize, 3), fields[2].array.len);
for (fields[2].array) |x| try std.testing.expect(x.int.ty == .u8 and x.int.bits == 0);
v = fields[0];
}
try std.testing.expect(v.aggregate.decl == 0 and v.aggregate.fields.len == 0);
}
test "failed zero construction does not publish a partially initialized local" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const byte: air.Type = .{ .int = .u8 };
const inner: air.Type = .{ .array = &.{ .elem = byte, .len = 16 } };
const ty: air.Type = .{ .array = &.{ .elem = inner, .len = 1 } };
const module: air.Module = .{ .name = "zero", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) };
var buf: [512]u8 = undefined;
var fixed: std.heap.FixedBufferAllocator = .init(&buf);
m.exec_heap.space = .init(fixed.allocator());
defer m.exec_heap.space.deinit();
var cell: Value.Cell = .{ .value = .{ .boolean = true }, .ty = ty };
var vals = [_]Value{.{ .local = &cell }};
const inst: air.Inst = .{ .span = .{ .line = 1, .col = 1 }, .result = null, .op = .{ .local_zero = 0 } };
try std.testing.expectError(error.OutOfMemory, m.execMemory(&vals, inst));
try std.testing.expect(fixed.end_index != 0); // root allocated, child failed
try std.testing.expect(cell.value == .boolean and cell.value.boolean);
}
test "deep zero materialization is one instruction under the ordinary collection threshold" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var src: std.ArrayList(u8) = .empty;
try src.appendSlice(arena, "module zero.fuel\nair 0\nlang 0.1\nfeatures [arrays, ownership]\nfn @main() -> void\neffects []\nentry:\n %p = local.alloc ");
for (0..32768) |_| try src.appendSlice(arena, "array<");
try src.appendSlice(arena, "u8");
for (0..32768) |_| try src.appendSlice(arena, ",1>");
try src.appendSlice(arena, "\n local.zero %p\n ret\n");
const checked = try check.checkAir(arena, "zero-fuel.air", src.items);
try std.testing.expect(checked.status == .accepted);
for (0..4) |fuel| {
var stats: MemoryStats = .{};
const outcome = try run(arena, checked.module.?, "main", .{ .fuel = fuel, .memory = &stats });
try std.testing.expectEqual(@as(u64, fuel), stats.steps);
if (fuel < 3) {
try std.testing.expect(outcome == .limit_exceeded);
try std.testing.expectEqual(@as(u64, fuel), outcome.limit_exceeded.steps);
try std.testing.expectEqual(@as(u64, fuel), outcome.limit_exceeded.limit);
try std.testing.expectEqualStrings("fuel", outcome.limit_exceeded.kind);
} else try std.testing.expect(outcome == .returned and outcome.returned == .void);
}
}
fn main1(comptime ret: []const u8, comptime insts: []const u8) []const u8 {
return h ++ "fn @main() -> " ++ ret ++ "\neffects []\nentry:\n" ++ insts;
}