From 2d750a052597f0b28aff1d8a9919ebfc5d20f358 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Wed, 14 Oct 2026 18:26:44 +0300 Subject: [PATCH] cli: index loop-exit edges and reuse negative After queries; fix loop-exit diagnostics (Q-063, Q-064) --- .github/workflows/ci.yml | 1 + .../design/control-depth-performance-audit.md | 249 ++++++++++++ docs/design/open-questions.md | 63 ++- src/frontend/liveness.zig | 172 +++++++- src/frontend/lower.zig | 374 +++++++++++++++--- .../source/loop_exit/call_break.aji | 10 + .../source/loop_exit/call_continue.aji | 9 + .../source/loop_exit/call_return.aji | 9 + .../source/loop_exit/call_trap.aji | 9 + .../source/loop_exit/condition_parameter.aji | 10 + .../source/loop_exit/condition_prefix.aji | 10 + .../source/loop_exit/conditional_break.aji | 10 + .../source/loop_exit/function_isolation.aji | 10 + .../source/loop_exit/nested_return.aji | 9 + tests/hosted/source_loop_exit.py | 147 +++++++ 15 files changed, 1016 insertions(+), 76 deletions(-) create mode 100644 tests/conformance/source/loop_exit/call_break.aji create mode 100644 tests/conformance/source/loop_exit/call_continue.aji create mode 100644 tests/conformance/source/loop_exit/call_return.aji create mode 100644 tests/conformance/source/loop_exit/call_trap.aji create mode 100644 tests/conformance/source/loop_exit/condition_parameter.aji create mode 100644 tests/conformance/source/loop_exit/condition_prefix.aji create mode 100644 tests/conformance/source/loop_exit/conditional_break.aji create mode 100644 tests/conformance/source/loop_exit/function_isolation.aji create mode 100644 tests/conformance/source/loop_exit/nested_return.aji create mode 100644 tests/hosted/source_loop_exit.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7975372..0289586 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,7 @@ jobs: - run: python3 tests/hosted/source_repair_advice.py - run: python3 tests/hosted/source_independent_errors.py - run: python3 tests/hosted/source_cfg_provenance.py + - run: python3 tests/hosted/source_loop_exit.py - run: python3 tools/source_reject_twins.py - run: python3 tests/hosted/source_reject_twins.py - run: python3 tests/hosted/examples.py --stress 200 diff --git a/docs/design/control-depth-performance-audit.md b/docs/design/control-depth-performance-audit.md index 79f5c0a..40b371b 100644 --- a/docs/design/control-depth-performance-audit.md +++ b/docs/design/control-depth-performance-audit.md @@ -118,3 +118,252 @@ instruction, agent bundle or benchmark claim changes. Residual AIR verification growth for while/match is visible but not assigned a specific cause by these profiles. Q-063 remains open for implementation decisions and those remaining measurements; Q-060's composite closure and the B1 gate on P7/P8 are independent. + +## First optimization: loop-exit reference index (2026-10-14) + +`Lowerer.reaches` now looks up a function-local index instead of scanning all +previously emitted instructions. `emit` indexes references to generated +`after_N` exit names. Keys borrow the instruction text's arena lifetime; the +index resets for each function. It reserves both index and instruction +capacity before publishing either, so metadata OOM cannot leave a phantom +reference or an emitted instruction absent from the index. Queries allocate +nothing. Metadata grows with distinct referenced exit names; arena storage is +released with the caller's arena, not immediately at the function reset. + +Inspection and frozen-CLI probes found that the old predicate also counted +calls to functions with colliding names, including references emitted before +the exit block existed, and used only the first substring match per +instruction. These are preserved exactly and logged as +[Q-064](open-questions.md#q-064--loop-exit-reference-search-confuses-function-and-block-names). +Consequently this increment indexes the old reference predicate rather than +changing it to actual CFG-edge reachability. References from unreachable +blocks still count. The frozen control oracle retains the independent old +full scan; it does not share the new query. + +Paired Debug measurements use the frozen and changed binaries on CPU 0 with +inherited process affinity, alternating before/after order, two warmups per +binary/shape, and seven measured repetitions per version. All source and AIR +bytes match. Medians for `lower`, at 512 levels: + +| Shape | Before | After | Before / after | +|---|---|---|---| +| scope (control) | 0.0927 s | 0.0952 s | 0.97× | +| while | 0.6291 s | 0.1956 s | 3.22× | +| loop | 0.2169 s | 0.1174 s | 1.85× | +| while_live | 1.2246 s | 0.6800 s | 1.80× | + +The control is 2.7% slower in this batch; the index has emission overhead and +these finite timings do not establish a statistical bound on that overhead. +Earlier unpinned batches had substantial control timing variation, so they are +not used for the quoted speedups. This removes the repeated full-function +search, not liveness rescans or AIR verification costs, and does not establish +linear whole-pipeline complexity. + +Validation: + +- `zig build test` exits 0 with the production change and the first two new + index tests; the final additional function-isolation/public-OOM cases and + both index tests pass in a focused `zig test --test-filter 'loop exit'` + run (8/8 including import-discovery tests). The emission test injects every + allocation failure before publication. Public lowering tests inject each + recovering and persistent allocation failure and check full arena release. +- All 1,799 current conformance files pass, terminal exit 0, with exact unique + coverage, no missing/extra/duplicate or nonpassing records. +- All 1,429 public source conformance files plus four function-name collision + probes retain exact `check` and `lower` exit/stdout/stderr: 2,866 comparisons. +- Six finite loop/shield examples, in source and AIR, retain exact run records + and exits at fourteen fuel values: 168 old/new pairs. Valid nested loops + with `break` still return normally; a divergent loop followed by a statement + still rejects E7006, subject to the explicitly preserved Q-064 collision. +- Zig format and diff whitespace checks pass. No new verifier rule needs a + conformance pair: this increment changes metadata, not source/AIR semantics. + +Evidence is in `/tmp/aji-q063-reaches/`: `aji-before`, +`conformance.audit.json`, `parity.audit.json`, `runtime-parity.json`, +`clean-before/`, `clean-after/`, `pinned-timings.jsonl` and `pinned-audit.json`. +The old binary hash is recorded above; the measured new Debug binary is +`46a1c15b25e84729ce03d24e04aeead05c4835ddb2355c64dd64f14d248e067a`. +No wall-clock timeout ends a run. No ownership/borrow/resource invariant, +runtime operation, fuel/scheduling rule, diagnostic, feature, normative text, +agent bundle or accepted-depth limit changes. Q-063 remains open for liveness +and shield improvements; Q-064 is a separate correctness follow-up. + + +## Second optimization: negative After-query reuse (2026-10-14) + +`liveAfter` now keeps one stack-local memo while walking outwards through Rest +frames. It reuses a completed **negative subtree After query**, not the answer +to whole-variable liveness. The key includes the immutable control payload's +AST identity/kind and positional span, variable name and construct position. +Supported expression roots are if, match and block; other forms retain the +original traversal. There is no name-only or function-wide result cache. + +The proof carried by an entry is narrow: the query entered with `seen=false`, +found the construct and returned no later read. An enclosing unseen traversal +of exactly that subtree can set `seen=true` and resume its existing work stack. +Sibling-arm exclusion and loop-back continuations therefore retain their old +state transitions. A query entered with `seen=true`, an absent construct, +a positive result, another AST node/name/position or a failed query cannot +supply this proof. Statement wrappers seed an expression entry only when their +position checks agree. The existing position-only span policy, including +cross-file position comparisons, is unchanged. + +First-use kills, pattern rebinding, enclosing-rest order, loop reads and +assignment queries still run in their original order. The memo resets for each +`liveAfter` invocation, allocates nothing and retains one entry regardless of +source depth. Successful reuse may avoid scratch allocations; every actual +scratch OOM still propagates and clears pending work before any memo publication. +The governing pruned-SSA rule in spec 15 section 4, diagnostics, accepted source, +canonical AIR and interpreter/fuel rules are confirmed unchanged. + +### Measurements + +Seconds for mutable-match lowering; medians of three measured runs. + +| Depth | Before | After | Before / after | +|---|---:|---:|---:| +| 128 | 0.560870 | 0.093792 | 5.98× | +| 256 | 3.991630 | 0.220675 | 18.09× | +| 512 | 30.981500 | 0.635286 | 48.77× | + +Other shapes at depth 512: + +| Shape | Before | After | +|---|---:|---:| +| scope | 0.093227 | 0.091937 | +| shield | 0.094780 | 0.094081 | +| while | 0.180449 | 0.179080 | +| loop | 0.074227 | 0.074617 | +| match | 0.182518 | 0.183027 | +| while_live | 0.674470 | 0.675189 | + +The six depth-512 controls change by at most 1.4% in this batch. The series +contains 126 measured lowerings, 42 warmups and 42 final source/AIR acceptance +checks. These controls do not establish a universal overhead bound. + +The paired Debug series compares the frozen first-optimization executable +against this increment on CPU 0: depths 128/256/512, all seven original public +probe shapes, one warmup per case/version and three measured repetitions. +Version order alternates and case order rotates. All generated sources match +the preceding audit's fixtures; every lowering has identical AIR. No builds or +correctness suites run alongside the timed series. The reports retain wall/CPU +and wait4 peak RSS (the latter can include the launcher's pre-exec memory). +These are lowering measurements on one machine, not a portable complexity or +whole-compiler latency bound. Source/AIR acceptance is checked separately. + +Repeated ancestor descent is avoided on the audited nested-match path, but +assignment/read queries, positive After queries, unsupported root shapes and +AIR verification still have their prior costs. Q-063 therefore remains open; +shield relations and Q-064 are independent follow-ups. + +### Validation and evidence + +- Full unit suite: **341/341**, terminal exit 0. Four new tests cover exact + memo keys, already-seen state, statement/expression position mismatch, + pre/post-boundary scratch OOM, frozen Rest-frame comparisons with kills, + competing siblings and loop reads, and 4,096 enclosing control frames with + bounded query scratch. Existing recovering/persistent OOM and frozen + liveness/CFG/error-order tests pass. The focused selection is 9/9 including + five import-discovery tests. +- All **1,799** conformance cases pass with exact unique inventory, no missing, + extra, duplicate or nonpassing records. +- All **1,429** public source conformance inputs and ten new finite positive/ + negative probes retain exact old/new `check`/`lower` exits, stdout and stderr: + **2,878 comparisons**. Four Q-064 collisions add eight exact comparisons. +- Eight positive new probes, in source and AIR at fifteen fuel values, retain + **240** exact run-record/exit pairs. They include nested mutation, straight-line + kills, competing-arm reads, loop backedges, continue, shadowing, returns and + independent variables. The negative probes preserve assignment/type errors. +- The existing hosted liveness-depth suite passes **418** CLI checks through + depth 65,536, including formatting, source/AIR, exact fuel and hosted records. + That run used a separately retained production-identical build before a + test-only setup correction; final unit/parity/timing artifacts use the + corrected test source. Both native hashes are retained in the provenance. +- Zig formatting and patch whitespace checks pass. No new verifier rule, + language feature, diagnostic, semantic flag or normative limit is introduced. + +Evidence is under `/tmp/aji-q063-review-20261014-se2oa131/liveness/`: +`baseline.json`, `source.json`, `unit-final.log`, `focused.log`, +`conformance-audit.json`, `parity-audit.json`, `runtime-parity.json`, +`collision-parity.json`, `hosted-liveness.log` and `performance/` with sources, +old/new AIR, provenance, warmups, timings, summary and acceptance checks. +Reproduce generated probes with `tools/profile_control_depth.py`; freeze each +Debug binary, pin the launcher to one CPU, and rotate versions on identical +inputs. The exact paired driver is retained as +`/tmp/aji-q063-liveness-performance.py`. No wall-clock timeout ends a command. + +## Correctness follow-up: explicit CFG incoming edges (Q-064, 2026-10-14) + +The compatibility index in the first optimization deliberately retained the +old textual predicate. Q-064 is now corrected independently: each frontend +block records whether an emitted terminator targets it, using block indices +supplied by the lowering construct. `term` requires an explicit successor +slice; `select` passes its existing outcome records without allocating a new +index. `ret` and `trap` have no successors. The loop-completion query reads the +exit block's bit in constant time. Instruction emission no longer searches +text or allocates a loop-exit hash table. + +The bit starts false with each new block and is published only after the +instruction append succeeds. There is no fallible step between publishing a +terminator and recording its edges. Targets exist before emission; no names, +source operands, calls or textual prefixes take part in the query. Edges from +syntactically emitted but disconnected blocks still count, and constant +conditions are not folded. This preserves the prior conservative CFG policy +apart from the naming defects; it does not add reachability analysis. + +Two corrected cases demonstrate why the separate correctness change is +needed: + +- A helper call `after_2()` inside `loop { after_2(); return 0u64; }` previously + supplied a phantom incoming edge to the loop exit. A following statement now + rejects E7006 `unreachable`, as spec 15 §10 requires. Trap, continue, nested + loops and function-state reset have corresponding rejection fixtures. +- A boolean parameter `after_2` (or the prefix `after_20`) previously masked the + genuine `@after_2` exit later in a conditional branch instruction. A reachable + statement after `while after_2 { return 1u64; }` now accepts. Both boolean + outcomes execute correctly; real break edges remain valid even when the + same helper name occurs. + +Validation uses Zig 0.17.0, Debug, with a frozen pre-fix executable containing +both Q-063 optimizations. The complete public corpus, without held-out or +untracked evaluation material, gives: + +| Check | Result | +|---|---| +| Unit suite, including emission OOM and recovering/persistent lowering OOM | 342 passed | +| Conformance, including nine new source fixtures | 1,808 passed | +| Pre-existing public sources: exact check/lower exit, stdout and stderr | 2,858 pairs on 1,429 files, no differences | +| New fixture check/lower comparisons | 18 pairs; 14 intentional corrections, four exact | +| Existing finite source/AIR runtime and fuel comparisons | 240 exact pairs | +| Targeted collision/diagnostic/format/package CLI suite | 182 passed | +| Existing diagnostic-reason suite | 236 passed | +| Existing independent-error suite | 234 passed | +| Existing CFG-provenance suite | 146 passed | +| Hosted smoke, including local TCP sockets | passed | +| Zig formatting | passed | + +The incoming-edge unit oracle independently parses emitted AIR and obtains +successors from AIR operations for ten programs covering loops, joins, short +circuiting, integer/enum/builtin matches, fallible outcomes, lock, select and +linear aggregate unpacking. It compares every function's block bits with +those parsed successors. The old textual predicate remains frozen in the +control compatibility oracle; the two collisions are tested as deliberate +old/new differences rather than silently changing that oracle. + +The targeted CLI suite checks E7006 reason and exact source position, +diagnostic ordering before and after divergence, independent function errors, +canonical formatting, package provenance, both loop-condition outcomes and +source/AIR fuel equality. Five erroneous acceptances now reject; two erroneous +rejections now accept. Other public acceptance, diagnostics, canonical AIR and +finite runtime/fuel behavior are unchanged. AIR format 0 and its verifier and +interpreter semantics are unchanged. No portable performance bound is claimed +for this correctness slice; Q-063's remaining liveness and shield work remains +open. + +Reproduction and qualification artifacts are retained in +`/tmp/aji-q064-20261014-x_a6b4gb/`: `baseline.json`, frozen binaries, +`reproduction.json`, `parity.jsonl`, `collision-changes.json`, +`runtime-parity.jsonl`, `parity-audit.json`, `unit-final.log`, +`conformance.jsonl`, CLI-suite logs and `qualification.json` with source and +executable hashes. The reproducible targeted test is +`python3 tests/hosted/source_loop_exit.py`. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 8d6b0ea..a39ff0d 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -661,17 +661,30 @@ profiled targets accept normally. This is a finite Debug profile, not a portable timing bound or a whole-compiler complexity proof. Q-060's full per-step validation is now closed by its composite audit. -Profiling for Q-063 is complete for these paths; optimization remains open. -The recommended first isolated change is explicit loop incoming-edge metadata, -followed by context-correct liveness indexing and a separately reviewed shield -relation optimization. A later optimization needs exact CFG/SSA, +Profiling for Q-063 is complete for these paths. The +[first optimization](control-depth-performance-audit.md#first-optimization-loop-exit-reference-index-2026-10-14) +indexes loop-exit references at instruction emission rather than repeatedly +scanning the whole function. Paired CPU-pinned Debug lowering at 512 levels +improves while by 3.22×, loop by 1.85× and mutable while by 1.80×, with exact +public check/lower and runtime/fuel compatibility. That slice preserved the +legacy reference policy; Q-064 now records its separate correction with +explicit CFG incoming edges. +The [second optimization](control-depth-performance-audit.md#second-optimization-negative-after-query-reuse-2026-10-14) +reuses one completed negative subtree After query while walking enclosing Rest +frames, with AST identity/name/construct guards. Paired Debug mutable-match +lowering at 512 levels falls from 30.982 to 0.635 seconds (48.77×), with 341 unit +tests, 1,799 conformance cases and exact source/AIR/runtime comparisons. This +preserves first-use kills, sibling exclusion and loop reads; it is not a global +variable-liveness cache. Remaining assignment/read/positive-query costs and a +separately reviewed shield relation optimization remain open. A later +optimization needs exact CFG/SSA, diagnostic-order, host-OOM and runtime/fuel compatibility checks. No source-depth limit, new diagnostic, verifier rule, AIR instruction or language semantic change is introduced by recording this limitation. ## Q-064 — Loop-exit reference search confuses function and block names -**Open; confirmed existing frontend diagnostic defect (2026-10-14).** While +**Closed; frontend diagnostic defect corrected (2026-10-14).** While optimizing Q-063, a frozen pre-change Debug binary at `17cbe3e` accepts this source in both `lower` and `check`, with exit 0: @@ -692,9 +705,37 @@ mistakes `call @after_2()` for an incoming reference to that block. Its first-substring test also allows an earlier non-reference substring in one instruction to mask a later genuine reference in that same instruction. -The Q-063 reference-index optimization deliberately preserves this behavior; -it does not make the collision a language rule. Replacing the compatibility -index with actual CFG-edge metadata belongs to a separate correctness change, -with source/AIR, naming-collision, unreachable-code and diagnostic-priority -coverage. Evidence is in `/tmp/aji-q063-reaches/collision-*.aji` and the frozen -CLI's output. No native-stack failure or unsafe execution is established here. +The Q-063 reference-index optimization initially preserved this behavior; +it did not make the collision a language rule. The separate correctness fix +replaces that compatibility index with a per-block incoming-edge bit, updated +from explicit target indices only after a terminator is successfully emitted. +Every terminator declares its successors; `select` reuses its existing outcome +metadata. Calls and operand names cannot supply or mask a block edge. The bit +counts syntactic edges, including edges from disconnected blocks; this is not +entry-reachability analysis or constant folding. A host allocation failure +publishes neither the instruction nor its edges. + +The other confirmed direction was a false rejection: in +`fn f(after_2: bool) -> u64`, `while after_2 { return 1u64; } return 42u64;` +previously reported E7006 at the reachable return. The operand's earlier +`after_2` substring masked the real exit target in the conditional branch. +This now accepts, returning 42 for `false` and 1 for `true`. + +Qualification: 342 unit tests, 1,808 conformance cases (nine new), 182 targeted +CLI checks, plus the diagnostic-reason, independent-error, CFG-provenance and +hosted smoke suites. All 2,858 `check`/`lower` comparisons on 1,429 pre-existing +public sources and 240 runtime/fuel comparisons match the frozen pre-fix +executable exactly. Fourteen of the eighteen new fixture comparisons change +intentionally: five false acceptances reject E7006 `unreachable`, and two +false rejections accept; two valid break cases retain exact output. Diagnostic +priority, source/package positions, formatting, function-local state and host +OOM are covered. Incoming metadata is also checked against independently +parsed AIR successors for ten lowering programs. The frozen textual predicate +remains only in compatibility tests, with its collisions explicitly tested as +old defects. + +The [control-depth audit](control-depth-performance-audit.md#correctness-follow-up-explicit-cfg-incoming-edges-q-064-2026-10-14) +records the implementation and evidence in +`/tmp/aji-q064-20261014-x_a6b4gb/`. Spec 15 §10 already requires the corrected +behavior: no new diagnostic, source rule, verifier rule, AIR meaning or runtime +instruction is introduced. Q-063's remaining performance work stays open. diff --git a/src/frontend/liveness.zig b/src/frontend/liveness.zig index 1fac245..e7a12cb 100644 --- a/src/frontend/liveness.zig +++ b/src/frontend/liveness.zig @@ -23,11 +23,58 @@ pub const After = struct { name: []const u8, construct: Span, seen: bool = false, + memo: ?*Memo = null, + + /// One completed negative After query, borrowed only while liveAfter walks + /// outwards through its Rest frames. It is not a variable-liveness cache: + /// first-use kills, rebinding and loop reads still run in the caller. + pub const Memo = struct { + const Key = struct { + kind: enum { conditional, match, block }, + node: *const anyopaque, + span: Span, + + fn of(e: ast.Expr) ?Key { + return switch (e.kind) { + .if_expr => |p| .{ .kind = .conditional, .node = p, .span = e.span }, + .match_expr => |p| .{ .kind = .match, .node = p, .span = e.span }, + .block => |p| .{ .kind = .block, .node = p, .span = e.span }, + else => null, + }; + } + }; + entry: ?struct { key: Key, name: []const u8, construct: Span } = null, + + fn hit(self: *const Memo, e: ast.Expr, after: *const After) bool { + const entry = self.entry orelse return false; + const key = Key.of(e) orelse return false; + return key.kind == entry.key.kind and key.node == entry.key.node and + spanEq(key.span, entry.key.span) and eq(after.name, entry.name) and + spanEq(after.construct, entry.construct); + } + }; + + fn remember(w: *After, e: ast.Expr, was_seen: bool, read: bool) void { + const memo = w.memo orelse return; + // Only publish after success, with proof that this root found the + // construct. A query entered with seen=true proves no such boundary. + if (was_seen or !w.seen or read) return; + if (Memo.Key.of(e)) |key| memo.entry = .{ .key = key, .name = w.name, .construct = w.construct }; + } + pub fn expr(w: *After, a: Allocator, workspace: *Workspace, e: ast.Expr) Allocator.Error!bool { - return workspace.query(a, .after, .{ .expr = e }, w.name, null, w); + const was_seen = w.seen; + const read = try workspace.query(a, .after, .{ .expr = e }, w.name, null, w); + w.remember(e, was_seen, read); + return read; } pub fn stmt(w: *After, a: Allocator, workspace: *Workspace, st: ast.Stmt) Allocator.Error!bool { - return workspace.query(a, .after, .{ .stmt = st }, w.name, null, w); + const was_seen = w.seen; + const read = try workspace.query(a, .after, .{ .stmt = st }, w.name, null, w); + // An expression statement has the same query as its expression only + // when their position-based construct checks agree. + if (st.kind == .expr and spanEq(st.span, st.kind.expr.span)) w.remember(st.kind.expr, was_seen, read); + return read; } }; @@ -118,6 +165,15 @@ pub const Workspace = struct { current = self.work.pop() orelse return false; continue :scan; } + if (m == .after and !after.?.seen) { + if (after.?.memo) |memo| if (memo.hit(e, after.?)) { + // The same immutable subtree, name and construct + // already found the boundary and no later read. + after.?.seen = true; + current = self.work.pop() orelse return false; + continue :scan; + }; + } switch (e.kind) { .name, .move => |n| if (m != .assign and (m == .read or after.?.seen) and eq(n, name)) return true, .int, .boolean, .bytes, .variant, .specialize => {}, @@ -405,3 +461,115 @@ pub const Workspace = struct { } } }; + +fn memoTestSpan(line: u32) Span { + return .{ .start = .{ .line = line, .col = 1 }, .end = .{ .line = line, .col = 2 } }; +} + +test "after memo keys immutable node name construct and unseen entry state" { + const target: ast.Expr = .{ .span = memoTestSpan(1), .kind = .{ .boolean = true } }; + const x: ast.Expr = .{ .span = memoTestSpan(2), .kind = .{ .name = "x" } }; + const y: ast.Expr = .{ .span = memoTestSpan(3), .kind = .{ .name = "y" } }; + const branch: ast.If = .{ + .cond = .{ .span = memoTestSpan(4), .kind = .{ .boolean = true } }, + .then = .{ .span = memoTestSpan(5), .stmts = &.{.{ .span = target.span, .kind = .{ .expr = target } }}, .tail = &y }, + .@"else" = .{ .block = .{ .span = memoTestSpan(6), .stmts = &.{}, .tail = &x } }, + }; + const root: ast.Expr = .{ .span = memoTestSpan(7), .kind = .{ .if_expr = &branch } }; + var workspace: Workspace = .{}; + defer workspace.deinit(std.testing.allocator); + var memo: After.Memo = .{}; + var seed: After = .{ .name = "x", .construct = target.span, .memo = &memo }; + try std.testing.expect(!try seed.expr(std.testing.allocator, &workspace, root)); + try std.testing.expect(seed.seen and memo.entry != null); + + // A completed exact hit needs neither AST descent nor scratch allocation. + var fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + var empty: Workspace = .{}; + defer empty.deinit(fail.allocator()); + var hit: After = .{ .name = "x", .construct = target.span, .memo = &memo }; + try std.testing.expect(!try hit.expr(fail.allocator(), &empty, root)); + try std.testing.expect(hit.seen and !fail.has_induced_failure); + + var different_name: After = .{ .name = "y", .construct = target.span, .memo = &memo }; + try std.testing.expect(try different_name.expr(std.testing.allocator, &workspace, root)); + var different_construct: After = .{ .name = "x", .construct = branch.cond.span, .memo = &memo }; + try std.testing.expect(try different_construct.expr(std.testing.allocator, &workspace, root)); + var already_seen: After = .{ .name = "x", .construct = target.span, .seen = true, .memo = &memo }; + try std.testing.expect(try already_seen.expr(std.testing.allocator, &workspace, root)); + + var other_branch = branch; + other_branch.then.tail = &x; + const other: ast.Expr = .{ .span = root.span, .kind = .{ .if_expr = &other_branch } }; + var other_node: After = .{ .name = "x", .construct = target.span, .memo = &memo }; + try std.testing.expect(try other_node.expr(std.testing.allocator, &workspace, other)); + + // Neither an absent boundary nor an already-seen query may replace proof + // that the remembered root itself found the construct. + var absent: After = .{ .name = "x", .construct = memoTestSpan(99), .memo = &memo }; + try std.testing.expect(!try absent.expr(std.testing.allocator, &workspace, root)); + try std.testing.expect(!absent.seen); + const no_reads: ast.Block = .{ .span = memoTestSpan(8), .stmts = &.{}, .tail = null }; + const no_read_root: ast.Expr = .{ .span = no_reads.span, .kind = .{ .block = &no_reads } }; + var continued: After = .{ .name = "x", .construct = target.span, .seen = true, .memo = &memo }; + try std.testing.expect(!try continued.expr(std.testing.allocator, &workspace, no_read_root)); + try std.testing.expectEqual(@as(*const anyopaque, &branch), memo.entry.?.key.node); + + // Statement and expression positions can differ in library-supplied ASTs. + var statement_memo: After.Memo = .{}; + const statement: ast.Stmt = .{ .span = target.span, .kind = .{ .expr = no_read_root } }; + var statement_after: After = .{ .name = "x", .construct = target.span, .memo = &statement_memo }; + try std.testing.expect(!try statement_after.stmt(std.testing.allocator, &workspace, statement)); + try std.testing.expect(statement_after.seen and statement_memo.entry == null); + var expression_after: After = .{ .name = "x", .construct = target.span, .memo = &statement_memo }; + try std.testing.expect(!try expression_after.expr(std.testing.allocator, &workspace, no_read_root)); + try std.testing.expect(!expression_after.seen); +} + +test "after memo publishes no negative result on scratch OOM" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const target: ast.Expr = .{ .span = memoTestSpan(1), .kind = .{ .boolean = true } }; + var suffix = target; + suffix.span = memoTestSpan(2); + for (0..64) |i| { + const child = try a.create(ast.Expr); + child.* = suffix; + const branch = try a.create(ast.If); + branch.* = .{ + .cond = target, + .then = .{ .span = memoTestSpan(3), .stmts = &.{}, .tail = child }, + .@"else" = null, + }; + suffix = .{ .span = memoTestSpan(@intCast(i + 10)), .kind = .{ .if_expr = branch } }; + } + const body: ast.Block = .{ + .span = memoTestSpan(100), + .stmts = &.{.{ .span = target.span, .kind = .{ .expr = target } }}, + .tail = &suffix, + }; + const root: ast.Expr = .{ .span = body.span, .kind = .{ .block = &body } }; + var storage: [128 * 1024]u8 = undefined; + var failed_before = false; + var failed_after = false; + var succeeded = false; + for (0..129) |k| { + var backing: std.heap.FixedBufferAllocator = .init(storage[0 .. k * 1024]); + const allocation = backing.allocator(); + var workspace: Workspace = .{}; + defer workspace.deinit(allocation); + var memo: After.Memo = .{}; + var after: After = .{ .name = "missing", .construct = target.span, .memo = &memo }; + if (after.expr(allocation, &workspace, root)) |read| { + try std.testing.expect(!read and after.seen and memo.entry != null); + succeeded = true; + } else |err| { + try std.testing.expectEqual(error.OutOfMemory, err); + try std.testing.expect(memo.entry == null); + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + if (after.seen) failed_after = true else failed_before = true; + } + } + try std.testing.expect(failed_before and failed_after and succeeded); +} diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index cbe5588..f37db3a 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -216,6 +216,9 @@ const Block = struct { params: std.ArrayList(Param) = .empty, insts: std.ArrayList(Inst) = .empty, terminated: bool = false, + /// At least one successfully emitted CFG edge targets this block. This + /// counts syntactic edges, even from blocks unreachable from the entry. + has_incoming: bool = false, }; const Param = struct { name: []const u8, ty: Ty }; @@ -977,9 +980,9 @@ const Lowerer = struct { } if (tail) |v| { try l.checkTy(f.body.tail.?.span, v.ty, sig.ret); - try l.term(try l.retText(v), f.body.tail.?.span); + try l.term(try l.retText(v), f.body.tail.?.span, &.{}); } else if (sig.ret == .void) { - try l.term("ret", f.body.span); + try l.term("ret", f.body.span, &.{}); } else return l.invalid(.missing_return, f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }}); } @@ -1058,12 +1061,23 @@ const Lowerer = struct { return v; } - fn term(l: *Lowerer, text: []const u8, span: Span) Error!void { + /// Successors are block indices supplied by the construct that emits the + /// terminator, independent of printed names, operands and function calls. + /// Publish edges only after instruction emission succeeds; updating the + /// per-block bit is infallible and needs no separate host allocation. + fn term(l: *Lowerer, text: []const u8, span: Span, targets: []const usize) Error!void { try l.emit(text, span); l.blocks.items[l.cur.?].terminated = true; + for (targets) |target| l.blocks.items[target].has_incoming = true; l.cur = null; } + /// Select already stores its target indices with outcome metadata. + fn termSelect(l: *Lowerer, text: []const u8, span: Span, edges: []const SelectEdge) Error!void { + try l.term(text, span, &.{}); + for (edges) |edge| l.blocks.items[edge.block].has_incoming = true; + } + // ------------------------------------------------------------ variables and joins fn lookup(l: *Lowerer, name: []const u8) ?*Binding { @@ -1113,12 +1127,13 @@ const Lowerer = struct { /// whole-variable assignment in straight-line code before any read ends /// the variable's life. fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) Allocator.Error!bool { + var memo: After.Memo = .{}; var k = l.rest.items.len; while (k > 0) { k -= 1; const fr = l.rest.items[k]; // The rest of the statement or tail that contains the construct. - var w: After = .{ .name = name, .construct = construct }; + var w: After = .{ .name = name, .construct = construct, .memo = &memo }; if (fr.current) |c| if (try w.stmt(l.arena, &l.live_queries, c)) return true; if (fr.current_expr) |ce| if (try w.expr(l.arena, &l.live_queries, ce.*)) return true; switch (try l.live_queries.firstUse(l.arena, fr.stmts, fr.tail, name)) { @@ -1268,14 +1283,14 @@ const Lowerer = struct { try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = p.v.name, .ty = p.v.ty, .kind = .borrow }); } }, - .trap => try l.term("trap", s.span), + .trap => try l.term("trap", s.span, &.{}), .@"break", .@"continue" => { if (l.loops.items.len == 0) return l.invalid(.loop_control_outside_loop, s.span, "`break` or `continue` outside a loop", &.{}); const lp = l.loops.items[l.loops.items.len - 1]; const vars = if (s.kind == .@"break") lp.exit_vars else lp.header_vars; const target = if (s.kind == .@"break") lp.exit else lp.@"continue"; try l.endScopes(lp.scope_depth, s.span); - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span, &.{target}); }, // Child-bearing control/value statements are driven centrally. .let, .@"var", .assign, .@"return", .expr, .@"while", .loop, .@"for", .scope, .shield, .lock, .select => unreachable, @@ -1315,17 +1330,6 @@ const Lowerer = struct { return l.stmt(.{ .span = span, .kind = .{ .@"for" = .{ .name = name, .lo = lo, .hi = hi, .body = body } } }); } - fn reaches(l: *Lowerer, block: usize) bool { - const name = l.blocks.items[block].name; - for (l.blocks.items) |b| for (b.insts.items) |inst| { - if (std.mem.indexOf(u8, inst.text, name)) |at| { - const end = at + name.len; - if (at > 0 and inst.text[at - 1] == '@' and (end == inst.text.len or inst.text[end] == '(')) return true; - } - }; - return false; - } - // ------------------------------------------------------------ expressions /// The type of an expression without lowering it, where it follows @@ -1940,7 +1944,7 @@ const Lowerer = struct { try l.joinParams(header, vars); try l.joinParams(exit, exit_vars); if (step != null) try l.joinParams(cont, vars); - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span, &.{header}); l.cur = header; l.rebindToParams(header, vars, 0); const state = try l.arena.create(LoopState); @@ -1963,7 +1967,7 @@ const Lowerer = struct { // The old loop only pops on successful body completion. Error exits // retain that state; lexical block/range defers still unwind normally. _ = l.loops.pop(); - if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[state.cont].name, try l.argsOf(state.vars, null) }), state.body.span); + if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[state.cont].name, try l.argsOf(state.vars, null) }), state.body.span, &.{state.cont}); if (state.step) |st| { l.cur = state.cont; l.rebindToParams(state.cont, state.vars, 0); @@ -1971,11 +1975,11 @@ const Lowerer = struct { const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{try l.tyText(i.ty)}), st.span); const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ try l.tyText(i.ty), i.value, one.name }), st.span); l.lookup(st.name).?.value = next.name; - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[state.header].name, try l.argsOf(state.vars, null) }), st.span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[state.header].name, try l.argsOf(state.vars, null) }), st.span, &.{state.header}); } l.cur = state.exit; l.rebindToParams(state.exit, state.exit_vars, 0); - if (!l.reaches(state.exit)) l.cur = null; + if (!l.blocks.items[state.exit].has_incoming) l.cur = null; } fn enterDriveFor(l: *Lowerer, st: ast.Stmt, pending: *std.ArrayList(DriveFrame), active: *std.ArrayList(ActiveDriveScope)) Error!DriveRequest { @@ -2058,7 +2062,7 @@ const Lowerer = struct { if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", d.name, v.name })); } if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }}); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); state.mode = .declared; state.blocks = blocks; return l.advanceDriveMatch(state, pending); @@ -2099,7 +2103,7 @@ const Lowerer = struct { } const d = default orelse return l.fail("E7004", m.span, "a `match` over an integer needs a `_` arm", &.{}); try head.appendSlice(l.arena, try l.fmt("default -> @{s}()", .{l.blocks.items[blocks[d]].name})); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); state.blocks = blocks; return l.advanceDriveMatch(state, pending); } @@ -2131,7 +2135,7 @@ const Lowerer = struct { if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", name, v })); } if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }}); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); state.blocks = blocks; return l.advanceDriveMatch(state, pending); } @@ -2248,7 +2252,7 @@ const Lowerer = struct { const guard = try l.freshName("guard"); try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) }); const canc = try l.newBlock("lock_cancelled", cancelled.span); - try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span); + try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span, &.{ locked, canc }); l.cur = locked; const x = try l.def(name, try l.wrap(.mut, elem), try l.fmt("mutex.borrow %{s}", .{guard}), s.span); @@ -2424,7 +2428,7 @@ const Lowerer = struct { } } try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name})); - try l.term(text.items, s.span); + try l.termSelect(text.items, s.span, edges.items); state.temps = temps.items; state.edges = edges.items; @@ -2516,7 +2520,7 @@ const Lowerer = struct { state.vars = try l.carriedLive(depth, state.span, .{ .@"if" = state.x }); state.then_block = try l.newBlock("then", state.x.then.span); state.else_block = try l.newBlock("else", state.span); - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[state.then_block].name, l.blocks.items[state.else_block].name }), state.x.cond.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[state.then_block].name, l.blocks.items[state.else_block].name }), state.x.cond.span, &.{ state.then_block, state.else_block }); state.before = try l.snapshot(); l.restore(state.before); l.cur = state.then_block; @@ -2632,7 +2636,7 @@ const Lowerer = struct { } if (l.ret != .void) return l.fail("E7005", st.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = try l.diagnosticTyText(l.ret) }}); try l.endScopes(0, st.span); - try l.term("ret", st.span); + try l.term("ret", st.span, &.{}); return .{ .output = .statement }; }, else => unreachable, @@ -2683,7 +2687,7 @@ const Lowerer = struct { try l.checkTy(input.?.span, v.ty, l.ret); if (l.cur != null) { try l.endScopesExcept(0, st.span, if (v.ty.isBorrow()) v.name else null); - try l.term(try l.retText(v), st.span); + try l.term(try l.retText(v), st.span, &.{}); } }, else => unreachable, @@ -3107,8 +3111,8 @@ const Lowerer = struct { try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); const jn = l.blocks.items[join].name; if (x.op == .@"and") { - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span); - } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span, &.{ rhs_b, join }); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span, &.{ rhs_b, join }); l.cur = rhs_b; try l.pushOperand(&pending, .{ .boolean_right = .{ .e = parent, .join = join, .name = rname } }); e = x.r.*; @@ -3118,7 +3122,7 @@ const Lowerer = struct { }, .boolean_right => |frame| { try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, .bool); - try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span); + try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span, &.{frame.join}); l.cur = frame.join; v = .{ .name = frame.name, .ty = .bool }; }, @@ -3216,7 +3220,7 @@ const Lowerer = struct { const cv = completed.expression; try l.checkOperandTy(c.span, cv.ty, .bool); const body_block = try l.newBlock("body", state.body.span); - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_block].name, l.blocks.items[state.exit].name, try l.argsOf(state.exit_vars, null) }), c.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_block].name, l.blocks.items[state.exit].name, try l.argsOf(state.exit_vars, null) }), c.span, &.{ body_block, state.exit }); l.cur = body_block; request = try l.beginDriveLoopBody(state, &pending); continue :evaluate; @@ -3595,7 +3599,7 @@ const Lowerer = struct { if (sig.ret == .void or sig.ret == .never) { try l.emit(text, e.span); if (sig.ret == .never) { - try l.term("trap", e.span); + try l.term("trap", e.span, &.{}); return .{ .name = "", .ty = .never }; } try l.endNowIfLive(c.temps.items, e.span); @@ -3785,7 +3789,7 @@ const Lowerer = struct { l.restore(a.values); const vt: Ty = if (a.value) |v| v.ty else .void; if (vt == .never) continue; - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[join].name, try l.argsOf(vars, if (has_value) a.value.?.name else null) }), a.span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[join].name, try l.argsOf(vars, if (has_value) a.value.?.name else null) }), a.span, &.{join}); }; l.restore(before); l.cur = join; @@ -4213,7 +4217,7 @@ const Lowerer = struct { try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t }); if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false }); } - try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, try l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span); + try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, try l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span, &.{next}); l.cur = next; l.linear_enabled = true; } @@ -5007,7 +5011,7 @@ const Lowerer = struct { } try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name })); } - try l.term(text.items, span); + try l.term(text.items, span, blocks); // The operation's temporary borrows end on every edge. for (blocks) |b| { l.cur = b; @@ -5024,7 +5028,7 @@ const Lowerer = struct { const blocks = try l.outcomeBlocks(f, e.span); for (f.outcomes, blocks) |o, blk| if (!std.mem.eql(u8, o.role, "ok")) { l.cur = blk; - try l.term("trap", e.span); + try l.term("trap", e.span, &.{}); }; const ok = for (f.outcomes, blocks) |o, blk| { if (std.mem.eql(u8, o.role, "ok")) break blk; @@ -5147,7 +5151,7 @@ test "terminated blocks reject further emission with a source diagnostic" { var l: Lowerer = .{ .arena = scratch.allocator(), .m = .{ .name = "test", .types = &.{}, .functions = &.{} } }; const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } }; l.cur = try l.newBlock("entry", span); - try l.term("trap", span); + try l.term("trap", span, &.{}); try std.testing.expectError(error.Lower, l.emit("ret", span)); try std.testing.expectEqualStrings("E7006", l.problem.?.code); try std.testing.expectEqual(InvalidReason.@"unreachable", l.problem.?.reason.?); @@ -5156,6 +5160,173 @@ test "terminated blocks reject further emission with a source diagnostic" { try std.testing.expect(l.blocks.items[0].terminated); } +// Frozen pre-Q-064 textual predicate used only by the control-lowering oracle. +// Its naming collisions are deliberately covered separately from compatibility. +fn referenceReaches(l: *const Lowerer, block: usize) bool { + const name = l.blocks.items[block].name; + for (l.blocks.items) |b| for (b.insts.items) |inst| { + if (std.mem.indexOf(u8, inst.text, name)) |at| { + const end = at + name.len; + if (at > 0 and inst.text[at - 1] == '@' and (end == inst.text.len or inst.text[end] == '(')) return true; + } + }; + return false; +} + +test "CFG incoming edges ignore function references and operand name collisions" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + var l: Lowerer = .{ .arena = scratch.allocator(), .m = .{ .name = "test", .types = &.{}, .functions = &.{} } }; + const span = unaryTestSpan(1); + l.cur = try l.newBlock("entry", span); + const exit = try l.newBlock("after", span); + const other = try l.newBlock("after", span); + try l.emit("call @after_1()", span); + try l.emit("%after_1 = const.bool false", span); + try std.testing.expect(referenceReaches(&l, exit)); // Old false positive. + try std.testing.expect(!l.blocks.items[exit].has_incoming); + try std.testing.expect(!l.blocks.items[other].has_incoming); + try l.term("cbr %after_2, @after_1(), @after_2()", span, &.{ exit, other }); + try std.testing.expect(!referenceReaches(&l, other)); // Old false negative. + try std.testing.expect(l.blocks.items[exit].has_incoming); + try std.testing.expect(l.blocks.items[other].has_incoming); + try std.testing.expect(!l.blocks.items[0].has_incoming); + try std.testing.expect(l.blocks.items[0].terminated); + try std.testing.expect(l.cur == null); + + // This is incoming-edge existence, not entry reachability or constant + // folding: an edge from a disconnected block still counts. + const disconnected = try l.newBlock("disconnected", span); + const target = try l.newBlock("target", span); + l.cur = disconnected; + try l.term(try l.fmt("br @{s}()", .{l.blocks.items[target].name}), span, &.{target}); + try std.testing.expect(!l.blocks.items[disconnected].has_incoming); + try std.testing.expect(l.blocks.items[target].has_incoming); + try std.testing.expectError(error.Lower, l.term("br @entry()", span, &.{0})); + try std.testing.expect(!l.blocks.items[0].has_incoming); +} + +test "incoming metadata agrees with independently parsed AIR successors" { + const programs = [_][]const u8{ + "fn main() -> u64 effects [] { while false { loop { if true { break; } else { continue; } } } return 42u64; }", + "fn main() -> u64 effects [] { var x: u64 = 0u64; for i in 0u64..2u64 { x = i; } if false or true and true { x = 42u64; } return x; }", + "enum E { A(u64), B } fn main() -> u64 effects [] { let e = E::A(42u64); match e { E::A(x) => x, E::B => 0u64 } }", + "fn main() -> u64 effects [] { match 0u8 { 0 => 42u64, _ => 0u64 } }", + "fn main() -> u64 effects [] { match alloc_error::out_of_memory { alloc_error::out_of_memory => 42u64, alloc_error::budget_exceeded => 0u64 } }", + "fn main(heap: cap) -> u64 effects [mem.alloc] { let r = region.create(heap) or trap; region.destroy(move r); return 42u64; }", + "fn main() -> u64 effects [task.wait] { let m = mutex.make(42u64); lock ref m as x { *x = 7u64; } cancelled { trap; } return mutex.take(move m); }", + "fn f(rx: receiver) -> u64 effects [task.wait] { select { recv(rx) { ok(x) => { return x; } closed => { return 0u64; } } cancelled => { return 1u64; } } } fn main() -> u64 effects [] { return 42u64; }", + "struct Pair { a: own, b: own } fn f(p: Pair) -> void effects [] { let (a, b) = struct.unpack(move p); own.free(move a); own.free(move b); } fn main() -> u64 effects [] { return 42u64; }", + "fn f(xs: [own; 2]) -> void effects [] { let (a, b) = array.unpack(move xs); own.free(move a); own.free(move b); } fn main() -> u64 effects [] { return 42u64; }", + }; + for (programs) |program| { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "module edges\n{s}\n", .{program})); + try std.testing.expect(parsed == .ok); + var l: Lowerer = .{ .arena = a, .m = parsed.ok }; + try l.run(); + const air = try @import("../air/parse.zig").parse(a, "", l.out.items); + try std.testing.expectEqual(@as(usize, 0), air.diagnostics.len); + try std.testing.expectEqual(l.fns.items.len, air.module.?.functions.len); + for (l.fns.items, air.module.?.functions) |emitted, function| { + const incoming = try a.alloc(bool, emitted.blocks.len); + @memset(incoming, false); + var targets: std.ArrayList(u32) = .empty; + for (function.blocks) |block| for (block.insts) |inst| { + targets.clearRetainingCapacity(); + try air_module.successors(inst.op, &targets, a); + for (targets.items) |target| { + const name = function.blocks[target].name; + for (emitted.blocks, 0..) |candidate, index| { + if (std.mem.eql(u8, candidate.name, name)) { + incoming[index] = true; + break; + } + } else return error.TestUnexpectedResult; + } + }; + for (emitted.blocks, incoming) |block, expected| try std.testing.expectEqual(expected, block.has_incoming); + } + } +} + +fn loopExitEmissionAllocationProbe(a: Allocator) !void { + const span = unaryTestSpan(1); + var blocks = [_]Block{ + .{ .name = "entry", .span = span }, + .{ .name = "after_1", .span = span }, + .{ .name = "after_2", .span = span }, + }; + var l: Lowerer = .{ + .arena = a, + .m = .{ .name = "test", .types = &.{}, .functions = &.{} }, + .blocks = .fromOwnedSlice(&blocks), + .cur = 0, + }; + defer blocks[0].insts.deinit(a); + l.term("cbr %after_1, @after_1(), @after_2()", span, &.{ 1, 2 }) catch |err| { + try std.testing.expectEqual(@as(usize, 0), blocks[0].insts.items.len); + try std.testing.expect(!blocks[0].terminated); + try std.testing.expect(!blocks[1].has_incoming); + try std.testing.expect(!blocks[2].has_incoming); + try std.testing.expectEqual(@as(?usize, 0), l.cur); + return err; + }; + try std.testing.expectEqual(@as(usize, 1), blocks[0].insts.items.len); + try std.testing.expect(blocks[0].terminated); + try std.testing.expect(blocks[1].has_incoming); + try std.testing.expect(blocks[2].has_incoming); + try std.testing.expect(l.cur == null); +} + +test "CFG edges and termination publish only after successful instruction emission" { + try std.testing.checkAllAllocationFailures(std.testing.allocator, loopExitEmissionAllocationProbe, .{}); +} + +fn loopExitLoweringAllocationProbe(a: Allocator, module: ast.Module, rejected_line: ?u32) !void { + const result = try lower(a, module); + if (rejected_line == null) { + try std.testing.expect(result == .ok); + } else { + try std.testing.expect(result == .err); + try std.testing.expectEqualStrings("E7006", result.err.code); + try std.testing.expectEqual(InvalidReason.@"unreachable", result.err.reason.?); + try std.testing.expectEqual(rejected_line.?, result.err.span.start.line); + } +} + +test "CFG incoming edges are function local and lowering OOM stays a host error" { + var fixture = std.heap.ArenaAllocator.init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module t\nfn main() -> u64 effects [] { while false { loop { break; } } return 1u64; }\n", + "module t\nfn after_2() -> void effects [] {}\nfn main() -> u64 effects [] { loop { after_2(); return 0u64; } return 1u64; }\n", + "module t\nfn after_2() -> void effects [] {}\nfn first() -> u64 effects [] { loop { after_2(); break; } return 1u64; }\nfn main() -> u64 effects [] { loop { return 0u64; } return 1u64; }\n", + }; + for (programs, 0..) |program, index| { + const parsed = try parse_mod.parse(fixture.allocator(), program); + try std.testing.expect(parsed == .ok); + for ([_]bool{ false, true }) |sticky| { + var fail_at: 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 allocation: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at, .sticky = sticky }; + const result = loopExitLoweringAllocationProbe(allocation.allocator(), parsed.ok, if (index == 0) null else @as(u32, @intCast(index + 2))); + if (allocation.failed) { + try std.testing.expectError(error.OutOfMemory, result); + } else try result; + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!allocation.failed) break; + } + } + } +} + // Independent old expected-use descent, including the outer rest/shadow // cursor. Type/name/signature queries are shared, not independently derived. const ReferenceUseQuery = struct { @@ -5785,7 +5956,7 @@ const ReferenceCalls = struct { if (sig.ret == .void or sig.ret == .never) { try l.emit(text, e.span); if (sig.ret == .never) { - try l.term("trap", e.span); // `never` returns do not come back + try l.term("trap", e.span, &.{}); // `never` returns do not come back return .{ .name = "", .ty = .never }; } try l.endNowIfLive(temps.items, e.span); @@ -6012,12 +6183,12 @@ const ReferenceOperands = struct { try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); const jn = l.blocks.items[join].name; if (op == .@"and") { - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span); - } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span, &.{ rhs_b, join }); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span, &.{ rhs_b, join }); l.cur = rhs_b; const rv = try expr(l, b, .bool); try l.checkOperandTy(b.span, rv.ty, .bool); - try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span); + try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span, &.{join}); l.cur = join; return .{ .name = rname, .ty = .bool }; }, @@ -10737,6 +10908,83 @@ test "liveAfter rest frames preserve shared seen kills backedges and inner first try std.testing.expect(!try l.liveAfter("x", kill.span)); } +test "after memo across Rest frames preserves frozen kills siblings loop reads and spans" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const x: ast.Expr = .{ .span = unaryTestSpan(50), .kind = .{ .name = "x" } }; + const v: ast.Expr = .{ .span = unaryTestSpan(51), .kind = .{ .name = "v" } }; + const kill: ast.Stmt = .{ .span = unaryTestSpan(52), .kind = .{ .assign = .{ .place = x, .e = v } } }; + const read: ast.Stmt = .{ .span = x.span, .kind = .{ .expr = x } }; + const empty: ast.Block = .{ .span = unaryTestSpan(53), .stmts = &.{}, .tail = null }; + var layers: std.ArrayList(ast.Expr) = .empty; + var e: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .boolean = true } }; + try layers.append(a, e); + for (0..9) |i| { + e = try queryNest(a, e, ([_]usize{ 3, 4, 6, 8, 10 })[i % 5], i); + try layers.append(a, e); + } + var l: Lowerer = .{ .arena = a, .m = .{ .name = "q", .types = &.{}, .functions = &.{} } }; + defer l.live_queries.deinit(a); + for (0..8) |variant| { + const frames = try a.alloc(Rest, layers.items.len); + for (layers.items, 0..) |layer, i| { + frames[frames.len - 1 - i] = .{ .stmts = &.{}, .tail = null }; + const fr = &frames[frames.len - 1 - i]; + if (variant % 2 == 0) fr.current_expr = try box(a, layer) else { + fr.current = .{ .span = if (i % 2 == 0) layer.span else unaryTestSpan(900), .kind = .{ .expr = layer } }; + if (variant == 7) fr.current_expr = &v; + } + } + switch (variant) { + 0 => frames[0].tail = &x, + 1 => frames[frames.len / 2].stmts = &.{ kill, read }, + 2 => frames[frames.len / 2].stmts = &.{ read, kill }, + 3 => frames[frames.len / 2].loop = .{ .cond = x, .body = empty, .step = null }, + 4 => frames[frames.len / 2].loop = .{ .cond = null, .body = empty, .step = "x" }, + else => {}, + } + l.rest.items = frames; + l.rest.capacity = frames.len; + for ([_][]const u8{ "x", "v", "rx", "missing" }) |name| { + for (layers.items) |layer| { + var span = layer.span; + if (variant == 6) { + span.file = "another.aji"; + span.namespace = "other"; + } + try std.testing.expectEqual(ReferenceLiveness.liveAfter(&l, name, span), try l.liveAfter(name, span)); + } + try std.testing.expectEqual(ReferenceLiveness.liveAfter(&l, name, unaryTestSpan(999)), try l.liveAfter(name, unaryTestSpan(999))); + } + } +} + +test "after memo walks deep enclosing matches with bounded query scratch" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const depth = 4096; + const frames = try a.alloc(Rest, depth + 1); + var e: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .boolean = true } }; + const construct = e.span; + for (0..depth + 1) |i| { + frames[depth - i] = .{ .stmts = &.{}, .tail = null, .current_expr = try box(a, e) }; + if (i != depth) e = try queryNest(a, e, ([_]usize{ 3, 4, 6 })[i % 3], i); + } + var l: Lowerer = .{ .arena = a, .m = .{ .name = "q", .types = &.{}, .functions = &.{} } }; + l.rest.items = frames; + l.rest.capacity = frames.len; + defer l.live_queries.deinit(a); + try std.testing.expect(!try l.liveAfter("missing", construct)); + const read: ast.Expr = .{ .span = unaryTestSpan(9999), .kind = .{ .name = "missing" } }; + frames[0].tail = &read; + try std.testing.expect(try l.liveAfter("missing", construct)); + // One prior completed subtree replaces descent through all ancestors. + try std.testing.expect(l.live_queries.work.capacity <= 16); + try std.testing.expectEqual(@as(usize, 0), l.live_queries.work.items.len); +} + test "liveness cursors preserve old reads assigns first use and after scope policies" { const statements = [_][]const u8{ "let y: u8 = x;", "let (x, y) = f(v);", "var x: u8 = zero;", "var v: u8 = x;", @@ -11289,22 +11537,22 @@ const ReferenceControl = struct { try l.checkTy(x.span, v.ty, l.ret); if (l.cur != null) { try l.endScopesExcept(0, s.span, if (v.ty.isBorrow()) v.name else null); - try l.term(try l.retText(v), s.span); + try l.term(try l.retText(v), s.span, &.{}); } } else { if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = try l.diagnosticTyText(l.ret) }}); try l.endScopes(0, s.span); - try l.term("ret", s.span); + try l.term("ret", s.span, &.{}); } }, - .trap => try l.term("trap", s.span), + .trap => try l.term("trap", s.span, &.{}), .@"break", .@"continue" => { if (l.loops.items.len == 0) return l.invalid(.loop_control_outside_loop, s.span, "`break` or `continue` outside a loop", &.{}); const lp = l.loops.items[l.loops.items.len - 1]; const vars = if (s.kind == .@"break") lp.exit_vars else lp.header_vars; const target = if (s.kind == .@"break") lp.exit else lp.@"continue"; try l.endScopes(lp.scope_depth, s.span); - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span, &.{target}); }, .expr => |e| { const v = try ReferenceControl.expr(l, e, null); @@ -11344,7 +11592,7 @@ const ReferenceControl = struct { try l.joinParams(header, vars); try l.joinParams(exit, exit_vars); if (step != null) try l.joinParams(cont, vars); - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span, &.{header}); l.cur = header; l.rebindToParams(header, vars, 0); @@ -11352,14 +11600,14 @@ const ReferenceControl = struct { const cv = try ReferenceControl.expr(l, c, .bool); try l.checkOperandTy(c.span, cv.ty, .bool); const body_b = try l.newBlock("body", body.span); - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(exit_vars, null) }), c.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(exit_vars, null) }), c.span, &.{ body_b, exit }); l.cur = body_b; } try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth, .scope_depth = l.scopes.items.len, .header_vars = vars, .exit_vars = exit_vars }); l.pending_loop = lp_ast; _ = try ReferenceControl.blockBody(l, body); _ = l.loops.pop(); - if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span); + if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span, &.{cont}); if (step) |st| { l.cur = cont; l.rebindToParams(cont, vars, 0); @@ -11367,12 +11615,12 @@ const ReferenceControl = struct { const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{try l.tyText(i.ty)}), st.span); const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ try l.tyText(i.ty), i.value, one.name }), st.span); l.lookup(st.name).?.value = next.name; - try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span, &.{header}); } l.cur = exit; l.rebindToParams(exit, exit_vars, 0); // A `loop` without `break` never reaches its exit. - if (!l.reaches(exit)) l.cur = null; + if (!referenceReaches(l, exit)) l.cur = null; } fn forLoop(l: *Lowerer, span: Span, name: []const u8, lo: ast.Expr, hi: ast.Expr, body: ast.Block) Error!void { @@ -11719,8 +11967,8 @@ const ReferenceControl = struct { try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); const jn = l.blocks.items[join].name; if (x.op == .@"and") { - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span); - } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span, &.{ rhs_b, join }); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span, &.{ rhs_b, join }); l.cur = rhs_b; try pending.append(l.arena, .{ .boolean_right = .{ .e = parent, .join = join, .name = rname } }); e = x.r.*; @@ -11729,7 +11977,7 @@ const ReferenceControl = struct { }, .boolean_right => |frame| { try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, .bool); - try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span); + try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span, &.{frame.join}); l.cur = frame.join; v = .{ .name = frame.name, .ty = .bool }; }, @@ -11816,7 +12064,7 @@ const ReferenceControl = struct { const vars = try l.carriedLive(depth, span, .{ .@"if" = x }); const then_b = try l.newBlock("then", x.then.span); const else_b = try l.newBlock("else", span); - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span, &.{ then_b, else_b }); const before = try l.snapshot(); var ends: [2]ArmEnd = undefined; for (0..2) |k| { @@ -11887,7 +12135,7 @@ const ReferenceControl = struct { if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", d.name, v.name })); } if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }}); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); for (m.arms, blocks) |arm, blk| { l.restore(before); l.cur = blk; @@ -11938,7 +12186,7 @@ const ReferenceControl = struct { } const d = default orelse return l.fail("E7004", m.span, "a `match` over an integer needs a `_` arm", &.{}); try head.appendSlice(l.arena, try l.fmt("default -> @{s}()", .{l.blocks.items[blocks[d]].name})); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); for (m.arms, blocks) |arm, blk| { l.restore(before); l.cur = blk; @@ -11975,7 +12223,7 @@ const ReferenceControl = struct { if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", name, v })); } if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }}); - try l.term(head.items, m.span); + try l.term(head.items, m.span, blocks); var ends: std.ArrayList(ArmEnd) = .empty; for (m.arms, blocks) |arm, blk| { l.restore(before); @@ -12057,7 +12305,7 @@ const ReferenceControl = struct { const blocks = try l.outcomeBlocks(f, e.span); for (f.outcomes, blocks) |o, blk| if (!std.mem.eql(u8, o.role, "ok")) { l.cur = blk; - try l.term("trap", e.span); + try l.term("trap", e.span, &.{}); }; const ok = for (f.outcomes, blocks) |o, blk| { if (std.mem.eql(u8, o.role, "ok")) break blk; @@ -12281,7 +12529,7 @@ const ReferenceControl = struct { const guard = try l.freshName("guard"); try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) }); const canc = try l.newBlock("lock_cancelled", cancelled.span); - try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span); + try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span, &.{ locked, canc }); var ends: std.ArrayList(ArmEnd) = .empty; l.cur = locked; @@ -12351,7 +12599,7 @@ const ReferenceControl = struct { } } // Edges: per arm `ok` and `closed`, then `cancelled`. - const Edge = struct { arm: ?usize, role: []const u8, params: []const Ty, values: []const usize, block: usize = 0 }; + const Edge = Lowerer.SelectEdge; var edges: std.ArrayList(Edge) = .empty; const notSent = struct { fn f(lw: *Lowerer, n: usize, sent: ?usize) Error![]const usize { @@ -12406,7 +12654,7 @@ const ReferenceControl = struct { } } try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name})); - try l.term(text.items, s.span); + try l.termSelect(text.items, s.span, edges.items); var ends: std.ArrayList(ArmEnd) = .empty; for (edges.items) |ed| { diff --git a/tests/conformance/source/loop_exit/call_break.aji b/tests/conformance/source/loop_exit/call_break.aji new file mode 100644 index 0000000..2295f10 --- /dev/null +++ b/tests/conformance/source/loop_exit/call_break.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); break; } + return 42u64; +} diff --git a/tests/conformance/source/loop_exit/call_continue.aji b/tests/conformance/source/loop_exit/call_continue.aji new file mode 100644 index 0000000..5e47604 --- /dev/null +++ b/tests/conformance/source/loop_exit/call_continue.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); continue; } + return 1u64; +} diff --git a/tests/conformance/source/loop_exit/call_return.aji b/tests/conformance/source/loop_exit/call_return.aji new file mode 100644 index 0000000..708adb4 --- /dev/null +++ b/tests/conformance/source/loop_exit/call_return.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); return 0u64; } + return 1u64; +} diff --git a/tests/conformance/source/loop_exit/call_trap.aji b/tests/conformance/source/loop_exit/call_trap.aji new file mode 100644 index 0000000..82ff435 --- /dev/null +++ b/tests/conformance/source/loop_exit/call_trap.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); trap; } + return 1u64; +} diff --git a/tests/conformance/source/loop_exit/condition_parameter.aji b/tests/conformance/source/loop_exit/condition_parameter.aji new file mode 100644 index 0000000..60f7f4c --- /dev/null +++ b/tests/conformance/source/loop_exit/condition_parameter.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn f(after_2: bool) -> u64 effects [] { + while after_2 { return 1u64; } + return 42u64; +} +fn main() -> u64 effects [] { f(false) } diff --git a/tests/conformance/source/loop_exit/condition_prefix.aji b/tests/conformance/source/loop_exit/condition_prefix.aji new file mode 100644 index 0000000..7b84e42 --- /dev/null +++ b/tests/conformance/source/loop_exit/condition_prefix.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn f(after_20: bool) -> u64 effects [] { + while after_20 { return 1u64; } + return 42u64; +} +fn main() -> u64 effects [] { f(false) } diff --git a/tests/conformance/source/loop_exit/conditional_break.aji b/tests/conformance/source/loop_exit/conditional_break.aji new file mode 100644 index 0000000..85d99b4 --- /dev/null +++ b/tests/conformance/source/loop_exit/conditional_break.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); if true { break; } else { return 1u64; } } + return 42u64; +} diff --git a/tests/conformance/source/loop_exit/function_isolation.aji b/tests/conformance/source/loop_exit/function_isolation.aji new file mode 100644 index 0000000..bacfe82 --- /dev/null +++ b/tests/conformance/source/loop_exit/function_isolation.aji @@ -0,0 +1,10 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn first() -> u64 effects [] { loop { break; } return 42u64; } +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { after_2(); return 0u64; } + return 1u64; +} diff --git a/tests/conformance/source/loop_exit/nested_return.aji b/tests/conformance/source/loop_exit/nested_return.aji new file mode 100644 index 0000000..19264fa --- /dev/null +++ b/tests/conformance/source/loop_exit/nested_return.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §4, §10 +module test.loop_exit +fn after_2() -> void effects [] {} +fn main() -> u64 effects [] { + loop { loop { after_2(); return 0u64; } } + return 1u64; +} diff --git a/tests/hosted/source_loop_exit.py b/tests/hosted/source_loop_exit.py new file mode 100644 index 0000000..db52713 --- /dev/null +++ b/tests/hosted/source_loop_exit.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Q-064: CFG loop exits, name collisions, diagnostic priority and packages.""" +import json +from pathlib import Path +import re +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / 'zig-out/bin/aji' +CORPUS = REPO / 'tests/conformance/source/loop_exit' +checks = 0 + + +def cli(*args, code=0): + global checks + p = subprocess.run([str(AJI), *map(str, args)], capture_output=True) + assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr) + assert not p.stderr, (args, p.stderr) + checks += 1 + return p.stdout + + +def diagnostics(path, expected, args=None): + arguments = args if args is not None else [path] + output = cli('check', *arguments, code=1) + records = [json.loads(line) for line in output.splitlines()] + assert len(records) == len(expected), records + for d, (code, reason, marker) in zip(records, expected): + assert (d['code'], d.get('reason')) == (code, reason), d + assert 'air_line' not in d and 'air_code' not in d, d + line = path.read_text().splitlines()[d['line'] - 1] + assert line[d['col'] - 1:].startswith(marker), (d, line, marker) + assert d['file'] == (path.name if args is not None else str(path)), d + for command in ('lower', 'run', 'report'): + assert cli(command, *arguments, code=1) == output, (command, records) + assert cli('check', *arguments, code=1) == output + return records + + +with tempfile.TemporaryDirectory(prefix='aji-loop-exit-') as directory: + root = Path(directory) + # Conformance pins acceptance; these assertions additionally pin reason, + # source coordinates, stable CLI bytes and canonical formatted lowering. + for source in sorted(CORPUS.glob('*.aji')): + text = source.read_text() + if '// expect: reject E7006' in text: + diagnostics(source, [('E7006', 'unreachable', 'return 1u64;')]) + continue + air = cli('lower', source) + air_path = root / (source.stem + '.air') + air_path.write_bytes(air) + cli('check', source) + cli('check', air_path) + formatted = root / source.name + formatted.write_bytes(cli('fmt', source)) + assert cli('fmt', formatted) == formatted.read_bytes() + assert cli('lower', formatted) == air + expected = int(re.search(r'// result: (\d+)', text)[1]) + for fuel in (0, 1, 2, 4, 8, 16, 32, 64, 256): + code = None + records = [] + # Fuel limits may reject at different source/AIR positions only + # for traps. These fixtures return or exhaust fuel, so exact bytes + # and exits must match between the source and its canonical AIR. + for path in (source, air_path): + p = subprocess.run([str(AJI), 'run', '--fuel', str(fuel), str(path)], + capture_output=True) + checks += 1 + assert p.returncode in (0, 5) and not p.stderr, (path, p) + if code is None: + code = p.returncode + assert p.returncode == code, (path, fuel, p.stdout) + records.append(p.stdout) + assert records[0] == records[1], (source, fuel, records) + if fuel == 256: + assert json.loads(records[0]) == {'status': 'returned', 'value': expected} + + # Names and name prefixes never replace the syntactic exit edge. Both + # branch outcomes remain explicit; constant conditions are not folded. + for parameter in ('after_2', 'after_20', 'after_2suffix', 'flag'): + source = root / (parameter + '.aji') + source.write_text(f'module exits\nfn f({parameter}: bool) -> u64 effects [] {{\n' + f' while {parameter} {{ return 7u64; }}\n' + ' return 42u64;\n}\n' + 'fn main() -> u64 effects [] { f(false) }\n') + cli('check', source) + assert json.loads(cli('run', '--fuel', '256', source))['value'] == 42 + source.write_text(source.read_text().replace('f(false)', 'f(true)')) + assert json.loads(cli('run', '--fuel', '256', source))['value'] == 7 + source = root / 'syntactic-break.aji' + source.write_text('module exits\nfn main() -> u64 effects [] {\n' + ' loop { if false { break; } }\n return 42u64;\n}\n') + cli('check', source) + assert json.loads(cli('run', '--fuel', '256', source, code=5))['status'] == 'limit_exceeded' + + # The unreachable statement wins over its own unknown name/type error; + # earlier body and signature errors keep their existing priority. + prefix = 'module priority\nfn after_2() -> void effects [] {}\n' + cases = [ + ('late_name', prefix + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n missing();\n}\n', + [('E7006', 'unreachable', 'missing();')]), + ('late_type', prefix + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n return true;\n}\n', + [('E7006', 'unreachable', 'return true;')]), + ('early_name', prefix + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); missing(); return 0u64; }\n return 1u64;\n}\n', + [('E7002', None, 'missing')]), + ('early_type', prefix + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); return true; }\n return 1u64;\n}\n', + [('E7005', None, 'true')]), + ('signature', prefix + 'fn main(x: void) -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n', + [('E7005', None, 'void')]), + ('independent', prefix + 'fn first() -> u64 effects [] { missing() }\n' + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n', + [('E7002', None, 'missing'), ('E7006', 'unreachable', 'return 1u64;')]), + ('tail', prefix + 'fn main() -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n 1u64\n}\n', + [('E7006', 'unreachable', '1u64')]), + ('never_call', 'module priority\nfn after_2() -> never effects [] { trap; }\n' + 'fn main() -> u64 effects [] {\n loop { after_2(); }\n return 1u64;\n}\n', + [('E7006', 'unreachable', 'return 1u64;')]), + ] + for name, text, expected in cases: + source = root / (name + '.aji') + source.write_text(text) + diagnostics(source, expected) + + # Imported bodies retain source provenance after symbol mangling and + # function-local metadata reset, for both corrected acceptance directions. + entry, lib, manifest = (root / name for name in ('main.aji', 'lib.aji', 'aji.toml')) + entry.write_text('module app\nimport lib;\nfn main() -> u64 effects [] { lib.f(false) }\n') + manifest.write_text('[package]\nname = "exits"\nversion = "1"\nentry = "main.aji"\n' + '[modules]\nlib = "lib.aji"\n') + lib.write_text('module lib\nfn f(after_2: bool) -> u64 effects [] {\n' + ' while after_2 { return 7u64; }\n return 42u64;\n}\n') + cli('check', '--manifest', manifest) + assert json.loads(cli('run', '--fuel', '256', '--manifest', manifest))['value'] == 42 + lib.write_text('module lib\nfn after_2() -> void effects [] {}\n' + 'fn f(flag: bool) -> u64 effects [] {\n' + ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n') + diagnostics(lib, [('E7006', 'unreachable', 'return 1u64;')], ['--manifest', manifest]) + +print(f'source loop exit passed ({checks} CLI checks)')