diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 09b065d..63601e0 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -545,4 +545,6 @@ Audit these paths separately with finite public/generated source inputs before c The [ordinary-call increment](source-expression-depth-audit.md#ordinary-call-argument-continuations) shares call arguments with scalar continuations, preserving signature/error priority, left-to-right consumption, loans, retained parents, CFG and host OOM behavior. Stable arena-owned states retain bounded builtin/control regression capacity. Build/units/format checks, exact ordinary conformance coverage and call-related CLI suites pass. A separate alternating struct/field program still aborts at 1,024 before and after; builtin/variant/place, aggregate/control and remaining liveness/read/assignment paths keep Q-061 open. No semantic or depth limit changes and no fresh external review are claimed. -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; nested array literals still abort 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 [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. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 7ca7be7..9793039 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -599,6 +599,63 @@ The follow-up's unverified CLI E5101 byte-parity assumption is covered by the 302-check run. Deep boolean/field interactions beyond the shallow oracle, borrow-place depth and full Q-061 completion are not established. +## Array list and repetition continuations + +Array initializers now share the scalar/call/struct/value-field driver. Lists +retain the 1..64 size check before children, contextual or first-element +inference, left-to-right explicit consumption, and element-position checks +before exact-type checks. Their result uses actual element type and length. +Repetitions retain the 1..2^32 bound before the operand, non-consuming operand +evaluation, then member/Copy checks and `array.splat` (spec 15 §5, §16). +Queries, CFG, names, spans, loans and host OOM policy are unchanged. Stable list +states and worklist buffers have caller-arena lifetime, including on errors; +public backing-failure tests observe arena destruction, not list-deinit frees. +No normative/format/feature/code/bundle, ownership/runtime or limit change. + +The copied former array descent joins the independent shallow scalar/call/ +struct/field oracle. It passes 1,036 comparisons including inference, consuming +names, borrow-before-Copy, position-before-type priority, void/never, boolean +CFG and synthetic list-size boundaries. Property/emission/place helpers and +non-operand fallback leaves remain shared. Separate 32,768-level tests cover +list/repetition/call alternation with bounded types, an inferred outer list +resuming at an unsuffixed or erroring sibling, exact emission/spans, and innermost +errors. +Recovering allocation sweeps include 64 inputs and an outer repetition; +persistent public failures check arena cleanup and no partial AIR/diagnostic. +The final error-sibling test passes after entry-by-entry prefix comparison: +a fixed-size-array deep comparison initially overflowed the test helper's native +stack (`array-continuations-unit-siblings.log`, final terminal exit 0). + +Build/unit/format checks and all 1,793 ordinary conformance cases pass with +exact coverage (`array-continuations-conformance.jsonl` and its audit). +Array-literal/argument/linear/nonvalue/inferred-content/independent-error CLI +suites pass 152/85/49/635/302/234 checks. Nine before/after assert/block/if +probes remain byte-identical through 256 (`array-continuations-callback-parity.json`). +The former pure-list abort at 4,096 now accepts +(`array-continuations-initial-probe.json`). Pure nested types produce quadratic +AIR text; this does not claim arbitrary-sized successful aggregate output. +The focused CLI suite passes 246 checks (`array-continuations-focused-depth.log`): +list/repetition calls accept through 65,536, mixed scalar/struct/array calls +through 32,768; at 65,536 mixed levels the existing E5101 instruction limit +reports `max: 262144`, `found: 458754`. Both pure forms check at 4,096; bounded +runs check exact values/fuel and AIR parity, formatting remains a fixed point, +and deep unknown/bound errors retain exact CLI records. Frozen public source +checks/lowerings are byte-identical (1,423/506; +`array-continuations-public-parity.json`). These are straight-line shapes; +loop/liveness/assignment callers are not thereby validated. + +Claude's read-only core review found no production defect, but identified two +fixture gaps: an unbound borrow name and missing position-before-type cases. +Both were corrected, with additional sibling/inference and OOM coverage. +The read-only follow-up found no concrete defects and confirmed the CLI counts, +fuel and run-record shape (`/tmp/aji-array-continuations-review.md` and +`/tmp/aji-array-continuations-followup-review.md`). Neither reviewer ran tests; +the final test-only error-sibling addition follows that review. Separate +variant-payload/call probes accept 16 levels but abort in `prepareCall` → +`variantValue` → `consuming` at 256 in both binaries (`array-followup-variant-probes.json`). +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. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -613,7 +670,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 and struct/value-field descent are repaired above. Nested array-literal lowering still aborts at 4,096 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 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 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 @@ -622,4 +679,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 increment has the scoped reviews recorded above. +The struct/value-field and array increments have the scoped reviews recorded +above. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 4ec5ae4..5457753 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -681,3 +681,17 @@ No normative/bundle/feature/code/limit or ownership/runtime rule changes. Remaining Q-061 callbacks/walks, Q-060 validation and Phase 6 exit gates remain open. Independent read-only Claude core/follow-up reviews found no concrete defects; neither ran tests or established whole-Q-061 completion. + +### Array-expression depth increment + +The [Q-061 array increment](../design/source-expression-depth-audit.md#array-list-and-repetition-continuations) +shares lists/repetitions with scalar/call/struct/field continuations, preserving +inference, explicit consumption, check order, spans, loans, Copy rules and OOM. +Independent comparisons (1,036), deep bounded-type/sibling/error and OOM tests, +build/units/format, exact ordinary conformance coverage and six targeted CLI +suites pass. The pure-list failure at 4,096 is repaired; enum-payload/call +alternation still aborts at 256 before and after. Focused depth CLI checks +(246) and frozen public check/lower parity (1,423/506) pass. Read-only Claude +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. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index dbc0180..05784a7 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -1983,7 +1983,7 @@ const Lowerer = struct { fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { switch (e.kind) { - .not, .neg, .deref, .cast, .binary => return l.operandExpr(e, want), + .not, .neg, .deref, .cast, .binary, .array_list, .array_rep => return l.operandExpr(e, want), .specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}), .int => |x| { const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse @@ -2009,27 +2009,6 @@ const Lowerer = struct { try l.endNow(p.ends, e.span); return v; }, - .array_list => |xs| { - if (xs.len == 0 or xs.len > 64) return l.invalid(.implementation_limit, e.span, "array literal requires 1..64 complete elements", &.{}); - var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null; - var names: std.ArrayList(u8) = .empty; - for (xs, 0..) |x, i| { - const v = try l.consuming(x, ty); - try l.arrayElement(x.span, v.ty, false); - if (ty) |t| try l.checkOperandTy(x.span, v.ty, t) else ty = v.ty; - try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); - } - const at = try l.arrayOf(ty.?, xs.len); - return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ try l.tyText(at), names.items }), e.span); - }, - .array_rep => |x| { - if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{}); - const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null; - const v = try l.expr(x.e.*, want_elem); - try l.arrayElement(x.e.span, v.ty, true); - const at = try l.arrayOf(v.ty, x.len); - return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(at), v.name }), e.span); - }, .bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}), .borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}), .call => |x| return switch (try l.prepareCall(e, x.callee.*, x.args, false)) { @@ -2058,7 +2037,7 @@ const Lowerer = struct { } } - // Scalar operands, ordinary calls, struct initializers and value fields + // Scalar operands, ordinary calls, aggregate initializers and value fields // share one worklist for arbitrary alternation of those expression forms. fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { return l.operandExprPrepared(initial, initial_want, .none); @@ -2074,6 +2053,8 @@ const Lowerer = struct { call_argument: *OrdinaryCall, struct_field: *StructConstruction, field_value: *FieldRead, + array_element: *ArrayConstruction, + array_repeat: ast.Expr, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); @@ -2123,6 +2104,16 @@ const Lowerer = struct { want = f.want; continue; }, + .array => |c| { + prepared = .none; + if (c.index == c.inputs.len) break try l.finishArray(c); + const input = c.inputs[c.index]; + try l.checkConsumingName(input); + try pending.append(l.arena, .{ .array_element = c }); + e = input; + want = c.element_ty; + continue; + }, } switch (e.kind) { .not, .deref => |x| { @@ -2178,6 +2169,13 @@ const Lowerer = struct { .ordinary => |c| prepared = .{ .call = 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) }, + .array_rep => |x| { + if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{}); + try pending.append(l.arena, .{ .array_repeat = e }); + want = if (want) |w| (if (w == .array) w.array.elem else null) else null; + e = x.e.*; + }, .field => |x| switch (try l.prepareFieldExpression(e, x.e.*, x.name)) { .done => |v| break v, .read => |f| prepared = .{ .field = f }, @@ -2274,6 +2272,21 @@ const Lowerer = struct { continue :evaluate; }, .field_value => |f| v = try l.finishField(f, v), + .array_element => |c| { + const input = c.inputs[c.index]; + try l.arrayElement(input.span, v.ty, false); + if (c.element_ty) |ty| try l.checkOperandTy(input.span, v.ty, ty) else c.element_ty = v.ty; + try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name })); + c.index += 1; + prepared = .{ .array = c }; + continue :evaluate; + }, + .array_repeat => |parent| { + const x = parent.kind.array_rep; + try l.arrayElement(x.e.span, v.ty, true); + const at = try l.arrayOf(v.ty, x.len); + v = try l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(at), v.name }), parent.span); + }, }; return v; } @@ -2328,6 +2341,7 @@ const Lowerer = struct { call: *OrdinaryCall, structure: *StructConstruction, field: *FieldRead, + array: *ArrayConstruction, }; const OrdinaryCall = struct { @@ -2483,6 +2497,26 @@ const Lowerer = struct { return result; } + const ArrayConstruction = struct { + span: Span, + inputs: []const ast.Expr, + element_ty: ?Ty, + index: usize = 0, + names: std.ArrayList(u8) = .empty, + }; + + fn prepareArray(l: *Lowerer, e: ast.Expr, inputs: []const ast.Expr, want: ?Ty) Error!*ArrayConstruction { + if (inputs.len == 0 or inputs.len > 64) return l.invalid(.implementation_limit, e.span, "array literal requires 1..64 complete elements", &.{}); + const c = try l.arena.create(ArrayConstruction); + c.* = .{ .span = e.span, .inputs = inputs, .element_ty = if (want) |w| (if (w == .array) w.array.elem else null) else null }; + return c; + } + + fn finishArray(l: *Lowerer, c: *const ArrayConstruction) Error!Value { + const at = try l.arrayOf(c.element_ty.?, c.inputs.len); + return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ try l.tyText(at), c.names.items }), c.span); + } + const StructConstruction = struct { span: Span, ty: Ty, @@ -5364,10 +5398,8 @@ const ReferenceCalls = struct { } }; -// Independent pre-repair unary/binary expression derivation. Other leaves -// share expression handlers; this oracle is only for shallow operand trees. // Copied former struct/field/length descent, linked to the independent -// shallow scalar/call oracle. Borrow-place and array/variant helpers remain +// shallow scalar/call/array oracle. Borrow-place and variant 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 { @@ -5429,6 +5461,42 @@ 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. +const ReferenceArrays = struct { + fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { + switch (e.kind) { + .array_list => |xs| { + if (xs.len == 0 or xs.len > 64) return l.invalid(.implementation_limit, e.span, "array literal requires 1..64 complete elements", &.{}); + var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null; + var names: std.ArrayList(u8) = .empty; + for (xs, 0..) |x, i| { + const v = try ReferenceCalls.consuming(l, x, ty); + try l.arrayElement(x.span, v.ty, false); + if (ty) |t| try l.checkOperandTy(x.span, v.ty, t) else ty = v.ty; + try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); + } + const at = try l.arrayOf(ty.?, xs.len); + return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ try l.tyText(at), names.items }), e.span); + }, + .array_rep => |x| { + if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{}); + const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null; + const v = try ReferenceOperands.expr(l, x.e.*, want_elem); + try l.arrayElement(x.e.span, v.ty, true); + const at = try l.arrayOf(v.ty, x.len); + return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(at), v.name }), e.span); + }, + else => unreachable, + } + } +}; + +// 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. const ReferenceOperands = struct { fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { switch (e.kind) { @@ -5481,6 +5549,7 @@ const ReferenceOperands = struct { }; return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); }, + .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), .field => |x| return if (std.mem.eql(u8, x.name, "len")) ReferenceFields.lenOf(l, e, x.e.*) else ReferenceFields.fieldValue(l, e, x.e.*, x.name), @@ -7804,3 +7873,192 @@ test "persistent backing OOM in public struct field lowering frees output arena" } } } + +test "array continuations match former inference consumption and diagnostic priority" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "[1i64]", "[1]", "[1, 2i64]", "[1i64, 2]", "[true, false]", + "[1i64, true, unknown]", "[true, unknown]", "[unknown, false]", "[1i64, p]", "[1i64, void_call(b\"xy\")]", + "[1i64, sl]", "[n, id(n)]", "[id(1i64), Box { n: 2i64 }.n]", "[[1i64], [2i64]]", "[[1i64; 2], [2i64; 2]]", + "[[1i64], [2i64, 3i64]]", "[o]", "[move o]", "[move o, move o]", "[move n]", + "[p]", "[ref n]", "[b\"xy\"]", "[void_call(b\"xy\"), unknown]", "[stop(b\"xy\"), unknown]", + "[Box { n: unknown }, unknown]", "[bool_id(true) and false, true or bool_id(false)]", "[1i64; 1]", "[1; 2]", "[true; 2]", + "[unknown; 0]", "[unknown; 4294967297]", "[unknown; 4294967296]", "[id(n); 2]", "[[1i64; 2]; 2]", + "[o; 2]", "[move o; 2]", "[p; 2]", "[void_call(b\"xy\"); 2]", "[stop(b\"xy\"); 2]", + "[Bool { flag: true and bool_id(false) }.flag; 2]", "[1i64, 2i64].len", "[id(unknown); 2].len", + }; + const forms = [_][]const u8{ "{s}", "[{s}]", "[{s}; 2]", "id({s})", "Box {{ n: {s} }}.n", "- ({s})" }; + var shape: Ty.Arr = .{ .elem = .{ .int = "i64" }, .len = 2 }; + var nested: Ty.Arr = .{ .elem = .{ .array = &shape }, .len = 1 }; + const wants = [_]?Ty{ null, .{ .int = "i64" }, .{ .array = &shape }, .{ .array = &nested } }; + inline for (forms) |form| for (expressions) |text| { + const expression = try std.fmt.allocPrint(a, form, .{text}); + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ fieldTestDeclarations, expression })); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for (wants) |want| try expectFieldMatches(a, parsed.ok, e, want); + }; + // Parser grammar cannot produce an empty list. Exercise lowerer's frozen + // list-size boundary with synthetic ASTs, including a forbidden 65th input. + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + const span = unaryTestSpan(1); + const xs = try a.alloc(ast.Expr, 65); + for (xs) |*x| x.* = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } }; + for ([_]usize{ 0, 1, 64, 65 }) |n| try expectFieldMatches(a, m, .{ .span = span, .kind = .{ .array_list = xs[0..n] } }, null); +} + +test "deep list repetition and call alternation retains bounded types and emission spans" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + const count = 32_768; + for ([_]bool{ false, true }) |repeated| { + var l = try fieldTestLowerer(a, m, unaryTestSpan(1)); + const array = try l.arrayOf(.{ .int = "i64" }, 1); + try l.sigs.put(a, "one", .{ .params = try a.dupe(Ty, &.{array}), .ret = .{ .int = "i64" }, .air_name = "one", .display_name = "one" }); + const callee: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .name = "one" } }; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } }; + for (0..count) |i| { + const span = unaryTestSpan(@intCast(i + 1)); + const child = try a.create(ast.Expr); + child.* = e; + const input = try a.alloc(ast.Expr, 1); + input[0] = if (repeated) .{ .span = span, .kind = .{ .array_rep = .{ .e = child, .len = 1 } } } else .{ .span = span, .kind = .{ .array_list = child[0..1] } }; + e = .{ .span = span, .kind = .{ .call = .{ .callee = &callee, .type_arg = null, .args = input } } }; + } + // The outer list infers its type only after the deep first child; + // then resumes at a pending unsuffixed sibling with that inferred type. + const outer_span = unaryTestSpan(90_001); + const siblings = try a.alloc(ast.Expr, 2); + siblings[0] = e; + siblings[1] = .{ .span = unaryTestSpan(90_002), .kind = .{ .int = .{ .text = "2" } } }; + const v = try l.expr(.{ .span = outer_span, .kind = .{ .array_list = siblings } }, null); + try std.testing.expect(v.ty == .array and v.ty.array.len == 2); + try std.testing.expect(v.ty.array.elem.eql(.{ .int = "i64" })); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, 2 * count + 3), insts.len); + for (0..count) |i| { + const at = 2 * i + 1; + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[at].span); + try std.testing.expectEqualDeep(insts[at].span, insts[at + 1].span); + try std.testing.expect(std.mem.indexOf(u8, insts[at].text, if (repeated) " = array.splat array " else " = array.make array(") != null); + try std.testing.expect(std.mem.indexOf(u8, insts[at + 1].text, " = call @one(") != null); + } + try std.testing.expect(std.mem.indexOf(u8, insts[insts.len - 2].text, " = const.i64 2") != null); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(90_002)), insts[insts.len - 2].span); + try std.testing.expect(std.mem.indexOf(u8, insts[insts.len - 1].text, " = array.make array(") != null); + try std.testing.expectEqualDeep(@as(?Span, outer_span), insts[insts.len - 1].span); + try std.testing.expect(l.problem == null and l.unimpl == null); + + // The erroring sibling follows the same completed deep prefix. Its + // value is emitted before the type check, but no outer make is emitted. + siblings[1].kind = .{ .boolean = true }; + var rejected = try fieldTestLowerer(a, m, unaryTestSpan(1)); + try rejected.sigs.put(a, "one", l.sigs.get("one").?); + try std.testing.expectError(error.Lower, rejected.expr(.{ .span = outer_span, .kind = .{ .array_list = siblings } }, null)); + try std.testing.expectEqualStrings("E7005", rejected.problem.?.code); + try std.testing.expectEqualDeep(siblings[1].span, rejected.problem.?.span); + const prefix = rejected.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, 2 * count + 2), prefix.len); + // Compare entries rather than comptime-sized array pointers: a deep + // comparison of those pointers copies their whole arrays on the stack. + for (0..2 * count + 1) |i| { + try std.testing.expectEqualStrings(insts[i].text, prefix[i].text); + try std.testing.expectEqualDeep(insts[i].span, prefix[i].span); + try std.testing.expectEqual(insts[i].constant, prefix[i].constant); + } + try std.testing.expect(std.mem.indexOf(u8, prefix[prefix.len - 1].text, " = const.bool true") != null); + try std.testing.expectEqualDeep(@as(?Span, siblings[1].span), prefix[prefix.len - 1].span); + try std.testing.expectEqual(@as(usize, 0), rejected.out.items.len); + } +} + +test "deep inferred array descent reaches exact inner errors without native recursion" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + for ([_]bool{ false, true }) |repeated| { + var l = try fieldTestLowerer(a, m, unaryTestSpan(1)); + const leaf_span = unaryTestSpan(90_000); + var e: ast.Expr = .{ .span = leaf_span, .kind = .{ .name = "unknown" } }; + for (0..32_768) |i| { + const child = try a.create(ast.Expr); + child.* = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = if (repeated) .{ .array_rep = .{ .e = child, .len = 1 } } else .{ .array_list = child[0..1] } }; + } + try std.testing.expectError(error.Lower, l.expr(e, null)); + try std.testing.expectEqualStrings("E7002", l.problem.?.code); + try std.testing.expectEqualDeep(leaf_span, l.problem.?.span); + try std.testing.expectEqual(@as(usize, 0), l.blocks.items[0].insts.items.len); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + } +} + +test "recovering OOM in array continuations propagates without source diagnosis" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + var wide: std.ArrayList(u8) = .empty; + defer wide.deinit(fixture.allocator()); + try wide.append(fixture.allocator(), '['); + for (0..64) |i| { + if (i != 0) try wide.appendSlice(fixture.allocator(), ", "); + try wide.appendSlice(fixture.allocator(), "id(n)"); + } + try wide.append(fixture.allocator(), ']'); + const expressions = [_][]const u8{ + "[[Box { n: id(n) }.n; 2], [1i64, 2i64]]", + "[[id(n), id(n)]; 2]", + wide.items, + }; + for (expressions) |expression| { + const source = try std.fmt.allocPrint(fixture.allocator(), "{s}fn f() -> void effects [] {{ return {s}; }}", .{ fieldTestDeclarations, expression }); + const parsed = try parse_mod.parse(fixture.allocator(), source); + 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 < 2048); + 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 "persistent backing OOM in public array lowering frees output arena" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const parsed = try parse_mod.parse(fixture.allocator(), "module oom\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> usize effects [] { let a = [[id(1i64); 2], [2i64, 3i64]]; return a.len; }\n"); + try std.testing.expect(parsed == .ok); + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 128); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at }); + var output: std.heap.ArenaAllocator = .init(failing.allocator()); + const result = lower(output.allocator(), parsed.ok); + output.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + try std.testing.expect((try result) == .ok); + break; + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 258c724..0602da2 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -450,6 +450,85 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert cli(command, path, code=1) == expected print(f'struct field invalid depth: {depth}', flush=True) + # Lists and repetitions suspend in the same driver as calls/scalars/fields. + for depth in (0, 1, 16, 1024, 16384, 32768, 65536): + for kind in ('list-call', 'repeat-call', 'mixed-array'): + if depth == 32768 and kind != 'mixed-array': + continue + prefix, suffix = ('one([', '; 1])' if kind == 'repeat-call' else '])') + if kind == 'mixed-array': + prefix, suffix = 'Box { n: one([- id(', ')]) }.n' + helper = 'fn one(a: [i64; 1]) -> i64 effects [] { let (x) = array.unpack(a); return x; }\n' + mixed = kind == 'mixed-array' + if mixed: + helper += 'struct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\n' + path = root / f'array-{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 2) * depth + 2 + limited = main_instructions > 262144 + check = cli('check', path, code=1 if limited else 0) + if limited: + diagnostic = json.loads(check) + 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) == check + else: + assert check == b'' + lowered = cli('lower', path) + instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or + line.strip().startswith((b'ret ', b'array.unpack ')) for line in lowered.splitlines()) + assert instructions == main_instructions + 2 + int(mixed), (kind, depth, instructions) + if depth <= 1024: + fuel = main_instructions + (3 if mixed else 2) * depth + value = -1 if mixed and depth % 2 else 1 + assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': value, 'stdout': '', 'stderr': '', 'files': {}} + assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'stdout': '', 'stderr': '', 'files': {}} + 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'array expression depth: {kind} {depth}', flush=True) + + # Pure nested arrays produce quadratic AIR type text. Keep success probes + # at the confirmed former native-failure checkpoint instead of 65k output. + for repeated in (False, True): + path = root / f'pure-array-{repeated}-4096.aji' + path.write_text('module depth\nfn main() -> i64 effects [] { let a = ' + + '[' * 4096 + '1i64' + ('; 1]' if repeated else ']') * 4096 + '; return 0i64; }\n') + assert cli('check', path) == b'' + print(f'pure array depth: {repeated} 4096', flush=True) + + for depth in (1024, 16384, 65536): + for repeated in (False, True): + for leaf, code in (('missing()', 'E7002'), ('[missing(); 0]', 'E7005')): + path = root / f'array-invalid-{depth}-{repeated}-{code}.aji' + header = 'fn main() -> i64 effects [] { let a = ' + path.write_text('module depth\n' + header + '[' * depth + leaf + + ('; 1]' if repeated else ']') * depth + '; return 0i64; }\n') + expected = cli('check', path, code=1) + error = json.loads(expected) + assert (error['code'], error['line'], error['col'], error['file']) == ( + code, 2, len(header) + depth + 1, str(path)), error + for command in ('lower', 'run', 'report', 'explore'): + assert cli(command, path, code=1) == expected + print(f'array invalid 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):