cli: transform generic source ASTs iteratively

This commit is contained in:
dev committed 2026-10-10 19:07:06 +03:00
1 parent 50a7575efb
commit d39a422b2b
5 files changed
+978 -89

No files matched your search

+816 -80
View File
@@ -546,43 +546,69 @@ const Generator = struct {
return false;
}
fn expression(g: *Generator, e: ast.Expr, env: Env) Error!ast.Expr {
var out = e;
// Entries borrow immutable input storage and write fresh, arena-owned
// output. Neither side points into a copied union payload or queue entry.
// Re-entry through instantiate/ty retains their existing depth guards.
const WalkWork = union(enum) {
visit: struct {
input: *const anyopaque,
output: *anyopaque,
env: Env,
run: *const fn (*Generator, *std.ArrayList(WalkWork), *const anyopaque, *anyopaque, Env) Error!void,
},
call: struct {
input: *const ast.Expr,
output: *ast.Expr,
env: Env,
phase: enum { after_type, after_callee },
name: ?[]const u8 = null,
},
argument: struct {
input: *const ast.Expr,
output: *ast.Expr,
env: Env,
index: usize,
name: ?[]const u8,
},
};
fn queueWalk(g: *Generator, pending: *std.ArrayList(WalkWork), comptime T: type, input: *const T, output: *T, env: Env) A.Error!void {
if (T == ast.Span) {
output.* = input.*;
return;
}
switch (@typeInfo(T)) {
.@"struct", .@"union", .optional => {},
.pointer => |info| if (info.child == u8) {
output.* = input.*;
return;
},
else => {
output.* = input.*;
return;
},
}
try pending.append(g.arena, .{ .visit = .{ .input = @ptrCast(input), .output = @ptrCast(output), .env = env, .run = WalkVisitor(T).visit } });
}
fn expression(g: *Generator, pending: *std.ArrayList(WalkWork), input: *const ast.Expr, out: *ast.Expr, env: Env) Error!void {
const e = input.*;
out.* = e;
if (e.kind == .move and env.params.len != 0) out.generic_transfer = true;
switch (e.kind) {
.name => |name| if (boundFunction(env, name) != null) return g.invalid(.invalid_static_function, e.span, "static function parameter is only a call target or named worker", name),
.specialize => |x| {
const name = path(g.arena, x.base.*) catch return error.OutOfMemory;
const name = try path(g.arena, x.base.*);
if (name) |n| if (boundFunction(env, n) != null) return g.invalid(.invalid_static_function, e.span, "bound static function cannot be specialized again", n);
const d = g.function(name orelse return g.invalid(.invalid_generic, e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) };
out.span.resolved = true;
return out;
return;
},
.call => |x| {
out.kind.call.type_arg = try g.walk(?ast.Type, x.type_arg, env);
const callee_name = try path(g.arena, x.callee.*);
if (callee_name) |name| if (boundFunction(env, name)) |arg| {
out.kind.call.callee = try g.box(ast.Expr, selectedExpr(x.callee.*, arg));
out.kind.call.args = try g.walk([]const ast.Expr, x.args, env);
return out;
};
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try path(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| {
if (d.generics.len != 0) return g.invalid(.invalid_generic, e.span, "generic function needs explicit arguments", name);
};
out.kind.call.callee = try g.box(ast.Expr, try g.expression(x.callee.*, env));
const args = try g.arena.alloc(ast.Expr, x.args.len);
for (x.args, args, 0..) |arg, *target, i| {
if (i == 1 and callee_name != null and std.mem.eql(u8, callee_name.?, "task.spawn")) {
if (try path(g.arena, arg)) |name| if (boundFunction(env, name)) |selected| {
target.* = selectedExpr(arg, selected);
continue;
};
}
target.* = try g.expression(arg, env);
}
out.kind.call.args = args;
return out;
.call => {
try pending.append(g.arena, .{ .call = .{ .input = input, .output = out, .env = env, .phase = .after_type } });
try g.queueWalk(pending, ?ast.Type, &input.kind.call.type_arg, &out.kind.call.type_arg, env);
return;
},
.variant => |x| {
const t = try g.named(x.@"enum", x.type_args, e.span, env);
@@ -590,21 +616,119 @@ const Generator = struct {
out.kind.variant.@"enum" = t.kind.name;
out.kind.variant.type_args = &.{};
out.span.resolved = t.span.resolved;
return out;
return;
},
.struct_lit => |x| {
const t = try g.named(x.name, x.type_args, e.span, env);
if (t.kind != .name) return g.fail("E7005", e.span, "struct constructor requires a named type", x.name);
out.kind.struct_lit.name = t.kind.name;
out.kind.struct_lit.type_args = &.{};
out.kind.struct_lit.fields = try g.walk([]const ast.FieldInit, x.fields, env);
out.span.resolved = t.span.resolved;
return out;
try g.queueWalk(pending, []const ast.FieldInit, &input.kind.struct_lit.fields, &out.kind.struct_lit.fields, env);
return;
},
else => {},
}
out.kind = try g.walk(ast.Expr.Kind, e.kind, env);
return out;
try g.queueWalk(pending, ast.Expr.Kind, &input.kind, &out.kind, env);
}
fn walkCall(g: *Generator, pending: *std.ArrayList(WalkWork), call: @FieldType(WalkWork, "call")) Error!void {
const x = call.input.kind.call;
if (call.phase == .after_type) {
const callee_name = try path(g.arena, x.callee.*);
if (callee_name) |name| if (boundFunction(call.env, name)) |arg| {
call.output.kind.call.callee = try g.box(ast.Expr, selectedExpr(x.callee.*, arg));
try g.queueWalk(pending, []const ast.Expr, &call.input.kind.call.args, &call.output.kind.call.args, call.env);
return;
};
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (callee_name) |name| if (g.function(name, x.callee.span)) |d| {
if (d.generics.len != 0) return g.invalid(.invalid_generic, call.input.span, "generic function needs explicit arguments", name);
};
const callee = try g.arena.create(ast.Expr);
call.output.kind.call.callee = callee;
try pending.append(g.arena, .{ .call = .{ .input = call.input, .output = call.output, .env = call.env, .phase = .after_callee, .name = callee_name } });
try g.queueWalk(pending, ast.Expr, x.callee, callee, call.env);
} else {
call.output.kind.call.args = try g.arena.alloc(ast.Expr, x.args.len);
try pending.append(g.arena, .{ .argument = .{ .input = call.input, .output = call.output, .env = call.env, .index = 0, .name = call.name } });
}
}
fn walkArgument(g: *Generator, pending: *std.ArrayList(WalkWork), arg: @FieldType(WalkWork, "argument")) Error!void {
const args = arg.input.kind.call.args;
if (arg.index == args.len) return;
const input = &args[arg.index];
const output = &@constCast(arg.output.kind.call.args)[arg.index];
try pending.append(g.arena, .{ .argument = .{ .input = arg.input, .output = arg.output, .env = arg.env, .index = arg.index + 1, .name = arg.name } });
if (arg.index == 1 and arg.name != null and std.mem.eql(u8, arg.name.?, "task.spawn")) {
if (try path(g.arena, input.*)) |name| if (boundFunction(arg.env, name)) |selected| {
output.* = selectedExpr(input.*, selected);
return;
};
}
try g.queueWalk(pending, ast.Expr, input, output, arg.env);
}
fn WalkVisitor(comptime T: type) type {
return struct {
fn visit(g: *Generator, pending: *std.ArrayList(WalkWork), raw_input: *const anyopaque, raw_output: *anyopaque, env: Env) Error!void {
const value: *const T = @ptrCast(@alignCast(raw_input));
const out: *T = @ptrCast(@alignCast(raw_output));
out.* = value.*;
if (T == ast.Type) {
out.* = try g.ty(value.*, env);
return;
}
if (T == ast.Expr) return g.expression(pending, value, out, env);
if (T == ast.Pattern) {
if (value.kind == .ctor) for (value.kind.ctor.binds) |name| try g.checkBinding(name, value.span, env);
if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| {
const t = try g.named(q, value.kind.ctor.type_args, value.span, env);
if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q);
out.kind.ctor.qualifier = t.kind.name;
out.kind.ctor.type_args = &.{};
out.span.resolved = t.span.resolved;
};
return;
}
if (T == ast.Param) try g.checkBinding(value.name, value.span, env);
if (T == ast.Select) for (value.cancelled_binds) |name| try g.checkBinding(name, value.span, env);
if (T == ast.Stmt) switch (value.kind) {
.let => |x| for (x.names) |name| try g.checkBinding(name, value.span, env),
inline .@"var", .borrow, .@"for", .scope, .lock => |x| try g.checkBinding(x.name, value.span, env),
else => {},
};
switch (@typeInfo(T)) {
.@"struct" => |info| {
inline for (0..info.field_names.len) |offset| {
const i = info.field_names.len - 1 - offset;
try g.queueWalk(pending, info.field_types[i], &@field(value.*, info.field_names[i]), &@field(out.*, info.field_names[i]), env);
}
},
.@"union" => switch (value.*) {
inline else => |*payload, tag| try g.queueWalk(pending, @TypeOf(payload.*), payload, &@field(out.*, @tagName(tag)), env),
},
.optional => |info| if (value.*) |*child| try g.queueWalk(pending, info.child, child, &out.*.?, env),
.pointer => |info| {
if (info.child == u8) return;
if (info.size == .slice) {
const children = try g.arena.alloc(info.child, value.*.len);
out.* = children;
var i = children.len;
while (i != 0) {
i -= 1;
try g.queueWalk(pending, info.child, &value.*[i], &children[i], env);
}
} else {
const child = try g.arena.create(info.child);
out.* = child;
try g.queueWalk(pending, info.child, value.*, child, env);
}
},
else => {},
}
}
};
}
fn box(g: *Generator, comptime T: type, value: T) A.Error!*const T {
@@ -614,49 +738,17 @@ const Generator = struct {
}
fn walk(g: *Generator, comptime T: type, value: T, env: Env) Error!T {
if (T == ast.Type) return g.ty(value, env);
if (T == ast.Expr) return g.expression(value, env);
if (T == ast.Pattern) {
var out = value;
if (value.kind == .ctor) for (value.kind.ctor.binds) |name| try g.checkBinding(name, value.span, env);
if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| {
const t = try g.named(q, value.kind.ctor.type_args, value.span, env);
if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q);
out.kind.ctor.qualifier = t.kind.name;
out.kind.ctor.type_args = &.{};
out.span.resolved = t.span.resolved;
};
return out;
}
if (T == ast.Param) try g.checkBinding(value.name, value.span, env);
if (T == ast.Select) for (value.cancelled_binds) |name| try g.checkBinding(name, value.span, env);
if (T == ast.Stmt) switch (value.kind) {
.let => |x| for (x.names) |name| try g.checkBinding(name, value.span, env),
inline .@"var", .borrow, .@"for", .scope, .lock => |x| try g.checkBinding(x.name, value.span, env),
else => {},
const input = value;
var output: T = undefined;
var pending: std.ArrayList(WalkWork) = .empty;
defer pending.deinit(g.arena);
try g.queueWalk(&pending, T, &input, &output, env);
while (pending.pop()) |work| switch (work) {
.visit => |v| try v.run(g, &pending, v.input, v.output, v.env),
.call => |c| try g.walkCall(&pending, c),
.argument => |a| try g.walkArgument(&pending, a),
};
if (T == ast.Span) return value;
switch (@typeInfo(T)) {
.@"struct" => |info| {
var out = value;
inline for (info.field_names, info.field_types) |name, FieldType| @field(out, name) = try g.walk(FieldType, @field(value, name), env);
return out;
},
.@"union" => switch (value) {
inline else => |payload, tag| return @unionInit(T, @tagName(tag), try g.walk(@TypeOf(payload), payload, env)),
},
.optional => |info| return if (value) |v| try g.walk(info.child, v, env) else null,
.pointer => |info| {
if (info.child == u8) return value;
if (info.size == .slice) {
const out = try g.arena.alloc(info.child, value.len);
for (value, out) |v, *target| target.* = try g.walk(info.child, v, env);
return out;
}
return try g.box(info.child, try g.walk(info.child, value.*, env));
},
else => return value,
}
return output;
}
};
@@ -670,11 +762,30 @@ fn builtin(name: []const u8) bool {
return false;
}
fn path(arena: A, e: ast.Expr) A.Error!?[]const u8 {
return switch (e.kind) {
.name => |name| name,
.field => |f| if (try path(arena, f.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, f.name }) else null,
else => null,
};
var root = e;
while (root.kind == .field) root = root.kind.field.e.*;
if (root.kind != .name) return null;
if (e.kind == .name) return root.kind.name;
var length = root.kind.name.len;
var node = e;
while (node.kind == .field) {
length = std.math.add(usize, length, node.kind.field.name.len) catch return error.OutOfMemory;
length = std.math.add(usize, length, 1) catch return error.OutOfMemory;
node = node.kind.field.e.*;
}
const out = try arena.alloc(u8, length);
var cursor = length;
node = e;
while (node.kind == .field) {
const field = node.kind.field;
cursor -= field.name.len;
@memcpy(out[cursor .. cursor + field.name.len], field.name);
cursor -= 1;
out[cursor] = '.';
node = field.e.*;
}
@memcpy(out[0..cursor], node.kind.name);
return out;
}
// Each entry borrows immutable AST storage. Reflective children point into
@@ -1060,3 +1171,628 @@ test "specialization identity OOM propagates with prefix bytes and arena cleanup
if (!failing.has_induced_failure) break;
}
}
// Independent former AST-cloning and path descent, for shallow finite tests.
// Binding/type/instantiation helpers are shared; nested instance bodies use
// the production walker and are outside this oracle's independence.
const ReferenceWalk = struct {
fn expression(g: *Generator, e: ast.Expr, env: Env) Error!ast.Expr {
var out = e;
if (e.kind == .move and env.params.len != 0) out.generic_transfer = true;
switch (e.kind) {
.name => |name| if (Generator.boundFunction(env, name) != null) return g.invalid(.invalid_static_function, e.span, "static function parameter is only a call target or named worker", name),
.specialize => |x| {
const name = oldPath(g.arena, x.base.*) catch return error.OutOfMemory;
if (name) |n| if (Generator.boundFunction(env, n) != null) return g.invalid(.invalid_static_function, e.span, "bound static function cannot be specialized again", n);
const d = g.function(name orelse return g.invalid(.invalid_generic, e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) };
out.span.resolved = true;
return out;
},
.call => |x| {
out.kind.call.type_arg = try walk(g, ?ast.Type, x.type_arg, env);
const callee_name = try oldPath(g.arena, x.callee.*);
if (callee_name) |name| if (Generator.boundFunction(env, name)) |arg| {
out.kind.call.callee = try g.box(ast.Expr, selectedExpr(x.callee.*, arg));
out.kind.call.args = try walk(g, []const ast.Expr, x.args, env);
return out;
};
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try oldPath(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| {
if (d.generics.len != 0) return g.invalid(.invalid_generic, e.span, "generic function needs explicit arguments", name);
};
out.kind.call.callee = try g.box(ast.Expr, try expression(g, x.callee.*, env));
const args = try g.arena.alloc(ast.Expr, x.args.len);
for (x.args, args, 0..) |arg, *target, i| {
if (i == 1 and callee_name != null and std.mem.eql(u8, callee_name.?, "task.spawn")) {
if (try oldPath(g.arena, arg)) |name| if (Generator.boundFunction(env, name)) |selected| {
target.* = selectedExpr(arg, selected);
continue;
};
}
target.* = try expression(g, arg, env);
}
out.kind.call.args = args;
return out;
},
.variant => |x| {
const t = try g.named(x.@"enum", x.type_args, e.span, env);
if (t.kind != .name) return g.fail("E7005", e.span, "enum constructor requires a named type", x.@"enum");
out.kind.variant.@"enum" = t.kind.name;
out.kind.variant.type_args = &.{};
out.span.resolved = t.span.resolved;
return out;
},
.struct_lit => |x| {
const t = try g.named(x.name, x.type_args, e.span, env);
if (t.kind != .name) return g.fail("E7005", e.span, "struct constructor requires a named type", x.name);
out.kind.struct_lit.name = t.kind.name;
out.kind.struct_lit.type_args = &.{};
out.kind.struct_lit.fields = try walk(g, []const ast.FieldInit, x.fields, env);
out.span.resolved = t.span.resolved;
return out;
},
else => {},
}
out.kind = try walk(g, ast.Expr.Kind, e.kind, env);
return out;
}
fn box(g: *Generator, comptime T: type, value: T) A.Error!*const T {
const out = try g.arena.create(T);
out.* = value;
return out;
}
fn walk(g: *Generator, comptime T: type, value: T, env: Env) Error!T {
if (T == ast.Type) return g.ty(value, env);
if (T == ast.Expr) return expression(g, value, env);
if (T == ast.Pattern) {
var out = value;
if (value.kind == .ctor) for (value.kind.ctor.binds) |name| try g.checkBinding(name, value.span, env);
if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| {
const t = try g.named(q, value.kind.ctor.type_args, value.span, env);
if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q);
out.kind.ctor.qualifier = t.kind.name;
out.kind.ctor.type_args = &.{};
out.span.resolved = t.span.resolved;
};
return out;
}
if (T == ast.Param) try g.checkBinding(value.name, value.span, env);
if (T == ast.Select) for (value.cancelled_binds) |name| try g.checkBinding(name, value.span, env);
if (T == ast.Stmt) switch (value.kind) {
.let => |x| for (x.names) |name| try g.checkBinding(name, value.span, env),
inline .@"var", .borrow, .@"for", .scope, .lock => |x| try g.checkBinding(x.name, value.span, env),
else => {},
};
if (T == ast.Span) return value;
switch (@typeInfo(T)) {
.@"struct" => |info| {
var out = value;
inline for (info.field_names, info.field_types) |name, FieldType| @field(out, name) = try walk(g, FieldType, @field(value, name), env);
return out;
},
.@"union" => switch (value) {
inline else => |payload, tag| return @unionInit(T, @tagName(tag), try walk(g, @TypeOf(payload), payload, env)),
},
.optional => |info| return if (value) |v| try walk(g, info.child, v, env) else null,
.pointer => |info| {
if (info.child == u8) return value;
if (info.size == .slice) {
const out = try g.arena.alloc(info.child, value.len);
for (value, out) |v, *target| target.* = try walk(g, info.child, v, env);
return out;
}
return try g.box(info.child, try walk(g, info.child, value.*, env));
},
else => return value,
}
}
fn oldPath(arena: A, e: ast.Expr) A.Error!?[]const u8 {
return switch (e.kind) {
.name => |name| name,
.field => |f| if (try oldPath(arena, f.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, f.name }) else null,
else => null,
};
}
};
fn walkFixture(a: A) !ast.Module {
const parsed = try @import("parse.zig").parseWithFile(a,
\\module walk
\\struct S { value: u64 }
\\enum E { A(u64), B }
\\struct Box<T> { value: T }
\\enum Choice<T> { A(T), B }
\\fn ordinary(x: u64) -> u64 effects [] { return x; }
\\fn id<T>(x: T) -> T effects [] { return move x; }
, "fixture.aji");
try std.testing.expect(parsed == .ok);
return parsed.ok;
}
fn expectWalkMatches(comptime T: type, value: T, env: Env, module: ast.Module) !void {
var old_arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer old_arena.deinit();
var new_arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer new_arena.deinit();
var old: Generator = .{ .arena = old_arena.allocator(), .m = module };
var new: Generator = .{ .arena = new_arena.allocator(), .m = module };
const before = ReferenceWalk.walk(&old, T, value, env);
const after = new.walk(T, value, env);
if (before) |expected| {
try std.testing.expectEqualDeep(expected, try after);
} else |err| try std.testing.expectError(err, after);
try std.testing.expectEqualDeep(old.problem, new.problem);
try std.testing.expectEqualDeep(old.instances.items, new.instances.items);
try std.testing.expectEqualDeep(old.requirements.items, new.requirements.items);
try std.testing.expectEqual(old.depth, new.depth);
try std.testing.expectEqual(old.type_depth, new.type_depth);
}
test "generic AST continuations match independent shallow expression descent" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const module = try walkFixture(a);
const span = identitySpan(29);
const ty: ast.Type = .{ .span = span, .kind = .{ .name = "u64" } };
const contract: ast.FunctionContract = .{ .params = &.{ty}, .ret = ty, .effects = &.{} };
const parameters = [_]ast.TypeParam{
.{ .name = "T", .span = span, .constraints = &.{} },
.{ .name = "F", .span = span, .constraints = &.{}, .callable = &contract },
};
const arguments = [_]ast.Type{ ty, .{ .span = span, .kind = .{ .function_ref = .{ .name = "ordinary" } } } };
const environments = [_]Env{ .{}, .{ .params = parameters[0..1], .args = arguments[0..1] }, .{ .params = parameters[1..], .args = arguments[1..] }, .{ .params = &parameters, .args = &arguments } };
const leaves = [_][]const u8{
"1u64", "true", "b\"hi\"", "x", "F", "move x", "E::B", "Choice::<T>::B", "Choice::<u64>::A(1u64)", "S { value: x }", "Box::<T> { value: x }", "id::<u64>", "id::<T>(x)", "id(x)", "unknown::<u64>(x)", "F(x)", "F::<u64>(x)", "task.spawn(s, F, x)", "task.spawn(F, x)", "ordinary::<u64>(x)",
};
const forms = [_][]const u8{
"{s}", "- {s}", "not {s}", "* {s}", "ref ({s})", "({s}) + F", "F + ({s})", "({s}) as! T", "({s}).value", "({s})[F]", "x[({s})..F]", "[{s}; 7]", "[{s}, F]", "ordinary({s}, F)", "({s})(F)", "channel.make::<T>({s})", "S {{ value: {s} }}", "Box::<T> {{ value: {s} }}", "({s}) or trap", "if true {{ {s} }} else {{ F }}", "match x {{ E::A(y) => {s}, E::B => F }}", "{{ {s} }}",
};
inline for (forms) |form| for (leaves) |leaf| {
const text = try std.fmt.allocPrint(a, form, .{leaf});
const source = try std.fmt.allocPrint(a, "module walk\nfn probe() -> void effects [] {{ return {s}; }}", .{text});
const parsed = try @import("parse.zig").parseWithFile(a, source, "expression.aji");
try std.testing.expect(parsed == .ok);
const expression = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for (environments) |env| try expectWalkMatches(ast.Expr, expression, env, module);
};
}
test "generic AST continuations retain statement pattern and binding error priority" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const module = try walkFixture(a);
const span = identitySpan(31);
const ty: ast.Type = .{ .span = span, .kind = .{ .name = "u64" } };
const contract: ast.FunctionContract = .{ .params = &.{ty}, .ret = ty, .effects = &.{} };
const parameters = [_]ast.TypeParam{ .{ .name = "T", .span = span, .constraints = &.{} }, .{ .name = "F", .span = span, .constraints = &.{}, .callable = &contract } };
const arguments = [_]ast.Type{ ty, .{ .span = span, .kind = .{ .function_ref = .{ .name = "ordinary" } } } };
const environments = [_]Env{ .{}, .{ .params = &parameters, .args = &arguments } };
const bodies = [_][]const u8{
"let x: T = F; let y = move x; y", "let F: unknown = F;", "let (x, F) = unknown;", "var F: unknown = F;", "var x: T = zero;", "var x: unknown = F;", "ref F = x;", "mut x = F;", "x[F] = F;", "while F { F; }", "for F in 0u64..1u64 { F; }", "loop { F; break; }", "scope F { F; }", "shield { F; }", "if F { F; } else if F { F; } else { F; }", "match F { E::A(F) => F, E::B => F }", "match x { Choice::<T>::A(F) => F, Choice::<T>::B => F }", "match x { Choice::<T>::A(y) => move y, Choice::<T>::B => F }", "{ let x: T = 1u64; F };", "return F;", "continue; trap;",
};
for (bodies) |body| {
const source = try std.fmt.allocPrint(a, "module walk\nfn probe(x: T) -> T effects [] {{ {s} }}", .{body});
const parsed = try @import("parse.zig").parseWithFile(a, source, "statements.aji");
try std.testing.expect(parsed == .ok);
const function = parsed.ok.functions[0];
for (environments) |env| {
try expectWalkMatches(ast.FnDecl, function, env, module);
try expectWalkMatches(ast.Block, function.body, env, module);
for (function.body.stmts) |statement| try expectWalkMatches(ast.Stmt, statement, env, module);
try expectWalkMatches(ast.Param, .{ .name = "F", .span = span, .ty = .{ .span = span, .kind = .{ .name = "unknown" } } }, env, module);
}
}
const plain: ast.Expr = .{ .span = span, .kind = .{ .name = "x" } };
const bad: ast.Expr = .{ .span = span, .kind = .{ .name = "F" } };
for ([_][]const []const u8{ &.{"F"}, &.{"y"}, &.{} }) |binds| {
const pattern: ast.Pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = "Choice", .name = "A", .binds = binds, .type_args = &.{ty} } } };
const select: ast.Select = .{ .span = span, .arms = &.{.{ .span = span, .send = true, .endpoint = "F", .value = bad, .arms = &.{.{ .pattern = pattern, .body = plain }} }}, .cancelled_binds = binds, .cancelled = bad };
const empty: ast.Block = .{ .span = span, .stmts = &.{}, .tail = null };
for (environments) |env| {
try expectWalkMatches(ast.Pattern, pattern, env, module);
try expectWalkMatches(ast.Select, select, env, module);
try expectWalkMatches(ast.Stmt, .{ .span = span, .kind = .{ .select = select } }, env, module);
try expectWalkMatches(ast.Stmt, .{ .span = span, .kind = .{ .lock = .{ .place = bad, .name = if (binds.len == 0) "g" else binds[0], .body = empty, .cancelled = empty } } }, env, module);
}
}
}
fn deepWalkInput(a: A, count: usize) !ast.Expr {
const plain: ast.Expr = .{ .span = identitySpan(1), .kind = .{ .name = "x" } };
const callee = try a.create(ast.Expr);
callee.* = .{ .span = identitySpan(2), .kind = .{ .name = "ordinary" } };
var expression: ast.Expr = .{ .span = identitySpan(3), .kind = .{ .move = "x" } };
for (0..count) |i| {
const inner = try a.create(ast.Expr);
inner.* = expression;
var span = identitySpan(@intCast(i + 4));
span.file = "deep.aji";
span.namespace = "walk";
const annotation: ast.Type = .{ .span = span, .kind = .{ .name = "T" } };
const kind: ast.Expr.Kind = switch (i % 14) {
0 => .{ .neg = inner },
1 => .{ .cast = .{ .mode = .checked, .e = inner, .ty = annotation } },
2 => blk: {
const args = try a.alloc(ast.Expr, 2);
args[0] = inner.*;
args[1] = plain;
break :blk .{ .call = .{ .callee = callee, .type_arg = annotation, .args = args } };
},
3 => blk: {
const branch = try a.create(ast.If);
branch.* = .{ .cond = plain, .then = .{ .span = span, .stmts = &.{}, .tail = inner }, .@"else" = .{ .block = .{ .span = span, .stmts = &.{}, .tail = null } } };
break :blk .{ .if_expr = branch };
},
4 => blk: {
const match = try a.create(ast.Match);
const arms = try a.alloc(ast.Arm, 2);
arms[0] = .{ .pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = "E", .name = "A", .binds = &.{"y"} } } }, .body = inner.* };
arms[1] = .{ .pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = "E", .name = "B", .binds = &.{} } } }, .body = plain };
match.* = .{ .span = span, .scrutinee = plain, .arms = arms, .kind = .@"enum" };
break :blk .{ .match_expr = match };
},
5 => blk: {
const block = try a.create(ast.Block);
const statements = try a.alloc(ast.Stmt, 1);
statements[0] = .{ .span = span, .kind = .{ .let = .{ .names = &.{"y"}, .ty = annotation, .e = plain } } };
block.* = .{ .span = span, .stmts = statements, .tail = inner };
break :blk .{ .block = block };
},
6 => .{ .binary = .{ .op = .add, .l = inner, .r = callee } },
7 => .{ .index = .{ .e = inner, .lo = callee, .hi = null } },
8 => .{ .field = .{ .e = inner, .name = "value" } },
9 => .{ .array_rep = .{ .e = inner, .len = 7 } },
10 => blk: {
const items = try a.alloc(ast.Expr, 2);
items[0] = inner.*;
items[1] = plain;
break :blk .{ .array_list = items };
},
11 => .{ .borrow = .{ .mutable = true, .unchecked = false, .place = inner } },
12 => .{ .or_trap = inner },
else => blk: {
const fields = try a.alloc(ast.FieldInit, 1);
fields[0] = .{ .name = "value", .span = span, .e = inner.* };
break :blk .{ .struct_lit = .{ .name = "S", .fields = fields } };
},
};
expression = .{ .span = span, .generic_transfer = i % 3 == 0, .kind = kind };
}
return expression;
}
fn walkNext(e: ast.Expr) ast.Expr {
return switch (e.kind) {
.neg => |x| x.*,
.cast => |x| x.e.*,
.call => |x| x.args[0],
.if_expr => |x| x.then.tail.?.*,
.match_expr => |x| x.arms[0].body,
.block => |x| x.tail.?.*,
.binary => |x| x.l.*,
.index => |x| x.e.*,
.field => |x| x.e.*,
.array_rep => |x| x.e.*,
.array_list => |x| x[0],
.borrow => |x| x.place.*,
.or_trap => |x| x.*,
.struct_lit => |x| x.fields[0].e,
else => unreachable,
};
}
test "generic AST continuations clone deep mixed expressions and preserve input ownership" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const module = try walkFixture(a);
const concrete: ast.Type = .{ .span = identitySpan(99), .kind = .{ .name = "u64" } };
const params = [_]ast.TypeParam{.{ .name = "T", .span = identitySpan(98), .constraints = &.{} }};
var g: Generator = .{ .arena = a, .m = module };
const count = 32_768;
var before = try deepWalkInput(a, count);
var after = try g.walk(ast.Expr, before, .{ .params = &params, .args = &.{concrete} });
for (0..count) |_| {
try std.testing.expectEqual(std.meta.activeTag(before.kind), std.meta.activeTag(after.kind));
var expected_span = before.span;
if (before.kind == .struct_lit) expected_span.resolved = true;
try std.testing.expectEqualDeep(expected_span, after.span);
try std.testing.expectEqual(before.generic_transfer, after.generic_transfer);
switch (after.kind) {
.cast => |x| try std.testing.expectEqualDeep(concrete, x.ty),
.call => |x| {
try std.testing.expect(x.callee != before.kind.call.callee);
try std.testing.expect(x.args.ptr != before.kind.call.args.ptr);
try std.testing.expectEqualDeep(concrete, x.type_arg.?);
try std.testing.expectEqualDeep(before.kind.call.args[1], x.args[1]);
},
.block => |x| {
try std.testing.expect(x != before.kind.block);
try std.testing.expect(x.stmts.ptr != before.kind.block.stmts.ptr);
try std.testing.expectEqualDeep(concrete, x.stmts[0].kind.let.ty.?);
},
.match_expr => |x| {
try std.testing.expect(x != before.kind.match_expr);
try std.testing.expect(x.arms.ptr != before.kind.match_expr.arms.ptr);
try std.testing.expectEqualDeep(before.kind.match_expr.arms[1].body, x.arms[1].body);
try std.testing.expect(x.arms[0].pattern.span.resolved);
},
.array_list => |x| try std.testing.expect(x.ptr != before.kind.array_list.ptr),
.struct_lit => |x| try std.testing.expect(x.fields.ptr != before.kind.struct_lit.fields.ptr),
else => {},
}
before = walkNext(before);
after = walkNext(after);
}
try std.testing.expectEqualStrings("x", after.kind.move);
try std.testing.expect(after.generic_transfer);
try std.testing.expect(!before.generic_transfer);
try std.testing.expectEqualDeep(before.span, after.span);
try std.testing.expect(g.problem == null);
}
test "generic AST continuations handle deep callee and statement reentry" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const module = try walkFixture(a);
var g: Generator = .{ .arena = a, .m = module };
const count = 32_768;
var callee: ast.Expr = .{ .span = identitySpan(1), .kind = .{ .name = "ordinary" } };
const argument: ast.Expr = .{ .span = identitySpan(2), .kind = .{ .name = "x" } };
for (0..count) |i| {
const child = try a.create(ast.Expr);
child.* = callee;
callee = .{ .span = identitySpan(@intCast(i + 3)), .kind = .{ .call = .{ .callee = child, .type_arg = null, .args = &.{argument} } } };
}
var current = try g.walk(ast.Expr, callee, .{});
var input = callee;
for (0..count) |_| {
try std.testing.expect(current.kind == .call);
try std.testing.expectEqualDeep(input.span, current.span);
try std.testing.expect(current.kind.call.callee != input.kind.call.callee);
try std.testing.expect(current.kind.call.args.ptr != input.kind.call.args.ptr);
try std.testing.expectEqualDeep(argument, current.kind.call.args[0]);
current = current.kind.call.callee.*;
input = input.kind.call.callee.*;
}
try std.testing.expectEqualDeep(input, current);
var block: ast.Block = .{ .span = identitySpan(1), .stmts = &.{}, .tail = &argument };
for (0..count) |i| {
const statements = try a.alloc(ast.Stmt, 1);
statements[0] = .{ .span = identitySpan(@intCast(i + 3)), .kind = switch (i % 3) {
0 => .{ .loop = block },
1 => .{ .shield = block },
else => .{ .scope = .{ .name = "s", .body = block } },
} };
block = .{ .span = statements[0].span, .stmts = statements, .tail = null };
}
var result = try g.walk(ast.Block, block, .{});
var original = block;
for (0..count) |_| {
try std.testing.expectEqualDeep(original.span, result.span);
try std.testing.expect(result.stmts.ptr != original.stmts.ptr);
try std.testing.expect(result.tail == null);
result = switch (result.stmts[0].kind) {
.loop, .shield => |b| b,
.scope => |x| x.body,
else => unreachable,
};
original = switch (original.stmts[0].kind) {
.loop, .shield => |b| b,
.scope => |x| x.body,
else => unreachable,
};
}
try std.testing.expectEqualDeep(argument, result.tail.?.*);
try std.testing.expect(result.tail.? != original.tail.?);
try std.testing.expect(g.problem == null);
}
test "generic AST work and instance OOM propagates with arena cleanup" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const module = try walkFixture(a);
const ty: ast.Type = .{ .span = identitySpan(1), .kind = .{ .name = "u64" } };
const parameter: ast.TypeParam = .{ .name = "T", .span = identitySpan(2), .constraints = &.{} };
const base: ast.Expr = .{ .span = identitySpan(3), .kind = .{ .name = "id" } };
const specialized: ast.Expr = .{ .span = identitySpan(4), .kind = .{ .specialize = .{ .base = &base, .args = &.{ty} } } };
const expression: ast.Expr = .{ .span = identitySpan(5), .kind = .{ .call = .{ .callee = &specialized, .type_arg = null, .args = &.{.{ .span = identitySpan(6), .kind = .{ .name = "x" } }} } } };
for ([_]ast.Expr{ try deepWalkInput(a, 64), expression }) |input| {
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 256);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var output: std.heap.ArenaAllocator = .init(failing.allocator());
var g: Generator = .{ .arena = output.allocator(), .m = module };
const result = g.walk(ast.Expr, input, .{ .params = &.{parameter}, .args = &.{ty} });
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else {
const value = try result;
try std.testing.expectEqual(std.meta.activeTag(input.kind), std.meta.activeTag(value.kind));
if (input.kind == .call) {
try std.testing.expect(value.kind.call.callee.kind == .name);
try std.testing.expectEqual(@as(usize, 1), g.instances.items.len);
try std.testing.expect(g.instances.items[0].decl == .function);
}
}
try std.testing.expect(g.problem == null);
try std.testing.expectEqual(@as(usize, 0), g.depth);
try std.testing.expectEqual(@as(usize, 0), g.type_depth);
output.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
}
// Fail once, then allow all following allocations. No diagnostic or retry may
// hide a failed work entry, output clone or nested instance query.
const WalkAllocationFailure = struct {
backing: A,
at: usize,
attempts: usize = 0,
failed: bool = false,
fn allocator(self: *@This()) A {
return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
}
fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(raw));
self.attempts += 1;
if (self.attempts == self.at + 1) {
self.failed = true;
return null;
}
return self.backing.rawAlloc(len, alignment, ra);
}
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(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void {
const self: *@This() = @ptrCast(@alignCast(raw));
self.backing.rawFree(memory, alignment, ra);
}
};
test "public specialization propagates every recovering allocation failure" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const parsed = try @import("parse.zig").parse(fixture.allocator(),
\\module walk
\\struct Box<T> { value: T }
\\fn id<T>(x: T) -> T effects [] { return move x; }
\\fn main() -> u64 effects [] { let b = Box::<u64> { value: id::<u64>(1u64) }; return b.value + id::<u64>(2u64); }
);
try std.testing.expect(parsed == .ok);
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 1024);
var output: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer output.deinit();
var failure: WalkAllocationFailure = .{ .backing = output.allocator(), .at = fail_index };
const result = specialize(failure.allocator(), parsed.ok);
if (failure.failed) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expectEqual(fail_index + 1, failure.attempts);
} else {
const value = try result;
try std.testing.expect(value == .ok);
try std.testing.expectEqual(@as(usize, 2), value.ok.functions.len);
try std.testing.expectEqual(@as(usize, 1), value.ok.types.len);
break;
}
}
}
test "generic qualified paths own one complete string and validate roots before allocation" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const span = identitySpan(17);
const root: ast.Expr = .{ .span = span, .kind = .{ .name = "root" } };
const invalid: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } };
for ([_]ast.Expr{ root, invalid }) |leaf| {
var current = leaf;
for (0..9) |i| {
const before = try ReferenceWalk.oldPath(a, current);
const after = try path(a, current);
try std.testing.expectEqualDeep(before, after);
const child = try a.create(ast.Expr);
child.* = current;
current = .{ .span = span, .kind = .{ .field = .{ .e = child, .name = if (i % 2 == 0) "left" else "right" } } };
}
}
var current = root;
for (0..65_536) |i| {
const child = try a.create(ast.Expr);
child.* = current;
current = .{ .span = span, .kind = .{ .field = .{ .e = child, .name = if (i % 2 == 0) "x" else "yz" } } };
}
var allocation: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
const owned = (try path(allocation.allocator(), current)).?;
try std.testing.expectEqual(@as(usize, 1), allocation.allocations);
try std.testing.expectEqual(@as(usize, 4 + 32_768 * 5), owned.len);
try std.testing.expectEqualStrings("root", owned[0..4]);
for (0..32_768) |i| try std.testing.expectEqualStrings(".x.yz", owned[4 + i * 5 .. 4 + (i + 1) * 5]);
allocation.allocator().free(owned);
try std.testing.expectEqual(allocation.allocated_bytes, allocation.freed_bytes);
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
try std.testing.expectError(error.OutOfMemory, path(none.allocator(), current));
try std.testing.expect(none.has_induced_failure);
var no_alloc: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
try std.testing.expectEqualStrings("root", (try path(no_alloc.allocator(), root)).?);
const bad: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &invalid, .name = "x" } } };
try std.testing.expect(try path(no_alloc.allocator(), bad) == null);
try std.testing.expect(!no_alloc.has_induced_failure);
}
test "generic continuations retain deep else union storage and deepest binding failures" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const module = try walkFixture(a);
const span = identitySpan(97);
const ty: ast.Type = .{ .span = span, .kind = .{ .name = "u64" } };
const contract: ast.FunctionContract = .{ .params = &.{ty}, .ret = ty, .effects = &.{} };
const parameters = [_]ast.TypeParam{ .{ .name = "T", .span = span, .constraints = &.{} }, .{ .name = "F", .span = span, .constraints = &.{}, .callable = &contract } };
const arguments = [_]ast.Type{ ty, .{ .span = span, .kind = .{ .function_ref = .{ .name = "ordinary" } } } };
const env: Env = .{ .params = &parameters, .args = &arguments };
const count = 32_768;
const plain: ast.Expr = .{ .span = span, .kind = .{ .name = "x" } };
const leaf: ast.Expr = .{ .span = span, .kind = .{ .move = "x" } };
const empty: ast.Block = .{ .span = span, .stmts = &.{}, .tail = null };
var branch: ast.If = .{ .cond = plain, .then = empty, .@"else" = .{ .block = .{ .span = span, .stmts = &.{}, .tail = &leaf } } };
for (0..count) |_| {
const child = try a.create(ast.If);
child.* = branch;
branch = .{ .cond = plain, .then = empty, .@"else" = .{ .@"if" = child } };
}
var g: Generator = .{ .arena = a, .m = module };
var after = try g.walk(ast.If, branch, env);
var before = branch;
for (0..count) |_| {
try std.testing.expectEqualDeep(plain, after.cond);
try std.testing.expectEqualDeep(empty, after.then);
try std.testing.expect(after.@"else".? == .@"if");
try std.testing.expect(after.@"else".?.@"if" != before.@"else".?.@"if");
before = before.@"else".?.@"if".*;
after = after.@"else".?.@"if".*;
}
try std.testing.expect(after.@"else".?.block.tail.?.generic_transfer);
try std.testing.expect(!before.@"else".?.block.tail.?.generic_transfer);
const forbidden: ast.Expr = .{ .span = identitySpan(91), .kind = .{ .name = "F" } };
var expression = forbidden;
for (0..count) |_| {
const child = try a.create(ast.Expr);
child.* = expression;
expression = .{ .span = span, .kind = .{ .not = child } };
}
var failed: Generator = .{ .arena = a, .m = module };
try std.testing.expectError(error.InvalidGeneric, failed.walk(ast.Expr, expression, env));
try std.testing.expectEqualStrings("E7006", failed.problem.?.code);
try std.testing.expectEqual(lower.InvalidReason.invalid_static_function, failed.problem.?.reason.?);
try std.testing.expectEqualDeep(forbidden.span, failed.problem.?.span);
var block: ast.Block = .{ .span = span, .tail = null, .stmts = &.{.{ .span = forbidden.span, .kind = .{ .@"var" = .{ .name = "F", .ty = .{ .span = span, .kind = .{ .name = "unknown" } }, .init = forbidden } } }} };
for (0..count) |_| {
const statements = try a.alloc(ast.Stmt, 1);
statements[0] = .{ .span = span, .kind = .{ .loop = block } };
block = .{ .span = span, .tail = null, .stmts = statements };
}
var failed_binding: Generator = .{ .arena = a, .m = module };
try std.testing.expectError(error.InvalidGeneric, failed_binding.walk(ast.Block, block, env));
try std.testing.expectEqualStrings("E7006", failed_binding.problem.?.code);
try std.testing.expectEqual(lower.InvalidReason.invalid_static_function, failed_binding.problem.?.reason.?);
try std.testing.expectEqualDeep(forbidden.span, failed_binding.problem.?.span);
try std.testing.expectEqual(@as(usize, 0), failed.depth);
try std.testing.expectEqual(@as(usize, 0), failed.type_depth);
try std.testing.expectEqual(@as(usize, 0), failed_binding.depth);
try std.testing.expectEqual(@as(usize, 0), failed_binding.type_depth);
}