diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 043ec1d..6d64b62 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -571,4 +571,6 @@ The [spawn increment](source-expression-depth-audit.md#task-spawn-argument-conti The [mutex make/take increment](source-expression-depth-audit.md#mutex-maketake-operand-continuations) preserves consuming/content/type priority, explicit moves, spans, loans, emission and host OOM. Build/units/format, lifetime/related/CFG and 310 focused CLI checks pass; scalar checks and original/formatted lower reach 65,536, mixed checks reach 32,768 then existing E5101, runtime/source-AIR/fuel reach 1,024 and rejected positions reach 65,536. All 1,793 ordinary conformance files have exact successful coverage. Frozen public check/lower parity passes (1,423/506) over `tests/conformance/**/*.aji`; read-only Claude core/final reviews found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. At that mutex checkpoint index operands aborted at 1,024 before/after; other walks, Q-060 and Phase 6 remain open. No semantic or depth-limit change. -The [scalar index operand increment](source-expression-depth-audit.md#scalar-index-operand-continuations) preserves base/type/operand priority, usize hints, bounds facts, unchecked state, loans, load/end order, spans and host OOM. Build/units/format and store-mode/array-argument/lifetime/CFG suites pass; exact ordinary conformance (1,793), public frozen parity (1,423/506), the original focused run passes 318 CLI checks (check through 32,768 then existing E5101 at 65,536; lower/fmt through 65,536; runtime/fuel through 1,024), and separate overlapping 30-call fuel/28-call CFG/deref/proven-context subsets pass. Read-only Claude core/final reviews found no production defect and their fixture/wording suggestions are covered. The recorded nested-array base-index probe still aborts at 1,024 before/after, with other place/control/liveness callbacks, Q-060 and Phase 6 open. No semantic or new depth-limit change. +The [scalar index operand increment](source-expression-depth-audit.md#scalar-index-operand-continuations) preserves base/type/operand priority, usize hints, bounds facts, unchecked state, loans, load/end order, spans and host OOM. Build/units/format and store-mode/array-argument/lifetime/CFG suites pass; exact ordinary conformance (1,793), public frozen parity (1,423/506), the original focused run passes 318 CLI checks (check through 32,768 then existing E5101 at 65,536; lower/fmt through 65,536; runtime/fuel through 1,024), and separate overlapping 30-call fuel/28-call CFG/deref/proven-context subsets pass. Read-only Claude core/final reviews found no production defect and their fixture/wording suggestions are covered. At that scalar-operand checkpoint the recorded nested-array base-index probe still aborted at 1,024 before/after; its subsequent repair is recorded below. Other place/control/liveness callbacks, Q-060 and Phase 6 remain open. No semantic or new depth-limit change. + +The [raw-place base increment](source-expression-depth-audit.md#raw-place-base-continuations) repairs the recorded 1,024-level nested-array base failure using iterative field/index projections and one ancestor-name list. Borrow modes, parents, child-first ends, range ordering, facts, unchecked selection, spans and host OOM separation are preserved. Exact ordinary conformance coverage, public check/lower parity and 159 focused CLI calls pass; expanded units pass, and scoped read-only Claude core/final reviews found no production defect. Follow-up block/if probes confirm remaining parser aborts at 1,024 before/after. Q-061, Q-060 full GC validation and Phase 6 remain open; no semantic or depth-limit change. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 7771f66..0fb9f68 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -1070,8 +1070,97 @@ expression-suite, control/liveness or runtime-depth closure claim. Follow-up base-index nesting `a[0usize][0usize]...` on nested length-one arrays accepts 16/256 but aborts at 1,024 before/after this operand repair. `index-operand-next-probes.json` and matching raw files retain the evidence. -Place base/range/borrow, graph/control and other native callbacks still need -repair/audit; Q-061, Q-060 full GC and Phase 6 remain open. +At that operand checkpoint place base/range/borrow, graph/control and other +native callbacks still needed repair/audit. Raw place bases are repaired in +the next section; Q-061, Q-060 full GC and Phase 6 remain open. + +## Raw place base continuations + +The recorded nested-array `a[0usize][0usize]...` failure at 1,024 is +repaired. `placeRaw` collects field/index projections, evaluates the leaf, +then resumes projections inside out. It preserves mutable mode, diagnostic +and emission spans, field lookup before outer projections, base validation +before bounds, lo/check/hi/check order, parent identities, current proven +facts and the outermost unchecked index. The unchanged leaf still calls +`expr` for dereference; bounds also enter expression lowering. Those callback +combinations are not whole-frontend closure evidence. + +One owned list accumulates ancestor names in the original order; consumers +still end children before parents. This removes the old per-projection full +list copy. Frames and lists use the caller arena: `deinit` does not promise +physical release before arena destruction. The returned slice remains stable; +other callers' slices are never mutated. Host allocation errors propagate +without language diagnostics or partial public AIR. Private state after host +OOM is not a recoverable language contract; `uncheckedPlace` still clears its +flag on every exit. No peak-memory or total pipeline complexity measurement +is claimed. + +Validation at this checkpoint: + +- Direct comparisons with the former recursive raw body cover leaves, fields, + scalar indices, ranges, failures, CFG, facts, explicit mutable modes and + synthetic unchecked range/index children. Leaf/type/emission helpers are + shared; the comparison is independent only for traversal and sequencing. +- Helper ASTs exercise 32,768 array-base projections, nominal field projections + with an innermost field error, and repeated ranges above a dereference leaf. + Parent chains, spans and reverse ends are checked. These are helper tests, + not complete CLI acceptance at that depth. +- Recovering/persistent allocation sweeps cover a grown 64-index worklist after + setup and public success/rejection lowering including setup, fields and + ranges. Arena-backing cleanup is checked; early physical scratch release + and every mixed deep callback combination are not established. +- All 1,793 ordinary conformance cases pass with exact corpus coverage; + frozen public checks/lowerings remain byte-exact (1,423/506). Store modes, + array arguments, lifetimes and CFG suites pass (348/85/188/146 checks, + plus 8/3 lifetime/CFG AIR twins). +- The added hosted block passes 159 CLI calls: array/borrowed-field/range + chains at 1/16/256/1,024, formatter fixed points and exact AIR, bounded + source/AIR returned records and exact fuel exhaustion through 256, mixed + writes/dereferences/unchecked/proven contexts and seven rejection positions + across check/lower/run/report/explore. The full accumulating expression-depth + file was not rerun; this count covers only the new block. + +Build, final expanded units and formatting checks pass. Read-only Claude core +and final follow-up reviews found no production defect within their recorded +body/caller/fixture scope; neither ran tests. The final reviewer could not read +the core report in `/tmp`, and independently compared the diff/live code with +the retained old-body oracle. Its documentation scope corrections are reflected +here; non-blocking OOM/public-depth coverage limits remain explicit. The core +field/range/deep-error and public OOM test gaps were expanded. Neither review +establishes independent normative/full-Q-061 conformance. A suggestion +that arena list deinit immediately releases scratch was not adopted: this +allocator retains storage until arena destruction. + +Memory checklist: the preserved invariant is the existing exclusive/shared +borrow tree and child-first termination (spec 08 §§11–12, AIR 07a). Verifier +rules, interpreter behavior, effects, features, traps, codes and backward +compatibility are unchanged. Deep read/borrow/range chains are checked through +1,024 in the CLI and 32,768 in helper tests. Write, unchecked, proven and mixed dereference CLI +contexts are shallow; deep dereference/range and unchecked behavior is only +helper-stage evidence. Invalid field/bound operands retain E7002/E7005 at the +first relevant construct. Existing `source/layer6/unchecked.aji`, index-scalar and +bounds-trap cases remain in the complete conformance gate. Deterministic +source/AIR and fuel checks preserve observable execution. No normative text, +syntax, bundle growth or new depth limit is introduced. + +Evidence under `.zig-cache/contract-gate/type-depth/`: `place-base-` build, +unit, conformance/audit, public-parity, focused-depth and integration logs; +`place-base-initial-probes.json` records the original array reproducer; +`place-base-review.diff`, `place-base-final-review.diff` and copied +`claude-place-base-{core,final}-review.md` delimit review scope. Original +`/tmp` reports and these ignored cache artifacts are untracked and transient; +the conclusions and limits above are the committed record. +Initial fixture attempts incorrectly allowed source struct `zero`, counted +nominal type declarations as instructions, omitted `local.zero`, expected the +wrong capture envelope, and used a self-referencing AST construction. Those +fixture errors were corrected; none is counted as a successful gate. + +Finite follow-up block and if expressions accept 16/256 but abort at 1,024 +before and after, with empty stdout and parser re-entry in the traceback. +`place-base-next-probes.json` and matching stdout/stderr retain all results. +Control parsing/lowering, multi-result/graph callbacks and liveness/read/ +assignment scans keep Q-061 open. Q-060's full GC validation and Phase 6 exit +review remain independent open gates. ## Remaining work @@ -1086,8 +1175,8 @@ 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, array and enum-payload descent are repaired above. Boolean, consuming own/region, atomic, task.join and spawn operands are repaired above. Mutex make/take operands are repaired above. Scalar index operands use continuations above; the recorded nested-array base-index probe still aborts at 1,024 before/after this repair. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | +| Parser `ifExpr`, block/statement and match/arm expression entry | Finite block/if probes above confirm parser aborts at 1,024 before/after the raw-place repair; 16/256 accept. Alternating control/statement combinations still need audit. | +| 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. Boolean, consuming own/region, atomic, task.join and spawn operands are repaired above. Mutex make/take operands are repaired above. Scalar index operands use continuations above; the recorded nested-array base-index failure is repaired by the raw-place increment above. Dereference/bound expression callbacks and graph/control combinations still need audit. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. 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 @@ -1097,4 +1186,5 @@ 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, array, enum-payload, task.join, task.spawn, mutex and -scalar index operand increments have the scoped reviews recorded above. +scalar index operand increments have the scoped reviews recorded above. The +raw-place increment records its core and final follow-up reviews explicitly. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 4cc16c7..ce14c78 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -815,3 +815,20 @@ fixture/wording suggestions are covered. The recorded nested-array base-index probe still aborts at 1,024 before/after; place/range/borrow, control/liveness and other paths, Q-060 and Phase 6 remain open. No semantic or new depth-limit change. + +### Raw place base depth increment + +The [raw-place increment](../design/source-expression-depth-audit.md#raw-place-base-continuations) +repairs the recorded nested-array base failure at 1,024. Iterative field/index +projections preserve borrow modes/parents/ends, spans, field/bounds error +priority, range order, facts and unchecked selection. One ancestor list +replaces repeated full-list copies; caller-arena lifetime and host OOM +propagation remain explicit. + +All 1,793 ordinary conformance cases, exact public check/lower parity +(1,423/506), store/array-argument/lifetime/CFG suites and 159 new focused CLI +calls pass. Expanded units pass; scoped read-only Claude core/final reviews found no +production defect. Documentation scope corrections are recorded in the audit. The whole accumulating expression-depth suite is not +claimed. Block/if parsing still aborts at 1,024 before/after; other callbacks +and liveness/read/assignment scans, Q-060 full GC validation and Phase 6 exit +review remain open. No normative, feature, bundle or accepted-depth change. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 6210d86..bbc2d96 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -3208,7 +3208,88 @@ const Lowerer = struct { return p; } + /// Descend field/index bases without a native call per projection. The + /// caller arena owns frames and the one ancestor list until lowering ends. + /// Expression callbacks (dereference and index bounds) remain separate. fn placeRaw(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed { + const Frame = struct { place: ast.Expr, unchecked: bool = false }; + var frames: std.ArrayList(Frame) = .empty; + defer frames.deinit(l.arena); + var e = place; + while (true) switch (e.kind) { + .field => |f| { + try frames.append(l.arena, .{ .place = e }); + e = f.e.*; + }, + .index => |x| { + try frames.append(l.arena, .{ .place = e, .unchecked = l.unchecked }); + l.unchecked = false; + e = x.e.*; + }, + else => break, + }; + var base = try l.placeLeaf(e, mutable, span); + if (frames.items.len == 0) return base; + var ends: std.ArrayList([]const u8) = .empty; + defer ends.deinit(l.arena); + try ends.appendSlice(l.arena, base.ends); + while (frames.pop()) |frame| { + const projection = frame.place; + switch (projection.kind) { + .field => |f| { + const st = base.v.ty.inner() orelse return l.fail("E7005", projection.span, "field of a value that is not a struct", &.{}); + const d = l.decl(st) orelse return l.fail("E7005", projection.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }}); + if (d.kind != .@"struct") return l.fail("E7005", projection.span, "field of an enum; use `match`", &.{}); + const fd = for (d.kind.@"struct") |x| { + if (std.mem.eql(u8, x.name, f.name)) break x; + } else return l.fail("E7002", projection.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } }); + const ft = try l.typeOf(fd.ty); + const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span); + try ends.append(l.arena, v.name); + base.v = v; + }, + .index => |x| { + l.unchecked = frame.unchecked; + const bt = base.v.ty; + const elem = elemOf(bt) orelse return l.fail("E7005", projection.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); + if (x.hi) |hi| { + // `s[a..b]`: slice.sub with start a and length b - a (checked). + var sl = base.v; + if (bt == .ref or bt == .mut) { + sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span); + try ends.append(l.arena, sl.name); + } + const a = try l.expr(x.lo.*, .{ .int = "usize" }); + try l.checkOperandTy(x.lo.span, a.ty, .{ .int = "usize" }); + const b = try l.expr(hi.*, .{ .int = "usize" }); + try l.checkOperandTy(hi.span, b.ty, .{ .int = "usize" }); + const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span); + const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span); + try ends.append(l.arena, sub_.name); + base.v = sub_; + continue; + } + // Only the outermost index of an unchecked place is unchecked. + const unchecked = l.unchecked; + l.unchecked = false; + const i = try l.expr(x.lo.*, .{ .int = "usize" }); + try l.checkOperandTy(x.lo.span, i.ty, .{ .int = "usize" }); + const proven = for (l.facts.items) |f| { + if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true; + } else false; + if (unchecked) l.uses.insert(.unsafe); + const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index"; + const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span); + try ends.append(l.arena, v.name); + base.v = v; + }, + else => unreachable, + } + } + return .{ .v = base.v, .ends = try ends.toOwnedSlice(l.arena) }; + } + + fn placeLeaf(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed { const op = if (mutable) "borrow.mut" else "borrow.ref"; switch (place.kind) { .name => |n| { @@ -3249,54 +3330,6 @@ const Lowerer = struct { if (!r.ty.isBorrow()) return l.fail("E7005", place.span, "`*` needs a borrow", &.{}); return .{ .v = r, .ends = &.{} }; }, - .field => |f| { - const base = try l.placeRaw(f.e.*, mutable, span); - const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{}); - const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }}); - if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{}); - const fd = for (d.kind.@"struct") |x| { - if (std.mem.eql(u8, x.name, f.name)) break x; - } else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } }); - const ft = try l.typeOf(fd.ty); - const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span); - return .{ .v = v, .ends = try l.concat(base.ends, v.name) }; - }, - .index => |x| { - const outer_unchecked = l.unchecked; - l.unchecked = false; - const base = try l.placeRaw(x.e.*, mutable, span); - l.unchecked = outer_unchecked; - const bt = base.v.ty; - const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); - if (x.hi) |hi| { - // `s[a..b]`: slice.sub with start a and length b - a (checked). - var sl = base.v; - var ends = base.ends; - if (bt == .ref or bt == .mut) { - sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span); - ends = try l.concat(ends, sl.name); - } - const a = try l.expr(x.lo.*, .{ .int = "usize" }); - try l.checkOperandTy(x.lo.span, a.ty, .{ .int = "usize" }); - const b = try l.expr(hi.*, .{ .int = "usize" }); - try l.checkOperandTy(hi.span, b.ty, .{ .int = "usize" }); - const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span); - const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span); - return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) }; - } - // Only the outermost index of an unchecked place is unchecked. - const unchecked = l.unchecked; - l.unchecked = false; - const i = try l.expr(x.lo.*, .{ .int = "usize" }); - try l.checkOperandTy(x.lo.span, i.ty, .{ .int = "usize" }); - const proven = for (l.facts.items) |f| { - if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true; - } else false; - if (unchecked) l.uses.insert(.unsafe); - const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index"; - const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span); - return .{ .v = v, .ends = try l.concat(base.ends, v.name) }; - }, else => return l.invalid(.invalid_place, place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}), } } @@ -9791,3 +9824,248 @@ test "grown index continuation stack propagates every allocation failure" { } try std.testing.expect(later_prefix_failures > 0); } + +// This oracle retains the former recursive raw-place body independently. +// Expression children use ReferenceOperands; shared leaf/type/emission helpers +// are deliberately outside this comparison's independence claim. +fn expectRawPlaceMatches(a: Allocator, m: ast.Module, e: ast.Expr, mutable: bool, unchecked: bool) !void { + var old = try indexTestLowerer(a, m, e.span); + var current = try indexTestLowerer(a, m, e.span); + old.unchecked = unchecked; + current.unchecked = unchecked; + const span = unaryTestSpan(123_456); + const expected = ReferenceIndexPlaces.placeRaw(&old, e, mutable, span); + const actual = current.placeRaw(e, mutable, span); + if (expected) |p| { + const result = try actual; + try std.testing.expectEqualStrings(p.v.name, result.v.name); + try std.testing.expect(p.v.ty.eql(result.v.ty)); + try std.testing.expectEqualDeep(p.ends, result.ends); + } else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.problem, current.problem); + try std.testing.expectEqualDeep(old.unimpl, current.unimpl); + try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items); + try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items); + try std.testing.expectEqualDeep(old.constants.items, current.constants.items); + try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items); + try std.testing.expectEqual(old.unchecked, current.unchecked); + try std.testing.expectEqualDeep(old.facts.items, current.facts.items); + try std.testing.expectEqual(old.counter, current.counter); + try std.testing.expectEqual(old.cur, current.cur); + try std.testing.expectEqualDeep(old.uses, current.uses); + try std.testing.expectEqual(old.linear_enabled, current.linear_enabled); + try std.testing.expectEqual(old.in_constant, current.in_constant); + try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count()); + var parents = old.borrow_parents.iterator(); + while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?); +} + +test "raw place continuations preserve base range error loan and unchecked ordering" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "xs", "ss", "sm", "ra", "n", "o", "oa", "unknown", "b\"xy\"", "*ra", "*n", + "indexed.data", "ir.data", "matrix.data[0usize][0usize]", "box.n", "box.missing", "box.n.missing", "xs[0usize]", "xs[unknown]", "xs[true]", "ss[ix]", "sm[ix]", + "n[unknown]", "unknown[unknown]", "xs[0usize..1usize]", "ss[0usize..1usize]", "sm[0usize..1usize]", "xs[unknown..true]", "xs[true..unknown]", "xs[0usize..unknown]", "xs[0usize..true]", "xs[0usize..1usize][0usize]", "indexed.data[0usize..1usize][0usize]", + "ss[0usize..1usize][0usize..1usize]", "xs[xs[0usize]..xs[0usize]]", "ss[0usize..1usize].missing", "matrix.data[unknown][true]", "matrix.data[true][unknown]", "(*ra)[0usize]", "(*ra)[0usize..1usize]", "xs[if true { 0usize } else { 0usize }]", "xs[xs[0usize]]", "xs[stop(b\"x\")]", "xs[void_call(b\"x\")]", + "xs[ref n]", "xs[move o]", "matrix.data[0usize].missing", "indexed.missing[unknown]", "1usize", "true", "[0usize]", + }; + for (expressions) |text| { + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ indexTestDeclarations, text })); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]bool{ false, true }) |mutable| for ([_]bool{ false, true }) |unchecked| try expectRawPlaceMatches(a, parsed.ok, e, mutable, unchecked); + } +} + +fn rawPlaceArrayChain(a: Allocator, count: usize) !ast.Expr { + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .name = "deep" } }; + for (0..count) |i| { + const items = try a.dupe(ast.Expr, &.{ e, .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .int = .{ .text = "0usize" } } } }); + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = null } } }; + } + return e; +} + +fn bindRawPlaceArray(l: *Lowerer, count: usize) !void { + var t: Ty = .{ .int = "usize" }; + for (0..count) |_| t = try l.arrayOf(t, 1); + try l.bindings.append(l.arena, .{ .name = "deep", .value = "deep_storage", .mutable = true, .ty = t, .kind = .storage }); +} + +test "deep raw index bases preserve complete ancestor chain spans and reverse ends" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, indexTestDeclarations)).ok; + const count = 32_768; + const e = try rawPlaceArrayChain(a, count); + for ([_]bool{ false, true }) |mutable| { + var l = try indexTestLowerer(a, m, e.span); + try bindRawPlaceArray(&l, count); + l.unchecked = true; + const span = unaryTestSpan(200_000); + const p = try l.placeRaw(e, mutable, span); + try std.testing.expectEqual(count + 1, p.ends.len); + try std.testing.expectEqual(mutable, p.v.ty.isMutBorrow()); + try std.testing.expect(p.v.ty.inner().?.eql(.{ .int = "usize" })); + try std.testing.expectEqualStrings(p.v.name, p.ends[count]); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(2 * count + 1, insts.len); + try std.testing.expect(std.mem.indexOf(u8, insts[0].text, if (mutable) "borrow.mut %deep_storage" else "borrow.ref %deep_storage") != null); + for (0..count) |i| { + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(100_000 + i))), insts[1 + 2 * i].span); + try std.testing.expectEqualDeep(@as(?Span, span), insts[2 + 2 * i].span); + try std.testing.expect(std.mem.indexOf(u8, insts[2 + 2 * i].text, if (i + 1 == count) "borrow.index.unchecked %" else "borrow.index %") != null); + try std.testing.expectEqualStrings(p.ends[i], l.borrow_parents.get(p.ends[i + 1]).?); + } + try l.endNow(p.ends, span); + const after = l.blocks.items[0].insts.items; + for (0..count + 1) |i| try std.testing.expectEqualStrings(try l.fmt("borrow.end %{s}", .{p.ends[count - i]}), after[2 * count + 1 + i].text); + } +} + +test "grown raw place worklists propagate every host allocation failure and release backing" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, indexTestDeclarations)).ok; + const count = 64; + const e = try rawPlaceArrayChain(a, count); + for ([_]bool{ false, true }) |persistent| { + var fail_at: usize = 0; + var late_failures: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 4096); + var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + var output: std.heap.ArenaAllocator = .init(backing.allocator()); + var l = try indexTestLowerer(output.allocator(), m, e.span); + try bindRawPlaceArray(&l, count); + var failing: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at }; + var sticky: std.testing.FailingAllocator = .init(output.allocator(), .{ .fail_index = fail_at }); + l.arena = if (persistent) sticky.allocator() else failing.allocator(); + const result = l.placeRaw(e, true, e.span); + const failed = if (persistent) sticky.has_induced_failure else failing.failed; + if (failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!persistent) try std.testing.expectEqual(fail_at + 1, failing.attempts); + try std.testing.expect(l.problem == null and l.unimpl == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + if (l.blocks.items[0].insts.items.len > count) late_failures += 1; + } else try std.testing.expectEqual(count + 1, (try result).ends.len); + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!failed) break; + } + try std.testing.expect(late_failures > 0); + } +} + +test "deep nominal raw fields keep parents and innermost error positions" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const count = 32_768; + var m = (try parse_mod.parse(a, indexTestDeclarations)).ok; + const declarations = try a.alloc(ast.TypeDecl, m.types.len + count); + @memcpy(declarations[0..m.types.len], m.types); + for (declarations[m.types.len..], 0..) |*d, i| { + const span = unaryTestSpan(@intCast(100_000 + i)); + const fields = try a.dupe(ast.Field, &.{.{ .name = "data", .span = span, .ty = .{ .span = span, .kind = .{ .name = if (i + 1 == count) "usize" else try std.fmt.allocPrint(a, "Deep{d}", .{i + 1}) } } }}); + d.* = .{ .name = try std.fmt.allocPrint(a, "Deep{d}", .{i}), .span = span, .kind = .{ .@"struct" = fields } }; + } + m.types = declarations; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .name = "deep" } }; + for (0..count) |i| { + const child = try a.dupe(ast.Expr, &.{e}); + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .field = .{ .e = &child[0], .name = "data" } } }; + } + var l = try indexTestLowerer(a, m, e.span); + try l.bindings.append(a, .{ .name = "deep", .value = "nominal_storage", .mutable = true, .ty = l.enumOrStruct("Deep0", e.span).?, .kind = .storage }); + const p = try l.placeRaw(e, true, e.span); + try std.testing.expectEqual(count + 1, p.ends.len); + try std.testing.expect(p.v.ty.inner().?.eql(.{ .int = "usize" })); + for (p.ends[1..], 0..) |name, i| try std.testing.expectEqualStrings(p.ends[i], l.borrow_parents.get(name).?); + for (l.blocks.items[0].insts.items) |inst| try std.testing.expectEqualDeep(@as(?Span, e.span), inst.span); + // The same long projection spine fails at its first field when the base + // has been replaced with a scalar stored value; outer spans do not win. + var bad = try indexTestLowerer(a, m, e.span); + try bad.bindings.append(a, .{ .name = "deep", .value = "scalar_storage", .mutable = true, .ty = .{ .int = "usize" }, .kind = .storage }); + try std.testing.expectError(error.Lower, bad.placeRaw(e, true, e.span)); + try std.testing.expectEqualStrings("E7005", bad.problem.?.code); + try std.testing.expectEqualDeep(unaryTestSpan(1), bad.problem.?.span); + try std.testing.expectEqual(@as(usize, 1), bad.blocks.items[0].insts.items.len); +} + +test "deep raw ranges and dereference leaves preserve every temporary ancestor" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, indexTestDeclarations)).ok; + const count = 32_768; + const leaf = try a.dupe(ast.Expr, &.{.{ .span = unaryTestSpan(90_000), .kind = .{ .name = "ra" } }}); + var e: ast.Expr = .{ .span = unaryTestSpan(90_001), .kind = .{ .deref = &leaf[0] } }; + for (0..count) |i| { + const items = try a.dupe(ast.Expr, &.{ e, .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .int = .{ .text = "0usize" } } }, .{ .span = unaryTestSpan(@intCast(200_000 + i)), .kind = .{ .int = .{ .text = "1usize" } } } }); + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = &items[2] } } }; + } + var l = try indexTestLowerer(a, m, e.span); + const p = try l.placeRaw(e, false, e.span); + try std.testing.expectEqual(count + 1, p.ends.len); // one make, count sub + try std.testing.expect(p.v.ty == .slice); + try std.testing.expectEqual(4 * count + 1, l.blocks.items[0].insts.items.len); + try std.testing.expectEqualStrings("array_loan", l.borrow_parents.get(p.ends[0]).?); + for (p.ends[1..], 0..) |name, i| try std.testing.expectEqualStrings(p.ends[i], l.borrow_parents.get(name).?); + const insts = l.blocks.items[0].insts.items; + for (0..count) |i| { + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(100_000 + i))), insts[1 + 4 * i].span); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(200_000 + i))), insts[2 + 4 * i].span); + try std.testing.expect(std.mem.indexOf(u8, insts[4 + 4 * i].text, "slice.sub %") != null); + } +} +test "public raw place field range lowering OOM stays host error with arena cleanup" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module oom\nstruct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; return s.data[0usize][0usize]; }\n", + "module oom\nfn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a[0usize..1usize][0usize..1usize]; return s[0usize]; }\n", + "module oom\nfn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a[unknown..1usize]; return 0usize; }\n", + "module oom\nfn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a[0usize..true]; return 0usize; }\n", + "module oom\nstruct S { data: usize }\nfn main() -> usize effects [] { var s: S = S { data: 0usize }; return s.missing[unknown]; }\n", + "module oom\nfn main() -> usize effects [] { var a: [usize; 1] = zero; return a[0usize..1usize]; }\n", + }; + for (programs, 0..) |program, index| { + const parsed = try parse_mod.parse(fixture.allocator(), program); + try std.testing.expect(parsed == .ok); + const baseline = try lower(fixture.allocator(), parsed.ok); + if (index < 2) try std.testing.expect(baseline == .ok) else { + try std.testing.expect(baseline == .err); + try std.testing.expectEqualStrings(switch (index) { + 2, 4 => "E7002", + 5 => "E7006", + else => "E7005", + }, baseline.err.code); + } + 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 { + try std.testing.expect(std.meta.activeTag(try result) == std.meta.activeTag(baseline)); + break; + } + } + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index d525b5a..700782e 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -1282,4 +1282,92 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: print(f'index operand rejection depth: {leaf}', flush=True) +with tempfile.TemporaryDirectory(prefix='aji-place-base-depth-') as directory: + root = Path(directory) + for kind in ('array', 'field', 'range'): + for depth in (1, 16, 256, 1024): + if kind == 'array': + ty = '[' * depth + 'usize' + '; 1]' * depth + source = f'module depth\nfn main() -> usize effects [] {{ var a: {ty} = zero; return a' + '[0usize]' * depth + '; }\n' + elif kind == 'field': + declarations = ''.join(f'struct T{i} {{ data: ' + (f'T{i+1}' if i+1 < depth else 'usize') + ' }\n' for i in range(depth)) + initial = ''.join(f'T{i} {{ data: ' for i in range(depth)) + '0usize' + ' }' * depth + source = 'module depth\n' + declarations + 'fn main() -> usize effects [] { var a: T0 = ' + initial + '; ref r = a; return r' + '.data' * depth + '; }\n' + else: + source = 'module depth\nfn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a' + '[0usize..1usize]' * depth + '; return s[0usize]; }\n' + path = root / f'place-base-{kind}-{depth}.aji' + path.write_text(source) + assert cli('check', path) == b'' + lowered = cli('lower', path) + expected_op = b'borrow.field @' if kind == 'field' else b'slice.sub %' if kind == 'range' else b'borrow.index %' + assert sum(expected_op in line for line in lowered.splitlines()) == depth, (kind, depth) + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert cli('lower', formatted) == lowered + if depth <= 256: + instructions = sum(line.startswith(b' ') and (b' = ' in line or line.strip().startswith((b'ret ', b'borrow.end ', b'local.store ', b'local.zero ', b'store '))) for line in lowered.splitlines()) + air = path.with_suffix('.air') + air.write_bytes(lowered) + options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', instructions) + result = cli('run', path, *options) + assert json.loads(result) == {'status': 'returned', 'value': 0}, (kind, depth, lowered, result) + assert cli('run', air, *options) == result + exhaustion = ('--quantum', 1, '--schedule-seed', 7, '--fuel', instructions - 1) + limit = cli('run', path, *exhaustion, code=5) + assert json.loads(limit) == {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}, (kind, depth, instructions, limit) + assert cli('run', air, *exhaustion, code=5) == limit + print(f'place base {kind} {depth} passed', flush=True) + + # Bound-mode, RHS-first store, ancestor cleanup and a mixed projection spine. + for label, source, value, marker in ( + ('write', 'struct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; s.data[0usize][0usize] = s.data[0usize][0usize] + 1usize; return s.data[0usize][0usize]; }', 1, b'store %'), + ('unchecked', 'struct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [unsafe] { var s: S = S { data: [[0usize]] }; ref unchecked r = s.data[0usize][0usize]; return *r; }', 0, b'borrow.index.unchecked %'), + ('deref', 'struct S { data: [[usize; 1]; 1] }\nfn read(p: ref) -> usize effects [] { (*p).data[0usize][0usize] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; return read(ref s); }', 0, b'borrow.field @S.data'), + ('proven', 'fn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a[0usize..1usize]; let i: usize = 0usize; if i < s.len { return s[i]; } else { return 2usize; } }', 0, b'borrow.index.proven %'), + ): + path = root / f'place-context-{label}.aji' + path.write_text('module depth\n' + source + '\n') + assert cli('check', path) == b'' + lowered = cli('lower', path) + assert marker in lowered, (label, lowered) + air = path.with_suffix('.air') + air.write_bytes(lowered) + opts = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 128) + result = cli('run', path, *opts) + expected = {'status': 'returned', 'value': value} + if label != 'proven': + expected.update(stdout='', stderr='', files={}) + assert json.loads(result) == expected, result + assert cli('run', air, *opts) == result + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert cli('lower', formatted) == lowered + + for expression, code, offending in ( + ('s.data[unknown][true]', 'E7002', 'unknown'), + ('s.data[true][unknown]', 'E7005', 'true'), + ('s.missing[unknown]', 'E7002', 's.missing'), + ('a[unknown..true]', 'E7002', 'unknown'), + ('a[true..unknown]', 'E7005', 'true'), + ('a[0usize..unknown]', 'E7002', 'unknown'), + ('a[0usize..true]', 'E7005', 'true'), + ): + path = root / 'place-error.aji' + source = 'module depth\nstruct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; var a: [usize; 1] = zero; ref r = ' + expression + '; return 0usize; }\n' + path.write_text(source) + diag = cli('check', path, code=1) + record = json.loads(diag) + assert record['code'] == code, record + start = source.index(offending, source.index('ref r =')) + assert record['line'] == source.count('\n', 0, start) + 1 + assert record['col'] == start - source.rfind('\n', 0, start) + for command in ('lower', 'run', 'report', 'explore'): + assert cli(command, path, code=1) == diag + print('place base contexts and rejection positions passed', flush=True) + + print(f'source expression depth: {checks} checks passed')