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

+2
View File
@@ -535,4 +535,6 @@ The [binary operand increment](source-expression-depth-audit.md#binary-operand-l
The [external review and host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) supersede the initial query OOM-to-unknown policy. A one-shot allocation failure reproduces false E7007 before repair. Expression/expected-use queries and their annotation, field, signature and place callbacks now propagate host OOM separately from optional unknown answers. Worklist buffers retain caller-arena lifetime; list deinit is not immediate physical release. The audit explicitly inventories non-scalar parsing/lowering, generic cloning/path callbacks and liveness/read/assignment scans. Build/units/format checks, all 1,793 ordinary conformance cases, 360 expression-depth and 234 independent-error CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). Recovering caller/callback and public-lowering allocation tests reject false diagnostics and partial publication. Q-061 remains open; this follow-up has no external review yet.
The [generic transformation increment](source-expression-depth-audit.md#generic-ast-transformation-continuations) replaces expression/statement/block cloning and its qualified-path callback with typed work entries. AST/error/instance order, spans, Copy-transfer and static-worker policy are preserved; existing type/instance guards remain. A separate baseline confirms generics.path also aborted on a 16,384-field unknown callee. Full generic scalar checks/lowerings now accept through 65,536; deep unknown callees return exact E7002. Independent shallow/deep/OOM and 497/42/25 CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). All 1,793 ordinary conformance cases pass with exact coverage. Follow-up probes confirm remaining parser failures at 1,024 parenthesized/mixed-call levels and 16,384 qualified-variant fields. Q-061 remains open, without a new limit or external review of this increment.
Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one.
+73 -8
View File
@@ -320,20 +320,85 @@ lazy-query tests still avoid unnecessary right-side work. This establishes
compiler error policy, not a new model result or full GC pass. Q-061 is open;
this follow-up has not yet received external review.
## Generic AST transformation continuations
Baseline checks at 50a7575 accept a generic body's 16 negations but abort at
1,024 in `generics.expression`/reflective `walk`, with empty stdout. An unused
template also forces transformation of nongeneric bodies: a 16-component
unknown callee produces E7002, while 16,384 components abort in `generics.path`.
The latter is now an observed callback failure, not just an inspection risk.
Raw records are `generic-transform-before-probes.json` and
`generic-transform-before-*.stdout/.stderr` under the ignored evidence directory.
Typed work entries now clone structural AST children in the former field,
union, optional, pointer and slice order. Inputs borrow stable immutable AST
storage (including the root held throughout a walk); output targets live in
fresh caller-arena nodes. Entries never point into copied union payloads or
queue entries. Type/pattern/binding handling, source spans and generic Copy
transfer flags retain their original policy. Calls have explicit stages:
transform type_arg, resolve/check the callee, transform it, then process
arguments in order, with the existing static-worker exception for task.spawn's
second argument. Constructors resolve their named type before their fields.
Nested instantiation/type queries keep their unchanged depth-64 guards,
instance/key limits and public error policy; no expression-depth limit is added.
The qualified-path callback validates the immutable root first, then allocates
one complete string and fills components iteratively. Direct names and invalid
roots allocate nothing; path bytes and named/static-function decisions are
unchanged. Host allocation failure propagates without a source diagnostic or
public partial AST. List deinit is logical cleanup; work buffers, generated
AST/type nodes and partial internal instances keep caller-arena lifetime until
that arena is destroyed. Allocation requests and failure-index outcomes need
not match the recursive implementation.
An independent copy of the former clone/path descent compares 1,760 shallow
expression/environment combinations, plus function/statement/pattern/select/
lock binding-priority fixtures. It checks complete ASTs, problems, instance and
requirement order and guard counters. Binding/type/instantiation helpers are
shared; nested instance bodies use the production walker, outside this oracle's
independence. Separate helpers exercise 32,768 mixed expression levels, nested
callee targets, statement blocks, else-if unions and deepest static/binding
E7006 positions, plus 65,536 qualified fields. These synthetic helpers do not
claim arbitrary source acceptance. Persistent backing-allocation failures on
mixed/instance fixtures check host errors, guard restoration and physical arena
cleanup; every recovering direct-allocation failure in a public specialization
fixture rejects diagnostics, retries and partial publication.
Full source checks/lowerings now accept generic not/neg/cast/add bodies through
65,536 levels. Generic malformed dereferences retain their inner E7005 and
source position. Deep unknown callees return E7002 with the complete name and
exact location through 65,536 fields (`generic-transform-after-probes.json` and
`generic-transform-after-*.stdout/.stderr`). The permanent CLI suite independently
counts emitted instructions, fuel boundaries and values; it checks source/AIR
and deterministic/hosted parity for smaller accepted depths and exact rejection
records across check/lower/run/report/explore.
Build/unit/Zig format checks pass. The expression-depth suite passes 497 checks;
generic/static-function CLI suites pass 42/25 checks. Frozen old/new CLIs retain
exact exit/stdout/stderr on all 1,423 public source checks and 506 accepted
lowerings (`generic-transform-cli-compatibility.json`). All 1,793 ordinary
conformance cases pass with exact unique corpus coverage and terminal exit 0
(`generic-transform-conformance.jsonl` and its audit). These are compiler
regressions, not a full per-step GC pass or a model-capability measurement.
No normative, source/AIR format, feature, code, bundle, acceptance-limit,
ownership, runtime instruction or model result changes. Q-061 remains open;
this generic increment has no external review yet.
## Remaining work
Current follow-up checks still abort with empty stdout at 1,024 parenthesized
levels and 1,024 generic unary levels (`binary-followup-depth-probes.json` and
`binary-followup-*.stdout/.stderr`). The remaining inventory is broader than
these two observed failures:
Current follow-up checks accept 16 parenthesized/mixed-call levels but abort
with empty stdout at 1,024. A qualified enum variant returns E7002 at 16
components but aborts in Parser.exprPath at 16,384. Raw evidence is
`generic-followup-depth-probes.json` and `generic-followup-*.stdout/.stderr`.
Generic transformation and its path callback above are repaired; the remaining
inventory includes these observed parser failures and inspection-only risks:
| Production path | Evidence and next scope |
|---|---|
| Parser `postfix`/`primary` through parenthesized `expr` | Confirmed failure at 1,024 levels; preserve grouping, precedence and spans. |
| Parser `callArgs`, array/index/struct initializers, `ifExpr`, block/statement and match/arm expression entry | Recursive callbacks inspected; deep behavior unverified. Include mixed forms such as `n + f(n + f(...))`, not only homogeneous spines. |
| Parser `exprPath` | Recursive qualified-field callback inspected; deep source behavior unverified. |
| Generic `expression`/reflective `walk` | Confirmed generic unary failure at 1,024; include call/type/static-worker handling and nested statement/block cloning. |
| Generic `path` | Recursive qualified-field callback inspected; deep full-source behavior unverified. |
| Parser `callArgs`, array/index/struct initializers, `ifExpr`, block/statement and match/arm expression entry | Mixed `1i64 + id(...)` calls have a confirmed parser abort at 1,024. Other callback depth behavior is unverified; include alternating forms, not only homogeneous spines. |
| Parser `exprPath` | Confirmed qualified enum-variant abort at 16,384; preserve named-root classification, spelling, syntax/error priority and spans. |
| Lowerer non-scalar `expr` callbacks: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Native re-entry remains outside the repaired scalar driver; deep behavior unverified, including alternating scalar/non-scalar expressions. |
| Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. |
+24
View File
@@ -572,3 +572,27 @@ now assert OOM propagation and cleanup. Frozen old/new public checks/lowerings
remain exact (1,423/506). Generic transformation and parenthesized parsing still
have confirmed depth failures; Q-061, Q-060's full per-step validation and the
Phase 6 exit gates remain open. The existing review does not cover this repair.
## Source generic AST depth (2026-10-10)
The [Q-061 generic increment](../design/source-expression-depth-audit.md#generic-ast-transformation-continuations) replaces reflective expression/statement/block
cloning with typed work entries, retaining traversal/error/instance order, spans,
Copy-transfer and static-function/worker handling. Callee and constructor
callbacks retain their original ordering; qualified paths are built iteratively
with one complete allocation. Guarded type/instantiation re-entry retains its
existing limits. OOM propagates without public partial AST; buffers and nodes
retain caller-arena lifetime. No normative/bundle/feature/code/acceptance-limit
or ownership/runtime rule changes.
Independent shallow comparisons (1,760 expression contexts plus binding/
statement fixtures), deep mixed/callee/block/else-union and deepest-error helpers,
path/instance/worklist allocation failures and public recovering specialization
failures pass. Build/units/format checks, 497 expression-depth, 42 generic and 25
static-function CLI checks pass; frozen old/new public checks/lowerings remain
exact (1,423/506). All 1,793 ordinary conformance cases pass with exact coverage.
Full generic
scalar checks/lowerings accept through 65,536; deep qualified unknown calls
return exact E7002. Follow-up probes retain separate parser failures at 1,024
parenthesized/mixed-call levels and confirm Parser.exprPath failure at 16,384
qualified-variant fields. Q-061's remaining inventory, Q-060 validation and Phase
6 exit gates stay open. No external review covers this increment yet.
+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);
}
+63 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Operand depth, exact lowering/CFG/fuel and rejected-value positions (Q-061)."""
"""Operand/generic depth, exact lowering/CFG/fuel and rejection positions (Q-061)."""
import json
from pathlib import Path
import subprocess
@@ -182,6 +182,68 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Force monomorphization: every body traverses generic AST cloning before
# ordinary lowering. These are full CLI acceptance/fuel tests, separate
# from synthetic mixed-AST helper tests that need not be valid programs.
for depth in (0, 1, 16, 1024, 16384, 65536):
for kind in ('not', 'neg', 'cast', 'add'):
if kind == 'not':
ty, argument = 'bool', 'false'
expression, expected, instructions = 'not ' * depth + 'x', bool(depth % 2), 2 * depth + 4
elif kind == 'neg':
ty, argument = 'i64', '1i64'
expression, expected, instructions = '- ' * depth + 'x', 1 if depth % 2 == 0 else -1, 2 * depth + 4
elif kind == 'cast':
ty, argument = 'i64', '1i64'
expression = 'x' + ''.join(' ' + ('as i64', 'as! i64', 'as% i64')[i % 3] for i in range(depth))
expected, instructions = 1, depth + 4
else:
ty, argument = 'i64', '1i64'
expression, expected, instructions = 'x' + ' + 1i64' * depth, depth + 1, 2 * depth + 4
path = root / f'generic-{kind}-{depth}.aji'
path.write_text('module depth\nfn f<T>(x: T) -> T effects [] { return ' + expression + '; }\n'
f'fn main() -> {ty} effects [] {{ return f::<{ty}>({argument}); }}\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
assert sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) == instructions
if depth <= 1024:
returned = cli('run', path, '--fuel', instructions)
assert json.loads(returned) == {'status': 'returned', 'value': expected}
assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', instructions) == returned
record = root / 'hosted.json'
assert cli('run', path, '--fuel', instructions, '--profile', 'hosted', '--result-file', record) == b''
assert json.loads(record.read_text()) == json.loads(returned)
print(f'generic depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
header = 'fn f<T>(x: T) -> T effects [] { return '
path = root / f'generic-deref-{depth}.aji'
path.write_text('module depth\n' + header + '* ' * depth + 'x; }\n'
'fn main() -> i64 effects [] { return f::<i64>(1i64); }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['line'], error['col'], error['file']) == (
'E7005', 2, len(header) + 1 + 2 * (depth - 1), str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
for depth in (16384, 65536):
# An unused template still forces transformation of nongeneric bodies.
# Formerly generics.path aborted before unknown-callee diagnostics.
name = 'ns.' * depth + 'unknown'
header = 'fn main() -> i64 effects [] { return '
path = root / f'generic-callee-{depth}.aji'
path.write_text('module depth\nfn unused<T>(x: T) -> T effects [] { return move x; }\n'
+ header + name + '(); }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['name'], error['file'], error['line'], error['col']) == (
'E7002', name, str(path), 3, len(header) + 1), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Signed boundary literal remains one negative constant; the outer
# checked negation traps rather than changing literal acceptance.
minimum = root / 'minimum.aji'