interp: copy aggregate value trees without native recursion

This commit is contained in:
dev committed 2026-10-09 21:52:08 +03:00
1 parent b1b9b4cf03
commit afc40f8502
6 files changed
+367 -7

No files matched your search

+161 -7
View File
@@ -1500,12 +1500,45 @@ const Machine = struct {
/// Values in storage never share structure with SSA values, so every
/// transfer between the two copies aggregates and arrays.
fn deepCopy(m: *Machine, v: Value) std.mem.Allocator.Error!Value {
return switch (v) {
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try m.copyAll(a.fields) } },
.array => |items| .{ .array = try m.copyAll(items) },
else => v,
};
fn deepCopy(m: *Machine, initial: Value) std.mem.Allocator.Error!Value {
// Every occurrence gets independent aggregate/array storage, even
// when source payloads are shared. Handles and places retain identity.
// Collection cannot run inside an instruction; all source pointers
// remain valid while the new value is built in the execution heap.
const CopyFrame = struct { source: []const Value, out: []Value, next: usize };
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer tmp.deinit();
var frames: std.ArrayList(CopyFrame) = .empty;
var result: Value = undefined;
var out = &result;
var value = initial;
while (true) {
const source: ?[]const Value = switch (value) {
.aggregate => |a| a.fields,
.array => |items| items,
else => null,
};
if (source) |items| {
const copied = try m.heap().alloc(Value, items.len);
out.* = switch (value) {
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = copied } },
.array => .{ .array = copied },
else => unreachable,
};
if (items.len != 0) {
if (items.len > 1) try frames.append(tmp.allocator(), .{ .source = items, .out = copied, .next = 1 });
value = items[0];
out = &copied[0];
continue;
}
} else out.* = value;
if (frames.items.len == 0) return result;
const f = &frames.items[frames.items.len - 1];
value = f.source[f.next];
out = &f.out[f.next];
f.next += 1;
if (f.next == f.out.len) _ = frames.pop();
}
}
fn copyAll(m: *Machine, items: []const Value) std.mem.Allocator.Error![]Value {
@@ -2567,6 +2600,111 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
const h = "module t\nair 0\nlang 0.1\nfeatures []\n";
test "deep copying preserves metadata and separates every payload occurrence" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const module: air.Module = .{ .name = "copy", .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();
const depth = 32768;
var root: Value = .{ .int = .{ .ty = .i16, .bits = 0xfffa } };
for (1..depth + 1) |i| {
const fields = try m.heap().alloc(Value, if (i % 2 == 0) 1 else 3);
fields[0] = root;
if (fields.len == 1) {
root = .{ .array = fields };
} else {
fields[1] = .{ .boolean = true };
fields[2] = .{ .aggregate = .{ .decl = 0, .variant = 0, .fields = &.{} } };
root = .{ .aggregate = .{ .decl = @intCast(i), .variant = @intCast(i % 3), .fields = fields } };
}
}
const copies = try m.copyAll(&.{ root, root });
for (copies) |copy| {
var original = root;
var copied = copy;
var i: usize = depth;
while (i != 0) : (i -= 1) {
if (i % 2 == 0) {
try std.testing.expect(original.array.ptr != copied.array.ptr);
try std.testing.expectEqual(@as(usize, 1), copied.array.len);
original = original.array[0];
copied = copied.array[0];
} else {
try std.testing.expect(original.aggregate.fields.ptr != copied.aggregate.fields.ptr);
try std.testing.expectEqual(original.aggregate.decl, copied.aggregate.decl);
try std.testing.expectEqual(original.aggregate.variant, copied.aggregate.variant);
try std.testing.expectEqual(@as(usize, 3), copied.aggregate.fields.len);
try std.testing.expect(copied.aggregate.fields[1].boolean);
const empty = copied.aggregate.fields[2].aggregate;
try std.testing.expect(empty.decl == 0 and empty.variant == 0 and empty.fields.len == 0);
original = original.aggregate.fields[0];
copied = copied.aggregate.fields[0];
}
}
try std.testing.expect(copied.int.ty == .i16 and copied.int.bits == 0xfffa);
}
var leaf0 = &copies[0];
var leaf1 = &copies[1];
var source_leaf = &root;
for (0..depth) |_| {
leaf0 = if (leaf0.* == .array) &leaf0.array[0] else &leaf0.aggregate.fields[0];
leaf1 = if (leaf1.* == .array) &leaf1.array[0] else &leaf1.aggregate.fields[0];
source_leaf = if (source_leaf.* == .array) &source_leaf.array[0] else &source_leaf.aggregate.fields[0];
}
leaf0.int.bits = 42;
try std.testing.expect(leaf1.int.bits == 0xfffa and source_leaf.int.bits == 0xfffa);
// Repeated payloads within one value must also be separated. Identity
// handles are intentionally shallow, unlike aggregate/array storage.
var cell: Value.Cell = .{ .value = .{ .boolean = true }, .ty = .bool };
var mutex: Value.MutexCell = .{ .locked = true, .cell = &cell };
var graph: Value.Graph = .{ .id = 7, .authority = 0, .bytes = 1 };
const shared = try m.heap().alloc(Value, 1);
shared[0] = .{ .int = .{ .ty = .u8, .bits = 9 } };
const payload = try m.heap().alloc(Value, 5);
payload[0] = .{ .array = shared };
payload[1] = .{ .array = shared };
payload[2] = .{ .own = &cell };
payload[3] = .{ .mutex = &mutex };
payload[4] = .{ .graph = &graph };
const copy = try m.deepCopy(.{ .array = payload });
try std.testing.expect(copy.array[0].array.ptr != copy.array[1].array.ptr);
copy.array[0].array[0].int.bits = 3;
try std.testing.expect(copy.array[1].array[0].int.bits == 9 and shared[0].int.bits == 9);
try std.testing.expect(copy.array[2].own == &cell and copy.array[3].mutex == &mutex and copy.array[4].graph == &graph);
}
test "failed local store retains its original complete payload" {
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 = "copy", .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();
const old = try arena.alloc(Value, 16);
@memset(old, .{ .int = .{ .ty = .u8, .bits = 8 } });
const incoming = try arena.alloc(Value, 16);
@memset(incoming, .{ .int = .{ .ty = .u8, .bits = 9 } });
var old_outer = [_]Value{.{ .array = old }};
var new_outer = [_]Value{.{ .array = incoming }};
var cell: Value.Cell = .{ .value = .{ .array = &old_outer }, .ty = ty };
var vals = [_]Value{ .{ .local = &cell }, .{ .array = &new_outer } };
const inst: air.Inst = .{ .span = .{ .line = 1, .col = 1 }, .result = null, .op = .{ .local_store = .{ .local = 0, .value = 1 } } };
try std.testing.expectError(error.OutOfMemory, m.execMemory(&vals, inst));
try std.testing.expect(fixed.end_index != 0);
try std.testing.expect(cell.value.array.ptr == old_outer[0..].ptr);
for (cell.value.array[0].array) |v| try std.testing.expect(v.int.bits == 8);
}
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();
@@ -2639,7 +2777,7 @@ test "failed zero construction does not publish a partially initialized local" {
try std.testing.expect(cell.value == .boolean and cell.value.boolean);
}
test "deep zero materialization is one instruction under the ordinary collection threshold" {
test "deep zero and local-load copying count as single instructions at the ordinary collection threshold" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
@@ -2648,6 +2786,7 @@ test "deep zero materialization is one instruction under the ordinary collection
for (0..32768) |_| try src.appendSlice(arena, "array<");
try src.appendSlice(arena, "u8");
for (0..32768) |_| try src.appendSlice(arena, ",1>");
const body_start = src.items.len;
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);
@@ -2662,6 +2801,21 @@ test "deep zero materialization is one instruction under the ordinary collection
try std.testing.expectEqualStrings("fuel", outcome.limit_exceeded.kind);
} else try std.testing.expect(outcome == .returned and outcome.returned == .void);
}
src.items.len = body_start;
try src.appendSlice(arena, "\n local.zero %p\n %v = local.load %p\n ret\n");
const copying = try check.checkAir(arena, "copy-fuel.air", src.items);
try std.testing.expect(copying.status == .accepted);
for (0..5) |fuel| {
var stats: MemoryStats = .{};
const outcome = try run(arena, copying.module.?, "main", .{ .fuel = fuel, .memory = &stats });
try std.testing.expectEqual(@as(u64, fuel), stats.steps);
if (fuel < 4) {
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 {