cli: lower enum payloads iteratively

This commit is contained in:
dev committed 2026-10-11 13:23:36 +03:00
1 parent 8c34a4d64d
commit 627ad8f857
5 files changed
+397 -17

No files matched your search

+2
View File
@@ -548,3 +548,5 @@ The [ordinary-call increment](source-expression-depth-audit.md#ordinary-call-arg
The [struct/value-field increment](source-expression-depth-audit.md#struct-construction-and-value-field-continuations) preserves declaration-order initializer checks, receiver lookup and deferred annotation queries, nominal/static/slice length rules, loans and host OOM. Independent shallow/deep comparisons, output-arena failure cleanup, exact ordinary conformance coverage and public CLI parity pass. The former struct/field abort is repaired; at that checkpoint nested array literals still aborted at 4,096 before and after. Remaining array/variant/place/control callbacks and liveness/read/assignment walks keep Q-061 open. No semantic or new depth limit changes are made. Independent read-only Claude core/follow-up reviews found no concrete defects, without running tests or establishing whole-Q-061 completion.
The [array-continuation increment](source-expression-depth-audit.md#array-list-and-repetition-continuations) preserves list inference/consumption/check priority, repetition bounds/Copy rules, emission/loans and host OOM. Independent comparisons and deep sibling/error/OOM tests pass; the former pure-list failure at 4,096 now accepts. Variant-payload/call alternation still aborts at 256 before and after; remaining native callbacks and liveness/read/assignment walks keep Q-061 open. No new semantic or depth limit changes. All 1,793 ordinary conformance cases, 246 focused depth CLI checks and exact public check/lower parity (1,423/506) pass. Read-only Claude core/follow-up reviews found no production defects; their fixture gaps were corrected. Whole-frontend, loop/liveness and Phase 6 completion are not established.
The [enum-payload increment](source-expression-depth-audit.md#enum-payload-continuations) preserves lookup/arity-before-arguments, per-payload type/consumption/check order, empty/built-in construction, spans/loans and OOM. Independent shallow/deep/sibling and direct/public allocation tests pass; exact ordinary conformance coverage and final public check/lower parity (1,423/506) pass. The former enum-payload failure at 256 is repaired; nested assert still aborts at 1,024 before and after. Scoped read-only Claude reviews found no semantic defects; 331 core and 66 final supplementary CLI checks pass. Q-061 and Phase 6 remain open, with no semantic or new depth limit change.
+52 -3
View File
@@ -656,6 +656,55 @@ variant-payload/call probes accept 16 levels but abort in `prepareCall` →
Variant/place/builtin/control callbacks and liveness/read/assignment scans keep
Q-061 open; Q-060 full GC validation and Phase 6 gates remain separate.
## Enum-payload continuations
Enum payloads now share the scalar/call/struct/array/value-field driver.
Enum/variant lookup and arity still precede arguments. Each payload annotation
is resolved immediately before its consuming-name check and evaluation; exact
type checking precedes the next payload. Argument order, names, CFG, spans,
loans and delayed `enum.make` are preserved (spec 15 §5, §16). Built-in errors
and empty named variants finish immediately. A narrow private `VariantDispatch`
is widened explicitly at the call boundary. Queued states are stable caller-
arena allocations; their backing remains until arena destruction, including
on errors. Host OOM propagates without language diagnostics or public partial
AIR. No normative/format/feature/code/bundle/limit or ownership/runtime change.
The copied old constructor joins the shallow recursive oracle, passing 720
comparisons including lookup/arity priority, linear transfers, borrow/bytes,
boolean CFG, arrays and failure after a consumed argument. Type/emission/place
helpers and non-operand leaves remain shared. Deep tests cover 32,768 variant/
call levels with one or two payloads, exact sibling and constructor spans/order;
recovering direct/public and persistent backing failures cover nonempty,
empty and built-in constructors, arena cleanup and no swallowed allocation.
Build/units/format and both initial/final ordinary conformance runs pass with
exact coverage of all 1,793 cases (`variant-continuations-conformance-final.jsonl`
and its audit). Targeted error/generic/linear/nonvalue/inferred-content/
independent-error suites pass 26/42/49/635/302/234 checks; error/generic suites
are repeated on the final binary. Final public check/lower outputs are exact
(1,423/506; `variant-continuations-public-parity-final.json`). Nine bounded
assert/block/if comparisons remain exact through 256, without a frame-size
claim. The former enum-payload abort at 256 now accepts through 16,384.
The frozen initial core passes 331 focused depth CLI checks: ordinary/two/
generic chains accept through 65,536, mixed scalar/struct chains through
32,768. At 65,536 mixed levels the existing instruction limit reports E5101,
`max: 262144`, `found: 458754`. Exact bounded fuel/values, AIR and formatter
parity, and deep lookup/arity error records are checked. Final supplemental mismatch/empty-constructor checks pass 66 cases
(`variant-continuations-supplemental-depth.log`), including exact type-error
positions and empty-leaf checking/formatting through 65,536 with bounded
values/fuel/AIR parity. Pure recursive-type construction, loop/liveness and
arbitrary native callbacks are not established.
Read-only Claude core/follow-up reviews found no semantic defects
(`/tmp/aji-variant-continuations-review.md` and
`/tmp/aji-variant-continuations-followup-review.md`). Comments/dispatch and
fixture gaps were corrected; direct borrow/bytes, deep type-error and empty
CLI cases follow the review. Neither reviewer ran tests. Separate nested-assert
probes still abort at 1,024 before and after (`variant-followup-assert-probes.json`),
in `prepareCall` → `expr`. Builtin/place/control callbacks and liveness/read/
assignment walks keep Q-061 open; Q-060 full GC and Phase 6 gates remain separate.
## Remaining work
Follow-up checks accept 16 parenthesized/mixed-call levels but abort
@@ -670,7 +719,7 @@ includes a confirmed lowerer failure and inspection-only risks:
| Production path | Evidence and next scope |
|---|---|
| Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. |
| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field and array descent are repaired above. Variant-payload/call alternation still aborts at 256 in both binaries. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. |
| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Nested assert lowering still aborts at 1,024 in both binaries. Other callback depth remains unverified; include 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. |
The formatter's expression-marking traversal already uses a worklist, as
@@ -679,5 +728,5 @@ claim every listed callback fails, or that all other paths have been cleared.
Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is
independent. The five reviewed increments now have a scoped external review;
the host-OOM follow-up and intermediate repairs have no separate review.
The struct/value-field and array increments have the scoped reviews recorded
above.
The struct/value-field, array and enum-payload increments have the scoped
reviews recorded above.
+13
View File
@@ -695,3 +695,16 @@ alternation still aborts at 256 before and after. Focused depth CLI checks
core/follow-up reviews found no production defects; fixture gaps were corrected.
Q-061, Q-060 and Phase 6 remain open;
no normative/format/feature/code/bundle/limit or ownership/runtime change.
### Enum-payload depth increment
The [Q-061 enum increment](../design/source-expression-depth-audit.md#enum-payload-continuations)
shares payloads with scalar/call/aggregate continuations, preserving lookup,
arity, annotation/consumption/check order, spans, loans, empty/built-in rules
and OOM. Independent comparisons (720), deep sibling and allocator tests,
build/units/format, exact final conformance coverage and public check/lower
parity pass. Scoped Claude reviews found no semantic defects. The former
256-level abort is repaired; nested assert still aborts at 1,024 before and
after. Initial focused CLI checks (331) and final supplementary checks (66)
pass. Q-061, Q-060 and Phase 6 remain open. No normative/format/feature/
code/bundle/limit or ownership/runtime change.
+223 -14
View File
@@ -2014,6 +2014,7 @@ const Lowerer = struct {
.call => |x| return switch (try l.prepareCall(e, x.callee.*, x.args, false)) {
.done => |v| v,
.ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }),
.variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }),
},
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
.block => |b| {
@@ -2055,6 +2056,7 @@ const Lowerer = struct {
field_value: *FieldRead,
array_element: *ArrayConstruction,
array_repeat: ast.Expr,
variant_argument: *VariantConstruction,
};
var pending: std.ArrayList(Frame) = .empty;
defer pending.deinit(l.arena);
@@ -2114,6 +2116,17 @@ const Lowerer = struct {
want = c.element_ty;
continue;
},
.variant => |c| {
prepared = .none;
if (c.index == c.args.len) break try l.finishVariant(c);
c.current_ty = try l.typeOf(c.payload[c.index]);
const input = c.args[c.index];
try l.checkConsumingName(input);
try pending.append(l.arena, .{ .variant_argument = c });
e = input;
want = c.current_ty;
continue;
},
}
switch (e.kind) {
.not, .deref => |x| {
@@ -2167,6 +2180,11 @@ const Lowerer = struct {
.call => |x| switch (try l.prepareCall(e, x.callee.*, x.args, false)) {
.done => |v| break v,
.ordinary => |c| prepared = .{ .call = c },
.variant => |c| prepared = .{ .variant = c },
},
.variant => |x| switch (try l.prepareVariant(e, x.@"enum", x.name, &.{})) {
.done => |v| break v,
.variant => |c| prepared = .{ .variant = c },
},
.struct_lit => |x| prepared = .{ .structure = try l.prepareStruct(e, x.name, x.fields) },
.array_list => |xs| prepared = .{ .array = try l.prepareArray(e, xs, want) },
@@ -2271,6 +2289,13 @@ const Lowerer = struct {
prepared = .{ .structure = c };
continue :evaluate;
},
.variant_argument => |c| {
try l.checkOperandTy(c.args[c.index].span, v.ty, c.current_ty);
try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name }));
c.index += 1;
prepared = .{ .variant = c };
continue :evaluate;
},
.field_value => |f| v = try l.finishField(f, v),
.array_element => |c| {
const input = c.inputs[c.index];
@@ -2342,6 +2367,7 @@ const Lowerer = struct {
structure: *StructConstruction,
field: *FieldRead,
array: *ArrayConstruction,
variant: *VariantConstruction,
};
const OrdinaryCall = struct {
@@ -2354,12 +2380,13 @@ const Lowerer = struct {
names: std.ArrayList(u8) = .empty,
temps: std.ArrayList([]const u8) = .empty,
};
const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall };
const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction };
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value {
return switch (try l.prepareCall(e, callee, args, borrow_allowed)) {
.done => |v| v,
.ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }),
.variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }),
};
}
@@ -2387,7 +2414,10 @@ const Lowerer = struct {
l.linear_enabled = true;
return .{ .done = result };
};
if (callee.kind == .variant) return .{ .done = try l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args) };
if (callee.kind == .variant) return switch (try l.prepareVariant(e, callee.kind.variant.@"enum", callee.kind.variant.name, args)) {
.done => |v| .{ .done = v },
.variant => |c| .{ .variant = c },
};
if (try l.moduleCall(callee)) |name| {
// Reuse ordinary call typing/borrowing/lowering, including E7002.
const owned_name = try l.arena.dupe(u8, name);
@@ -2557,26 +2587,46 @@ const Lowerer = struct {
return l.def("s", c.ty, try l.fmt("struct.make {s}({s})", .{ try l.tyText(c.ty), c.names.items }), c.span);
}
const VariantDispatch = union(enum) { done: Value, variant: *VariantConstruction };
const VariantConstruction = struct {
span: Span,
ty: Ty,
variant: []const u8,
args: []const ast.Expr,
payload: []const ast.Type,
index: usize = 0,
current_ty: Ty = .void,
names: std.ArrayList(u8) = .empty,
};
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
return switch (try l.prepareVariant(e, enum_name, variant, args)) {
.done => |v| v,
.variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }),
};
}
fn prepareVariant(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!VariantDispatch {
const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
if (t == .builtin) {
_ = t.builtin.variantIndex(variant) orelse return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != 0) return l.fail("E7005", e.span, "built-in error variants have no payload", &.{.{ .name = "variant", .value = variant }});
return l.def("e", t, try l.fmt("error.const {s}.{s}", .{ enum_name, variant }), e.span);
return .{ .done = try l.def("e", t, try l.fmt("error.const {s}.{s}", .{ enum_name, variant }), e.span) };
}
const vs = l.m.types[t.named].kind.@"enum";
const v = for (vs) |x| {
if (std.mem.eql(u8, x.name, variant)) break x;
} else return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != v.payload.len) return l.fail("E7005", e.span, "wrong number of payload values", &.{ .{ .name = "variant", .value = variant }, .{ .name = "expected", .value = try l.fmt("{d}", .{v.payload.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var names: std.ArrayList(u8) = .empty;
for (args, v.payload, 0..) |a, pt, i| {
const ty = try l.typeOf(pt);
const av = try l.consuming(a, ty);
try l.checkOperandTy(a.span, av.ty, ty);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name }));
}
return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(t), variant, names.items }), e.span);
if (v.payload.len == 0) return .{ .done = try l.def("e", t, try l.fmt("enum.make {s}.{s}()", .{ try l.tyText(t), variant }), e.span) };
const c = try l.arena.create(VariantConstruction);
c.* = .{ .span = e.span, .ty = t, .variant = variant, .args = args, .payload = v.payload };
return .{ .variant = c };
}
fn finishVariant(l: *Lowerer, c: *const VariantConstruction) Error!Value {
return l.def("e", c.ty, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(c.ty), c.variant, c.names.items }), c.span);
}
const FieldRead = struct {
@@ -5284,7 +5334,7 @@ const ReferenceCalls = struct {
l.linear_enabled = true;
return result;
};
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (callee.kind == .variant) return ReferenceVariants.value(l, e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (try l.moduleCall(callee)) |name| {
// Reuse ordinary call typing/borrowing/lowering, including E7002.
const owned_name = try l.arena.dupe(u8, name);
@@ -5399,7 +5449,7 @@ const ReferenceCalls = struct {
};
// Copied former struct/field/length descent, linked to the independent
// shallow scalar/call/array oracle. Borrow-place and variant helpers remain
// shallow scalar/call/array/variant oracle. Borrow-place helpers remain
// shared and are outside this oracle's independence.
const ReferenceFields = struct {
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
@@ -5464,7 +5514,7 @@ const ReferenceFields = struct {
// Copied former list/repetition descent. Scalar/call/struct/field children
// use their shallow recursive references. Element-property, place and builtin
// helpers and ReferenceOperands fallback leaves (control, indices, names,
// moves and variants) remain shared, outside this oracle's independence.
// and moves) remain shared, outside this oracle's independence.
const ReferenceArrays = struct {
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
@@ -5494,6 +5544,33 @@ const ReferenceArrays = struct {
}
};
// Copied former enum construction. Payload descent uses the recursive
// scalar/call/aggregate oracle; type/consumption helpers and non-operand
// fallback leaves remain shared, outside this oracle's independence.
const ReferenceVariants = struct {
fn value(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
if (t == .builtin) {
_ = t.builtin.variantIndex(variant) orelse return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != 0) return l.fail("E7005", e.span, "built-in error variants have no payload", &.{.{ .name = "variant", .value = variant }});
return l.def("e", t, try l.fmt("error.const {s}.{s}", .{ enum_name, variant }), e.span);
}
const vs = l.m.types[t.named].kind.@"enum";
const v = for (vs) |x| {
if (std.mem.eql(u8, x.name, variant)) break x;
} else return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != v.payload.len) return l.fail("E7005", e.span, "wrong number of payload values", &.{ .{ .name = "variant", .value = variant }, .{ .name = "expected", .value = try l.fmt("{d}", .{v.payload.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var names: std.ArrayList(u8) = .empty;
for (args, v.payload, 0..) |a, pt, i| {
const ty = try l.typeOf(pt);
const av = try ReferenceCalls.consuming(l, a, ty);
try l.checkOperandTy(a.span, av.ty, ty);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name }));
}
return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(t), variant, names.items }), e.span);
}
};
// Independent pre-repair unary/binary expression derivation, linked to the
// recursive aggregate/call references. Other leaves share production handlers.
// This oracle is only for shallow operand trees.
@@ -5549,6 +5626,7 @@ const ReferenceOperands = struct {
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
.variant => |v| return ReferenceVariants.value(l, e, v.@"enum", v.name, &.{}),
.array_list, .array_rep => return ReferenceArrays.expr(l, e, want),
.call => |x| return ReferenceCalls.call(l, e, x.callee.*, x.args, false),
.struct_lit => |x| return ReferenceFields.structLit(l, e, x.name, x.fields),
@@ -8062,3 +8140,134 @@ test "persistent backing OOM in public array lowering frees output arena" {
}
}
}
const variantTestDeclarations = fieldTestDeclarations ++
"enum Payload { pair(i64, bool), two(i64, i64), item(Box), owner(own<i64>), array([i64; 2]), empty }\n";
test "variant continuations match former lookup arity consumption and payload order" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const expressions = [_][]const u8{
"Choice::none", "Choice::some", "Choice::some(1i64)", "Choice::some(1)",
"Choice::some(id(1i64))", "Choice::none(unknown)", "Choice::missing(unknown)", "Missing::some(unknown)",
"Box::some(unknown)", "Choice::some(unknown, false)", "Choice::some(true)", "Choice::some(void_call(b\"xy\"))",
"Choice::some(stop(b\"xy\"))", "Payload::pair(id(n), bool_id(true) and false)", "Payload::pair(true, unknown)", "Payload::pair(unknown, false)",
"Payload::pair(1i64, unknown)", "Payload::two(1i64, false)", "Payload::two(stop(b\"xy\"), unknown)", "Payload::owner(o)",
"Payload::owner(move o)", "Payload::owner(move n)", "Payload::item(Box { n: Choice::some(1i64).n })", "Payload::item(Box { n: id(n) })",
"Payload::array([1i64, 2])", "Payload::array([1i64; 2])", "Payload::array([1i64])", "Payload::array([1i64, false])",
"Payload::empty", "Payload::pair", "io_error::not_found", "io_error::missing(unknown)",
"io_error::not_found(unknown)", "alloc_error::budget_exceeded", "cap_error::not_subset", "Choice::some(p)",
"Payload::item(ref n)", "Payload::array(b\"xy\")", "Payload::two(take(move o), unknown)", "Payload::pair(take(move o), false)",
};
const forms = [_][]const u8{ "{s}", "Choice::some({s})", "[{s}]", "Box {{ n: {s} }}.n", "Payload::two({s}, unknown)", "not ({s})" };
inline for (forms) |form| for (expressions) |text| {
const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ variantTestDeclarations, try std.fmt.allocPrint(a, form, .{text}) }));
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .{ .int = "i64" }, .{ .named = 6 } }) |want| try expectFieldMatches(a, parsed.ok, e, want);
};
}
test "deep variant payloads interleave with calls and pending siblings" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, variantTestDeclarations)).ok;
const count = 32_768;
for ([_]bool{ false, true }) |two| {
var l = try fieldTestLowerer(a, m, unaryTestSpan(1));
const enum_name = if (two) "Payload" else "Choice";
const variant_name = if (two) "two" else "some";
const t = l.enumType(enum_name, unaryTestSpan(1)).?;
try l.sigs.put(a, "unwrap", .{ .params = try a.dupe(Ty, &.{t}), .ret = .{ .int = "i64" }, .air_name = "unwrap", .display_name = "unwrap" });
const unwrap: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .name = "unwrap" } };
const constructor: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .variant = .{ .@"enum" = enum_name, .name = variant_name } } };
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } };
for (0..count) |i| {
const span = unaryTestSpan(@intCast(i + 1));
const args = try a.alloc(ast.Expr, if (two) 2 else 1);
args[0] = e;
if (two) args[1] = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .int = .{ .text = "2" } } };
const input = try a.alloc(ast.Expr, 1);
input[0] = .{ .span = span, .kind = .{ .call = .{ .callee = &constructor, .type_arg = null, .args = args } } };
e = .{ .span = span, .kind = .{ .call = .{ .callee = &unwrap, .type_arg = null, .args = input } } };
}
const v = try l.expr(e, .{ .int = "i64" });
try std.testing.expect(v.ty.eql(.{ .int = "i64" }));
const insts = l.blocks.items[0].insts.items;
const stride: usize = if (two) 3 else 2;
try std.testing.expectEqual(stride * count + 1, insts.len);
for (0..count) |i| {
const at = stride * i + 1;
if (two) {
try std.testing.expect(std.mem.indexOf(u8, insts[at].text, " = const.i64 2") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(100_000 + i))), insts[at].span);
}
const make_at = at + @intFromBool(two);
try std.testing.expect(std.mem.indexOf(u8, insts[make_at].text, " = enum.make ") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[make_at].span);
try std.testing.expect(std.mem.indexOf(u8, insts[make_at + 1].text, " = call @unwrap(") != null);
try std.testing.expectEqualDeep(insts[make_at].span, insts[make_at + 1].span);
}
try std.testing.expect(l.problem == null and l.unimpl == null);
}
}
test "recovering OOM in variant continuations is a host error without partial AIR" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const expressions = [_][]const u8{ "Payload::pair(Box { n: id(n) }.n, true and bool_id(false))", "Choice::none", "io_error::not_found" };
for (expressions) |expression| {
const parsed = try parse_mod.parse(fixture.allocator(), try std.fmt.allocPrint(fixture.allocator(), "{s}fn f() -> void effects [] {{ return {s}; }}", .{ variantTestDeclarations, expression }));
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
var fail_at: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 512);
var output: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer output.deinit();
var l = try fieldTestLowerer(output.allocator(), parsed.ok, e.span);
var failure: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
l.arena = failure.allocator();
const result = l.expr(e, null);
if (failure.failed) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null and l.unimpl == null);
try std.testing.expectEqual(fail_at + 1, failure.attempts);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
} else {
_ = try result;
break;
}
}
}
}
test "public variant lowering propagates each allocation failure and frees its arena" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const parsed = try parse_mod.parse(fixture.allocator(), "module oom\nenum Wrap { some(i64), empty }\nfn unwrap(w: Wrap) -> i64 effects [] { return match w { Wrap::some(x) => x, Wrap::empty => 0i64 }; }\nfn main() -> i64 effects [] { return unwrap(Wrap::some(- unwrap(Wrap::empty))); }\n");
try std.testing.expect(parsed == .ok);
for ([_]bool{ false, true }) |persistent| {
var fail_at: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 1024);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at });
var output: std.heap.ArenaAllocator = .init(if (persistent) failing.allocator() else std.testing.allocator);
var recovering: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
const result = lower(if (persistent) output.allocator() else recovering.allocator(), parsed.ok);
output.deinit();
if (persistent) try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
const failed = if (persistent) failing.has_induced_failure else recovering.failed;
if (failed) {
try std.testing.expectError(error.OutOfMemory, result);
if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts);
} else {
// Output bytes died with the arena; only inspect the result tag.
try std.testing.expect((try result) == .ok);
break;
}
}
}
}
+107
View File
@@ -529,6 +529,113 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
assert cli(command, path, code=1) == expected
print(f'array invalid depth: {depth}', flush=True)
# Enum payloads share scalar/call/aggregate continuations; validate arity
# before arguments and type/consume/check each payload in source order.
for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536):
for kind in ('variant-call', 'two-payload', 'generic-variant', 'mixed-variant'):
if depth == 32768 and kind != 'mixed-variant':
continue
generic, two, mixed = kind == 'generic-variant', kind == 'two-payload', kind == 'mixed-variant'
constructor = 'Wrap::<i64>::some' if generic else 'Wrap::some'
enum = 'enum Wrap<T> { some(T) }\n' if generic else ('enum Wrap { some(i64, i64) }\n' if two else 'enum Wrap { some(i64) }\n')
annotation = 'Wrap<i64>' if generic else 'Wrap'
binders = 'x, y' if two else 'x'
helper = enum + f'fn unwrap(w: {annotation}) -> i64 effects [] {{ return match w {{ {constructor}({binders}) => x }}; }}\n'
prefix, suffix = f'unwrap({constructor}(', ', 2))' if two else '))'
if mixed:
helper += 'struct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\n'
prefix, suffix = 'unwrap(Wrap::some(Box { n: - id(', ') }.n))'
path = root / f'enum-{kind}-{depth}.aji'
path.write_text('module depth\n' + helper + 'fn main() -> i64 effects [] { return ' +
prefix * depth + '1i64' + suffix * depth + '; }\n')
main_instructions = (7 if mixed else 3 if two else 2) * depth + 2
limited = main_instructions > 262144
checked = cli('check', path, code=1 if limited else 0)
if limited:
diagnostic = json.loads(checked)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == checked
else:
assert checked == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or
line.strip().startswith((b'ret ', b'br ', b'enum.switch ')) for line in lowered.splitlines())
assert instructions == main_instructions + 3 + int(mixed), (kind, depth, instructions)
if depth <= 1024:
fuel = main_instructions + (4 if mixed else 3) * depth
value = -1 if mixed and depth % 2 else 1
assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': value}
assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', fuel) == cli('run', path, '--fuel', fuel)
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
formatted_check = cli('check', formatted, code=1 if limited else 0)
if limited:
diagnostic = json.loads(formatted_check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
else:
assert formatted_check == b''
assert cli('lower', formatted) == lowered
print(f'variant expression depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
for leaf, code in (('missing()', 'E7002'), ('Wrap::some(missing(), true)', 'E7005'),
('Wrap::absent(missing())', 'E7002'), ('Wrap::some(true)', 'E7005')):
path = root / f'variant-invalid-{depth}-{code}-{len(leaf)}.aji'
header = 'fn main() -> i64 effects [] { return '
prefix = 'unwrap(Wrap::some(' * depth
path.write_text('module depth\nenum Wrap { some(i64) }\nfn unwrap(w: Wrap) -> i64 effects [] { return match w { Wrap::some(x) => x }; }\n' +
header + prefix + leaf + '))' * depth + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
assert (error['code'], error['line'], error['col'], error['file']) == (
code, 4, len(header) + len(prefix) + (len('Wrap::some(') if leaf == 'Wrap::some(true)' else 0) + 1, str(path)), error
if code == 'E7005':
assert (error['expected'], error['found']) == (('i64', 'bool') if leaf == 'Wrap::some(true)' else ('1', '2')), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'variant invalid depth: {depth}', flush=True)
# Empty named constructors also finish immediately at the deepest leaf.
for depth in (0, 1, 16, 1024, 65536):
path = root / f'empty-variant-{depth}.aji'
path.write_text('module depth\nenum Wrap { some(i64), empty }\n' +
'fn unwrap(w: Wrap) -> i64 effects [] { return match w { Wrap::some(x) => x, Wrap::empty => 1i64 }; }\n' +
'fn main() -> i64 effects [] { return ' + 'unwrap(Wrap::some(' * depth +
'unwrap(Wrap::empty)' + '))' * depth + '; }\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or
line.strip().startswith((b'ret ', b'br ', b'enum.switch ')) for line in lowered.splitlines())
assert instructions == 2 * depth + 8, (depth, instructions)
if depth <= 1024:
fuel = 5 * depth + 7
assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': 1}
assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', fuel) == cli('run', path, '--fuel', fuel)
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
assert cli('check', formatted) == b''
assert cli('lower', formatted) == lowered
print(f'empty variant depth: {depth}', flush=True)
# Builtin callbacks are still native; preserve the prior diagnostic at
# bounded nesting while ordinary calls gain explicit continuations.
for depth in (16, 64, 256):