diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f5e24bb..0520306 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,6 +34,7 @@ python3 tests/hosted/source_store_modes.py # exclusive places, source positions, python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity python3 tests/hosted/source_expression_depth.py # deep unary chains, exact AIR/fuel and rejection positions +python3 tests/hosted/source_liveness_depth.py # deep SSA liveness, join decisions, formatting and exact fuel python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance python3 tests/hosted/source_repair_advice.py # contextual syntax/cast/array-call advice and CLI/package parity python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index fd00adb..34dcaa2 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -590,6 +590,17 @@ are informational, not an efficiency gate. Full block/if checks still abort at Phase 6 stay open. Q-062 separately logs a preserved grouped-statement gap. +The [pruned-SSA liveness increment](source-expression-depth-audit.md#pruned-ssa-liveness-continuations) +removes confirmed read/assignment/After native recursion, preserving first-use +kills, loop steps, sibling gates, rest-frame order and pruned join sets. Host +OOM now propagates instead of the former select fallback's silent read fact. +Exact ordinary conformance coverage, frozen public parity and the full 418-call +source liveness CLI suite pass through 65,536 scalar wrappers; nested blocks +still abort later in `blockBodyWant`/`expr`. Final expanded units pass (332/332). +Direct AST tests and scoped Claude reviews do not establish arbitrary control +lowering or the performance of repeated nested-loop rescans. Q-061, Q-060 full +GC validation and Phase 6 remain open; no semantic or accepted-depth change. + ## Q-062 — Parenthesized block constructs without a statement terminator **Open; existing source-parser behavior, not a new rule.** Spec 15 §4 makes diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 1691239..ce6a71b 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -1242,6 +1242,38 @@ at 1,024 nested block/if levels in `blockBodyWant`/`ifExpr`, with empty stdout. Lowering/control/liveness, Q-060 full GC validation and Phase 6 exit gates stay open. +## Pruned-SSA liveness continuations + +At HEAD `b2c5510`, 16/256/1,024 unary wrappers around a later read or a nested assignment join check successfully, but 16,384 wrappers abort without diagnostic JSON in `exprReads` or `After.expr`. Separate nested-block assignment/read probes also abort in `exprAssigns`/`blockAssigns` and `exprReads`/`blockReads`; some lower-depth probes already reach recursive control lowering. The new shared read/assign/After dispatcher removes that AST recursion. Root regions, loop steps, first-use kills and innermost-first rest frames retain their former rules. + +The read and assignment child tables remain deliberately different. After captures sibling exclusion after if conditions, match scrutinees and select headers; endpoints retain their original per-arm ordering. A newly encountered loop construct resumes the former full-loop read scan in the same dispatcher, then restores the pending parent's mode. Position-only span comparison, including cross-file equal positions, is preserved. Metadata belongs to one caller allocator per reused Lowerer workspace. Queries clear pending entries on success and error; host OOM propagates and never manufactures a read/assignment fact, a source diagnostic or public partial AIR. The former implicit page-allocator/select-body flattening and its silent `true` on OOM are removed. Caller-arena buffers retain arena lifetime. + +Invariant: pruned SSA carries only mutable SSA bindings that may be assigned inside a region and read later (or on a loop back edge); the existing source/verifier ownership and loan rules still validate the resulting AIR. No verifier/runtime rule, ownership/concurrency policy, syntax, AIR format/feature, code, bundle or acceptance limit changes. Valid branch joins and joins before a straight-line kill are exercised through complete source/AIR execution; existing lifetime/CFG rejection twins constrain borrow/cancellation/source-position behavior. + +Independent tests copy the entire former family, including the outer rest-frame walk; AST parsing and span comparison helpers remain shared. Every shallow AST span, missing spans and equal positions with different provenance are queried with both seen states. Added root-region/step comparisons and 1,000 three-frame combinations cover shared current/current-expression seen, fresh state per frame, kills before backedges and innermost priority. Multi-statement/body/tail and loops inside match/select/if branches cover mode restoration. Additional 32,768-level groups put competing reads in later siblings and cancellation, with a false innermost loop rescan; exact false/seen and pre-seen true assertions distinguish exclusion from ordinary reads. Deep direct queries exercise 32,768 unary, binary-left/right, block, if/else-if, match, call, while, lock, select and mixed levels; a 65,536-element sequence uses one lazy cursor. Direct-heap and arena-backed per-call failure sweeps cover recovering/sticky failures, grown scratch, reuse after successful and recovering-OOM queries, and release; public lower sweeps cover both accepted and rejected modules. + +Deep loop After queries can still perform repeated subtree scans (quadratic worst case), as in the old implementation. The full-depth missing-read loop fixtures deliberately use an absent construct, so they do not establish acceptable performance for that path. No arbitrary-depth control lowering or performance bound is claimed. + +Build/format, all 1,793 ordinary conformance cases with exact unique current +coverage, frozen public check/lower byte parity (1,423/506), lifetime (188), +CFG provenance (146), independent-error (234) and repair-advice (299) checks +pass. The complete new `source_liveness_depth.py` suite passes 418 CLI calls: +read/After joins and later kills, both branch outcomes, check/AIR/formatter +fixed points through 65,536, exact unknown-name diagnostics across public +commands and formatted positions, and source/AIR/hosted runtime plus precise +fuel boundaries through 1,024. These do not establish arbitrary control +lowering depth. Final expanded units pass (332/332). + +Claude's read-only core, expanded and final test reviews found no production divergence; +their frame/root/group/heap/retry coverage suggestions are addressed by the +added tests. They ran no builds or tests. Earlier failed fixture extraction +assumed every control root was a statement; the corrected test also handles a +tail expression. Earlier logs are historical checkpoints; the final expanded run records +11/11 successful build steps, 332/332 passed tests and terminal exit 0. The +Zig stderr-warning footer alone does not classify an execution outcome. + +The repaired scalar probes reach later control callbacks on nested-block inputs: full checking still aborts in `blockBodyWant`/`expr`, independently of these now iterative queries. Shared block/statement/if/match lowering, other remaining callbacks, Q-060 full per-step GC validation and Phase 6 exit gates remain open. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -1257,7 +1289,7 @@ includes confirmed block/if lowerer failures and inspection-only risks: |---|---| | Parser block/statement/condition and if/match/select expression entry | Shared control/expression continuations are repaired above. Historical parser aborts no longer describe the candidate; parser-only deep coverage does not prove downstream AST traversal. | | 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. | +| Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, region/match/select helpers) | Shared iterative queries are repaired above; 32,768-level direct AST and 65,536-level scalar-wrapper CLI checks constrain them. Repeated nested-loop rescans retain quadratic worst-case work; that performance scope and arbitrary control lowering are not closed by this increment. | The formatter's expression-marking traversal already uses a worklist, as inspected and exercised by deep syntax-only probes. This inventory does not diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index a1d3e9e..1523ac3 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -856,3 +856,22 @@ Full block/if checking at 1,024 now reaches a confirmed lowerer stack failure. Q-062 logs the independently reproduced existing parenthesized-statement boundary discrepancy. Q-061 lowering/control/liveness, Q-060 full per-step GC validation and Phase 6 exit gates remain open. + +### Pruned-SSA liveness depth increment + +The [liveness increment](../design/source-expression-depth-audit.md#pruned-ssa-liveness-continuations) +replaces recursive read/assign/After walks with one reused allocator-explicit +workspace, preserving join sets, kills, sibling exclusion, loop scans, spans +and rest frames. Host OOM does not become a liveness fact or diagnostic. +Spec, verifier/runtime, AIR/features, syntax, bundles and depth limits stay +unchanged. + +Build/format, exact ordinary conformance coverage (1,793), frozen public +check/lower parity (1,423/506), lifetime/CFG/independent-error/advice suites and +418 new CLI calls pass, including original/formatted AIR through 65,536 and +runtime/fuel through 1,024. Final expanded units pass (332/332). +Scoped read-only Claude reviews found no production divergence and ran no +tests. Deep direct-query tests are distinguished from full control lowering; +repeated nested-loop scans retain a quadratic worst case. Nested-block checks +still fail in `blockBodyWant`/`expr`: shared control lowering, other callbacks, +Q-060 full per-step GC and Phase 6 exit review remain open. diff --git a/src/frontend/liveness.zig b/src/frontend/liveness.zig new file mode 100644 index 0000000..1fac245 --- /dev/null +++ b/src/frontend/liveness.zig @@ -0,0 +1,407 @@ +//! Pruned-SSA source queries (spec 15 §4). Borrowed AST cursors preserve +//! short-circuit order without native AST recursion. Scratch is reused across +//! queries; host OOM is an error, never a fabricated read/assignment fact. +const std = @import("std"); +const ast = @import("ast.zig"); +const Allocator = std.mem.Allocator; +const Span = ast.Span; + +pub const Loop = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 }; +pub const Region = union(enum) { + loop: Loop, + @"if": ast.If, + match: ast.Match, + lock: struct { ast.Block, ast.Block }, + select: ast.Select, + pub fn assigns(r: Region, a: Allocator, workspace: *Workspace, name: []const u8) Allocator.Error!bool { + return workspace.assigns(a, .{ .region = r }, name); + } +}; +pub const Use = enum { read, kill, none }; +pub const Root = union(enum) { expr: ast.Expr, stmt: ast.Stmt, block: ast.Block, loop: Loop, region: Region }; +pub const After = struct { + name: []const u8, + construct: Span, + seen: bool = false, + 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); + } + 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); + } +}; + +fn spanEq(a: Span, b: Span) bool { + // Preserve the former position-only comparison, including across files. + return a.start.line == b.start.line and a.start.col == b.start.col and a.end.line == b.end.line and a.end.col == b.end.col; +} +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +/// A workspace belongs to one allocator; every query and deinit uses that +/// same allocator. Lowerer owns one workspace for its entire arena lifetime. +pub const Workspace = struct { + const Mode = enum { read, assign, after }; + const ArmCursor = struct { arms: []const ast.Arm, cut_on_seen: bool = false }; + const SelectCursor = struct { sel: ast.Select, at: usize = 0, body: usize = 0, cut_on_seen: bool = false }; + const Entry = union(enum) { + expr: ast.Expr, + stmt: ast.Stmt, + block: ast.Block, + loop: Loop, + region: Region, + exprs: []const ast.Expr, + stmts: []const ast.Stmt, + fields: []const ast.FieldInit, + conditional: ast.If, + if_then: ast.If, + if_else: struct { branch: ?ast.Else, cut_on_seen: bool }, + match: ast.Match, + match_arms: []const ast.Arm, + arms: ArmCursor, + select: ast.Select, + select_headers: SelectCursor, + select_reads: SelectCursor, + select_bodies: SelectCursor, + loop_back: struct { loop: Loop, was_seen: bool }, + }; + const Work = struct { mode: Mode, entry: Entry }; + work: std.ArrayList(Work) = .empty, + + /// Same allocator as queries. Arena-backed buffers retain arena lifetime. + pub fn deinit(self: *Workspace, a: Allocator) void { + self.work.deinit(a); + } + pub fn reads(self: *Workspace, a: Allocator, root: Root, name: []const u8, skip: ?Span) Allocator.Error!bool { + return self.query(a, .read, root, name, skip, null); + } + pub fn assigns(self: *Workspace, a: Allocator, root: Root, name: []const u8) Allocator.Error!bool { + return self.query(a, .assign, root, name, null, null); + } + /// Only a straight-line whole-variable assignment kills the old value. + pub fn firstUse(self: *Workspace, a: Allocator, stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) Allocator.Error!Use { + for (stmts) |st| { + if (st.kind == .assign and st.kind.assign.place.kind == .name and eq(st.kind.assign.place.kind.name, name)) { + return if (try self.reads(a, .{ .expr = st.kind.assign.e }, name, null)) .read else .kill; + } + if (try self.reads(a, .{ .stmt = st }, name, null)) return .read; + } + if (tail) |t| if (try self.reads(a, .{ .expr = t.* }, name, null)) return .read; + return .none; + } + fn push(self: *Workspace, a: Allocator, mode: Mode, entry: Entry) Allocator.Error!void { + try self.work.append(a, .{ .mode = mode, .entry = entry }); + } + fn query(self: *Workspace, a: Allocator, mode: Mode, root: Root, name: []const u8, skip: ?Span, after: ?*After) Allocator.Error!bool { + std.debug.assert(self.work.items.len == 0); + defer self.work.items.len = 0; + var current: Work = .{ .mode = mode, .entry = switch (root) { + .expr => |x| .{ .expr = x }, + .stmt => |x| .{ .stmt = x }, + .block => |x| .{ .block = x }, + .loop => |x| .{ .loop = x }, + .region => |x| .{ .region = x }, + } }; + scan: while (true) { + const m = current.mode; + switch (current.entry) { + .expr => |e| { + if (m == .read) { + if (skip) |sk| if (spanEq(e.span, sk)) { + current = self.work.pop() orelse return false; + continue :scan; + }; + } + if (m == .after and !after.?.seen and spanEq(e.span, after.?.construct)) { + 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 => {}, + .neg, .not, .deref, .or_trap => |x| { + current.entry = .{ .expr = x.* }; + continue :scan; + }, + .borrow => |x| if (m != .assign) { + current.entry = .{ .expr = x.place.* }; + continue :scan; + }, + .binary => |x| { + try self.push(a, m, .{ .expr = x.r.* }); + current.entry = .{ .expr = x.l.* }; + continue :scan; + }, + .cast => |x| { + current.entry = .{ .expr = x.e.* }; + continue :scan; + }, + .call => |x| { + if (m != .assign and x.args.len != 0) try self.push(a, m, .{ .exprs = x.args }); + current.entry = if (m == .assign) .{ .exprs = x.args } else .{ .expr = x.callee.* }; + continue :scan; + }, + .field => |x| { + current.entry = .{ .expr = x.e.* }; + continue :scan; + }, + .index => |x| { + if (x.hi) |h| try self.push(a, m, .{ .expr = h.* }); + try self.push(a, m, .{ .expr = x.lo.* }); + current.entry = .{ .expr = x.e.* }; + continue :scan; + }, + .struct_lit => |x| { + current.entry = .{ .fields = x.fields }; + continue :scan; + }, + .array_rep => |x| { + current.entry = .{ .expr = x.e.* }; + continue :scan; + }, + .array_list => |xs| { + current.entry = .{ .exprs = xs }; + continue :scan; + }, + .if_expr => |x| { + current.entry = .{ .conditional = x.* }; + continue :scan; + }, + .match_expr => |x| { + current.entry = .{ .match = x.* }; + continue :scan; + }, + .block => |b| { + current.entry = .{ .block = b.* }; + continue :scan; + }, + } + }, + .stmt => |st| { + if (m == .after and !after.?.seen and spanEq(st.span, after.?.construct)) { + after.?.seen = true; + current = self.work.pop() orelse return false; + continue :scan; + } + switch (st.kind) { + .let => |x| { + current.entry = .{ .expr = x.e }; + continue :scan; + }, + .@"var" => |x| if (x.init) |e| { + current.entry = .{ .expr = e }; + continue :scan; + }, + .assign => |x| { + if (m == .assign and x.place.kind == .name and eq(x.place.kind.name, name)) return true; + if (m != .assign and x.place.kind != .name) try self.push(a, m, .{ .expr = x.place }); + current.entry = .{ .expr = x.e }; + continue :scan; + }, + .borrow => |x| { + current.entry = .{ .expr = x.place }; + continue :scan; + }, + .@"return" => |e| if (e) |x| { + current.entry = .{ .expr = x }; + continue :scan; + }, + .expr => |e| { + current.entry = .{ .expr = e }; + continue :scan; + }, + .@"while" => |x| { + current.entry = .{ .loop = .{ .cond = x.cond, .body = x.body, .step = null } }; + continue :scan; + }, + .@"for" => |x| { + if (m == .assign) { + if (eq(x.name, name)) return true; + current.entry = .{ .block = x.body }; + } else { + try self.push(a, m, if (m == .after) .{ .loop = .{ .cond = null, .body = x.body, .step = x.name } } else .{ .block = x.body }); + try self.push(a, m, .{ .expr = x.hi }); + current.entry = .{ .expr = x.lo }; + } + continue :scan; + }, + .loop => |b| { + current.entry = .{ .loop = .{ .cond = null, .body = b, .step = null } }; + continue :scan; + }, + .shield => |b| { + current.entry = .{ .block = b }; + continue :scan; + }, + .scope => |x| { + current.entry = .{ .block = x.body }; + continue :scan; + }, + .lock => |x| { + try self.push(a, m, .{ .block = x.cancelled }); + if (m == .assign) current.entry = .{ .block = x.body } else { + try self.push(a, m, .{ .block = x.body }); + current.entry = .{ .expr = x.place }; + } + continue :scan; + }, + .select => |x| { + current.entry = .{ .select = x }; + continue :scan; + }, + .@"break", .@"continue", .trap => {}, + } + }, + .block => |b| { + if (b.stmts.len == 0) { + if (b.tail) |t| { + current.entry = .{ .expr = t.* }; + continue :scan; + } + } else { + if (b.tail) |t| try self.push(a, m, .{ .expr = t.* }); + current.entry = .{ .stmts = b.stmts }; + continue :scan; + } + }, + .exprs => |xs| if (xs.len != 0) { + if (xs.len > 1) try self.push(a, m, .{ .exprs = xs[1..] }); + current.entry = .{ .expr = xs[0] }; + continue :scan; + }, + .stmts => |xs| if (xs.len != 0) { + if (xs.len > 1) try self.push(a, m, .{ .stmts = xs[1..] }); + current.entry = .{ .stmt = xs[0] }; + continue :scan; + }, + .fields => |xs| if (xs.len != 0) { + if (xs.len > 1) try self.push(a, m, .{ .fields = xs[1..] }); + current.entry = .{ .expr = xs[0].e }; + continue :scan; + }, + .conditional => |x| { + try self.push(a, m, .{ .if_then = x }); + current.entry = .{ .expr = x.cond }; + continue :scan; + }, + .if_then => |x| { + try self.push(a, m, .{ .if_else = .{ .branch = x.@"else", .cut_on_seen = m == .after and !after.?.seen } }); + current.entry = .{ .block = x.then }; + continue :scan; + }, + .if_else => |x| if (!(x.cut_on_seen and after.?.seen)) { + if (x.branch) |els| { + current.entry = switch (els) { + .block => |b| .{ .block = b }, + .@"if" => |inner| .{ .conditional = inner.* }, + }; + continue :scan; + } + }, + .match => |x| { + try self.push(a, m, .{ .match_arms = x.arms }); + current.entry = .{ .expr = x.scrutinee }; + continue :scan; + }, + .match_arms => |arms| { + current.entry = .{ .arms = .{ .arms = arms, .cut_on_seen = m == .after and !after.?.seen } }; + continue :scan; + }, + .arms => |cursor| if (cursor.arms.len != 0 and !(cursor.cut_on_seen and after.?.seen)) { + const arm = cursor.arms[0]; + if (m == .assign and arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |bn| { + if (eq(bn, name)) return true; + }; + if (cursor.arms.len > 1) try self.push(a, m, .{ .arms = .{ .arms = cursor.arms[1..], .cut_on_seen = cursor.cut_on_seen } }); + current.entry = .{ .expr = arm.body }; + continue :scan; + }, + .select => |sel| { + current.entry = if (m == .read) .{ .select_reads = .{ .sel = sel } } else if (m == .assign) .{ .select_bodies = .{ .sel = sel } } else .{ .select_headers = .{ .sel = sel } }; + continue :scan; + }, + .select_reads => |cursor| { + if (cursor.at < cursor.sel.arms.len) { + const arm = cursor.sel.arms[cursor.at]; + if (eq(arm.endpoint, name)) return true; + try self.push(a, m, .{ .select_reads = .{ .sel = cursor.sel, .at = cursor.at + 1 } }); + if (arm.value) |v| { + if (arm.arms.len != 0) try self.push(a, m, .{ .arms = .{ .arms = arm.arms } }); + current.entry = .{ .expr = v }; + } else current.entry = .{ .arms = .{ .arms = arm.arms } }; + } else current.entry = .{ .expr = cursor.sel.cancelled }; + continue :scan; + }, + .select_headers => |cursor| { + if (cursor.at < cursor.sel.arms.len) { + const arm = cursor.sel.arms[cursor.at]; + if (after.?.seen and eq(arm.endpoint, name)) return true; + current.entry = .{ .select_headers = .{ .sel = cursor.sel, .at = cursor.at + 1 } }; + if (arm.value) |v| { + try self.push(a, m, current.entry); + current.entry = .{ .expr = v }; + } + } else current.entry = .{ .select_bodies = .{ .sel = cursor.sel, .cut_on_seen = !after.?.seen } }; + continue :scan; + }, + .select_bodies => |cursor| if (!(cursor.cut_on_seen and after.?.seen)) { + if (cursor.at == cursor.sel.arms.len) { + if (m == .assign) for (cursor.sel.cancelled_binds) |bn| { + if (eq(bn, name)) return true; + }; + current.entry = .{ .expr = cursor.sel.cancelled }; + continue :scan; + } + const arms = cursor.sel.arms[cursor.at].arms; + if (cursor.body == arms.len) { + var next = cursor; + next.at += 1; + next.body = 0; + current.entry = .{ .select_bodies = next }; + continue :scan; + } + const arm = arms[cursor.body]; + if (m == .assign and arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |bn| { + if (eq(bn, name)) return true; + }; + var next = cursor; + next.body += 1; + try self.push(a, m, .{ .select_bodies = next }); + current.entry = .{ .expr = arm.body }; + continue :scan; + }, + .loop => |lp| { + if (m != .after) { + if (lp.step) |step| if (eq(step, name)) return true; + } else try self.push(a, m, .{ .loop_back = .{ .loop = lp, .was_seen = after.?.seen } }); + if (lp.cond) |cond| { + try self.push(a, m, .{ .block = lp.body }); + current.entry = .{ .expr = cond }; + } else current.entry = .{ .block = lp.body }; + continue :scan; + }, + .loop_back => |frame| if (!frame.was_seen and after.?.seen) { + // Resume the old full-loop read query in this same driver. + current = .{ .mode = .read, .entry = .{ .loop = frame.loop } }; + continue :scan; + }, + .region => |region| { + current.entry = switch (region) { + .loop => |lp| .{ .loop = lp }, + .@"if" => |x| .{ .conditional = x }, + .match => |x| .{ .match = x }, + .select => |x| .{ .select = x }, + .lock => |b| blk: { + try self.push(a, m, .{ .block = b[1] }); + break :blk .{ .block = b[0] }; + }, + }; + continue :scan; + }, + } + current = self.work.pop() orelse return false; + } + } +}; diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index bbc2d96..0c064e3 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -26,6 +26,7 @@ const std = @import("std"); const ast = @import("ast.zig"); +const liveness = @import("liveness.zig"); const parse_mod = @import("parse.zig"); const authority = @import("../air/authority.zig"); const features_mod = @import("../air/features.zig"); @@ -195,6 +196,7 @@ const Error = error{ Lower, Unimplemented, OutOfMemory }; pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result { var l: Lowerer = .{ .arena = arena, .m = m }; + defer l.live_queries.deinit(arena); l.run() catch |e| switch (e) { error.Lower => return if (l.problems.items.len > 1) .{ .errors = l.problems.items } else .{ .err = if (l.problems.items.len == 1) l.problems.items[0] else l.problem.? }, error.Unimplemented => return .{ .unimplemented = l.unimpl.? }, @@ -283,7 +285,7 @@ const Rest = struct { loop: ?LoopAst = null, }; -const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 }; +const LoopAst = liveness.Loop; const FnSig = struct { params: []const Ty, ret: Ty, from: ?usize = null, air_name: []const u8, display_name: []const u8 }; @@ -322,6 +324,8 @@ const Lowerer = struct { /// Statements still to be lowered in each enclosing block (innermost /// last), for inferring the type of an untyped `let` from its uses. rest: std.ArrayList(Rest) = .empty, + /// Reused AST-query scratch; every query drains it on success or error. + live_queries: liveness.Workspace = .{}, /// Set by a loop just before lowering its body: the body's `Rest` frame. pending_loop: ?LoopAst = null, /// Set by `scope`, `shield` and `lock` just before lowering a body: @@ -1087,7 +1091,7 @@ const Lowerer = struct { var out: std.ArrayList(usize) = .empty; for (try l.carried(depth)) |i| { const n = l.bindings.items[i].name; - if (region.assigns(n) and l.liveAfter(n, construct)) try out.append(l.arena, i); + if (try region.assigns(l.arena, &l.live_queries, n) and try l.liveAfter(n, construct)) try out.append(l.arena, i); } return out.items; } @@ -1099,7 +1103,7 @@ const Lowerer = struct { const region: Region = .{ .loop = lp }; for (try l.carried(depth)) |i| { const n = l.bindings.items[i].name; - if (region.assigns(n) and (loopReads(lp, n) or l.liveAfter(n, construct))) try out.append(l.arena, i); + if (try region.assigns(l.arena, &l.live_queries, n) and (try l.live_queries.reads(l.arena, .{ .loop = lp }, n, null) or try l.liveAfter(n, construct))) try out.append(l.arena, i); } return out.items; } @@ -1108,21 +1112,21 @@ const Lowerer = struct { /// `construct`. Conservative: any read on any later path counts; only a /// whole-variable assignment in straight-line code before any read ends /// the variable's life. - fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) bool { + fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) Allocator.Error!bool { 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 }; - if (fr.current) |c| if (w.stmt(c)) return true; - if (fr.current_expr) |ce| if (w.expr(ce.*)) return true; - switch (firstUse(fr.stmts, fr.tail, name)) { + 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)) { .read => return true, .kill => return false, .none => {}, } - if (fr.loop) |lp| if (loopReads(lp, name)) return true; + if (fr.loop) |lp| if (try l.live_queries.reads(l.arena, .{ .loop = lp }, name, null)) return true; } return false; } @@ -4607,335 +4611,8 @@ fn spanEq(a: Span, b: Span) bool { return a.start.line == b.start.line and a.start.col == b.start.col and a.end.line == b.end.line and a.end.col == b.end.col; } -const Use = enum { read, kill, none }; - -/// The first use of `name` in statements executed in order: a read, a -/// whole-variable assignment that does not read it (`name = e;`), or none. -fn firstUse(stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) Use { - for (stmts) |st| { - if (st.kind == .assign and st.kind.assign.place.kind == .name and std.mem.eql(u8, st.kind.assign.place.kind.name, name)) { - if (exprReads(st.kind.assign.e, name, null)) return .read; - return .kill; - } - if (stmtReads(st, name, null)) return .read; - } - if (tail) |t| if (exprReads(t.*, name, null)) return .read; - return .none; -} - -fn loopReads(lp: LoopAst, name: []const u8) bool { - if (lp.step) |st| if (std.mem.eql(u8, st, name)) return true; - if (lp.cond) |c| if (exprReads(c, name, null)) return true; - return blockReads(lp.body, name, null); -} - -fn blockReads(b: ast.Block, name: []const u8, skip: ?Span) bool { - for (b.stmts) |st| if (stmtReads(st, name, skip)) return true; - if (b.tail) |t| if (exprReads(t.*, name, skip)) return true; - return false; -} - -/// Whether the statement mentions `name` other than as the target of a -/// whole-variable assignment. `skip`: a construct whose own reads happen -/// before the join being decided. -fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool { - return switch (st.kind) { - .let => |x| exprReads(x.e, name, skip), - .@"var" => |x| if (x.init) |e| exprReads(e, name, skip) else false, - .assign => |x| exprReads(x.e, name, skip) or (x.place.kind != .name and exprReads(x.place, name, skip)), - .borrow => |x| exprReads(x.place, name, skip), - .@"return" => |e| if (e) |x| exprReads(x, name, skip) else false, - .expr => |e| exprReads(e, name, skip), - .@"while" => |x| exprReads(x.cond, name, skip) or blockReads(x.body, name, skip), - .@"for" => |x| exprReads(x.lo, name, skip) or exprReads(x.hi, name, skip) or blockReads(x.body, name, skip), - .loop, .shield => |b| blockReads(b, name, skip), - .scope => |x| blockReads(x.body, name, skip), - .lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip), - .select => |x| selectReads(x, name, skip), - .@"break", .@"continue", .trap => false, - }; -} - -fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool { - if (skip) |sk| if (spanEq(e.span, sk)) return false; - return switch (e.kind) { - .name => |n| std.mem.eql(u8, n, name), - .move => |n| std.mem.eql(u8, n, name), - .int, .boolean, .bytes, .variant, .specialize => false, - .neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip), - .borrow => |x| exprReads(x.place.*, name, skip), - .binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip), - .cast => |x| exprReads(x.e.*, name, skip), - .call => |x| blk: { - if (exprReads(x.callee.*, name, skip)) break :blk true; - for (x.args) |a| if (exprReads(a, name, skip)) break :blk true; - break :blk false; - }, - .field => |x| exprReads(x.e.*, name, skip), - .index => |x| exprReads(x.e.*, name, skip) or exprReads(x.lo.*, name, skip) or (if (x.hi) |h| exprReads(h.*, name, skip) else false), - .struct_lit => |x| blk: { - for (x.fields) |f| if (exprReads(f.e, name, skip)) break :blk true; - break :blk false; - }, - .array_rep => |x| exprReads(x.e.*, name, skip), - .array_list => |xs| for (xs) |x| { - if (exprReads(x, name, skip)) break true; - } else false, - .if_expr => |x| ifReads(x.*, name, skip), - .match_expr => |x| blk: { - if (exprReads(x.scrutinee, name, skip)) break :blk true; - for (x.arms) |a| if (exprReads(a.body, name, skip)) break :blk true; - break :blk false; - }, - .block => |b| blockReads(b.*, name, skip), - }; -} - -fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool { - for (x.arms) |a| { - if (std.mem.eql(u8, a.endpoint, name)) return true; - if (a.value) |v| if (exprReads(v, name, skip)) return true; - for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true; - } - return exprReads(x.cancelled, name, skip); -} - -fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool { - if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true; - if (x.@"else") |els| return switch (els) { - .block => |b| blockReads(b, name, skip), - .@"if" => |inner| ifReads(inner.*, name, skip), - }; - return false; -} - -/// Reads of `name` after `construct`, in evaluation order, within the -/// statement or expression that contains it. Once the construct is found in -/// one arm of an `if` or `match`, the other arms are not "after" it; once it -/// is found in a loop, the whole loop is (the back edge). -const After = struct { - name: []const u8, - construct: Span, - seen: bool = false, - - fn expr(w: *After, e: ast.Expr) bool { - if (!w.seen and spanEq(e.span, w.construct)) { - w.seen = true; - return false; - } - return switch (e.kind) { - .name, .move => |n| w.seen and std.mem.eql(u8, n, w.name), - .int, .boolean, .bytes, .variant, .specialize => false, - .neg, .not, .deref, .or_trap => |x| w.expr(x.*), - .borrow => |x| w.expr(x.place.*), - .binary => |x| w.expr(x.l.*) or w.expr(x.r.*), - .cast => |x| w.expr(x.e.*), - .call => |x| blk: { - if (w.expr(x.callee.*)) break :blk true; - for (x.args) |a| if (w.expr(a)) break :blk true; - break :blk false; - }, - .field => |x| w.expr(x.e.*), - .index => |x| w.expr(x.e.*) or w.expr(x.lo.*) or (if (x.hi) |h| w.expr(h.*) else false), - .struct_lit => |x| blk: { - for (x.fields) |f| if (w.expr(f.e)) break :blk true; - break :blk false; - }, - .array_rep => |x| w.expr(x.e.*), - .array_list => |xs| for (xs) |x| { - if (w.expr(x)) break true; - } else false, - .if_expr => |x| w.ifExpr(x.*), - .match_expr => |x| blk: { - if (w.expr(x.scrutinee)) break :blk true; - if (w.seen) { - for (x.arms) |a| if (w.expr(a.body)) break :blk true; - break :blk false; - } - for (x.arms) |a| { - const r = w.expr(a.body); - if (w.seen) break :blk r; // found in this arm: siblings are not after it - } - break :blk false; - }, - .block => |b| w.block(b.*), - }; - } - - fn select(w: *After, x: ast.Select) bool { - for (x.arms) |a| { - if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true; - if (a.value) |v| if (w.expr(v)) return true; - } - var bodies: std.ArrayList(ast.Expr) = .empty; - defer bodies.deinit(std.heap.page_allocator); - for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true; - bodies.append(std.heap.page_allocator, x.cancelled) catch return true; - if (w.seen) { - for (bodies.items) |b| if (w.expr(b)) return true; - return false; - } - for (bodies.items) |b| { - const r = w.expr(b); - if (w.seen) return r; - } - return false; - } - - fn ifExpr(w: *After, x: ast.If) bool { - if (w.expr(x.cond)) return true; - if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false); - const r = w.block(x.then); - if (w.seen) return r; - if (x.@"else") |els| return w.elseBranch(els); - return false; - } - - fn elseBranch(w: *After, els: ast.Else) bool { - return switch (els) { - .block => |b| w.block(b), - .@"if" => |inner| w.ifExpr(inner.*), - }; - } - - fn block(w: *After, b: ast.Block) bool { - for (b.stmts) |st| if (w.stmt(st)) return true; - if (b.tail) |t| if (w.expr(t.*)) return true; - return false; - } - - fn loopBody(w: *After, cond: ?ast.Expr, body: ast.Block, step: ?[]const u8) bool { - const was = w.seen; - if (cond) |c| if (w.expr(c)) return true; - const r = w.block(body); - if (r) return true; - // Found inside this loop: everything in it can run again. - if (!was and w.seen) return loopReads(.{ .cond = cond, .body = body, .step = step }, w.name); - return false; - } - - fn stmt(w: *After, st: ast.Stmt) bool { - if (!w.seen and spanEq(st.span, w.construct)) { - w.seen = true; - return false; - } - return switch (st.kind) { - .let => |x| w.expr(x.e), - .@"var" => |x| if (x.init) |e| w.expr(e) else false, - .assign => |x| w.expr(x.e) or (x.place.kind != .name and w.expr(x.place)), - .borrow => |x| w.expr(x.place), - .@"return" => |e| if (e) |x| w.expr(x) else false, - .expr => |e| w.expr(e), - .@"while" => |x| w.loopBody(x.cond, x.body, null), - .@"for" => |x| w.expr(x.lo) or w.expr(x.hi) or w.loopBody(null, x.body, x.name), - .loop => |b| w.loopBody(null, b, null), - .shield => |b| w.block(b), - .scope => |x| w.block(x.body), - .lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled), - .select => |x| w.select(x), - .@"break", .@"continue", .trap => false, - }; - } -}; - -/// The code of a branching construct, for deciding which variables it -/// assigns: a join carries only variables that may change inside. -const Region = union(enum) { - loop: LoopAst, - @"if": ast.If, - match: ast.Match, - lock: struct { ast.Block, ast.Block }, - select: ast.Select, - - fn assigns(r: Region, name: []const u8) bool { - return switch (r) { - .loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name), - .@"if" => |x| ifAssigns(x, name), - .match => |m| matchAssigns(m, name), - .lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name), - .select => |x| selectAssigns(x, name), - }; - } -}; - -/// Whether code assigns variable `name`: `name = e;`, or a pattern of an -/// outcome or `select` edge rebinding it (spec 15 §6). -fn blockAssigns(b: ast.Block, name: []const u8) bool { - for (b.stmts) |st| if (stmtAssigns(st, name)) return true; - if (b.tail) |t| if (exprAssigns(t.*, name)) return true; - return false; -} - -fn stmtAssigns(st: ast.Stmt, name: []const u8) bool { - return switch (st.kind) { - .assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name), - .let => |x| exprAssigns(x.e, name), - .@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false, - .borrow => |x| exprAssigns(x.place, name), - .@"return" => |e| if (e) |x| exprAssigns(x, name) else false, - .expr => |e| exprAssigns(e, name), - .@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name), - .@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name), - .loop, .shield => |b| blockAssigns(b, name), - .scope => |x| blockAssigns(x.body, name), - .lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name), - .select => |x| selectAssigns(x, name), - .@"break", .@"continue", .trap => false, - }; -} - -fn exprAssigns(e: ast.Expr, name: []const u8) bool { - return switch (e.kind) { - .if_expr => |x| ifAssigns(x.*, name), - .match_expr => |x| matchAssigns(x.*, name), - .block => |b| blockAssigns(b.*, name), - .neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name), - .binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name), - .cast => |x| exprAssigns(x.e.*, name), - .call => |x| blk: { - for (x.args) |a| if (exprAssigns(a, name)) break :blk true; - break :blk false; - }, - .struct_lit => |x| blk: { - for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true; - break :blk false; - }, - .field => |x| exprAssigns(x.e.*, name), - .index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false), - .array_rep => |x| exprAssigns(x.e.*, name), - .array_list => |xs| for (xs) |x| { - if (exprAssigns(x, name)) break true; - } else false, - else => false, - }; -} - -fn ifAssigns(x: ast.If, name: []const u8) bool { - if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true; - if (x.@"else") |els| return switch (els) { - .block => |b| blockAssigns(b, name), - .@"if" => |inner| ifAssigns(inner.*, name), - }; - return false; -} - -fn matchAssigns(m: ast.Match, name: []const u8) bool { - if (exprAssigns(m.scrutinee, name)) return true; - for (m.arms) |a| { - if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true; - if (exprAssigns(a.body, name)) return true; - } - return false; -} - -fn selectAssigns(x: ast.Select, name: []const u8) bool { - for (x.arms) |a| for (a.arms) |arm| { - if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true; - if (exprAssigns(arm.body, name)) return true; - }; - for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true; - return exprAssigns(x.cancelled, name); -} +const Region = liveness.Region; +const After = liveness.After; fn localName(full: []const u8, module: []const u8, short: []const u8) bool { return full.len == module.len + 1 + short.len and std.mem.startsWith(u8, full, module) and full[module.len] == '.' and std.mem.eql(u8, full[module.len + 1 ..], short); @@ -7565,6 +7242,7 @@ const QueryAllocationFailure = struct { attempts: usize = 0, fail_at: usize = 0, failed: bool = false, + sticky: bool = false, fn allocator(self: *@This()) Allocator { return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; @@ -7572,7 +7250,7 @@ const QueryAllocationFailure = struct { fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(raw)); self.attempts += 1; - if (!self.failed and self.attempts == self.fail_at + 1) { + if (self.attempts >= self.fail_at + 1 and (self.sticky or !self.failed)) { self.failed = true; return null; } @@ -10069,3 +9747,850 @@ test "public raw place field range lowering OOM stays host error with arena clea } } } + +// Independent frozen pre-repair liveness family; only AST/span helpers are +// shared. Its After.select page allocator is used on shallow successful +// allocations only; new host-OOM behavior is tested separately. +const ReferenceLiveness = struct { + const OldUse = enum { read, kill, none }; + + /// The first use of `name` in statements executed in order: a read, a + /// whole-variable assignment that does not read it (`name = e;`), or none. + fn firstUse(stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) OldUse { + for (stmts) |st| { + if (st.kind == .assign and st.kind.assign.place.kind == .name and std.mem.eql(u8, st.kind.assign.place.kind.name, name)) { + if (exprReads(st.kind.assign.e, name, null)) return .read; + return .kill; + } + if (stmtReads(st, name, null)) return .read; + } + if (tail) |t| if (exprReads(t.*, name, null)) return .read; + return .none; + } + + fn loopReads(lp: LoopAst, name: []const u8) bool { + if (lp.step) |st| if (std.mem.eql(u8, st, name)) return true; + if (lp.cond) |c| if (exprReads(c, name, null)) return true; + return blockReads(lp.body, name, null); + } + + fn blockReads(b: ast.Block, name: []const u8, skip: ?Span) bool { + for (b.stmts) |st| if (stmtReads(st, name, skip)) return true; + if (b.tail) |t| if (exprReads(t.*, name, skip)) return true; + return false; + } + + /// Whether the statement mentions `name` other than as the target of a + /// whole-variable assignment. `skip`: a construct whose own reads happen + /// before the join being decided. + fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool { + return switch (st.kind) { + .let => |x| exprReads(x.e, name, skip), + .@"var" => |x| if (x.init) |e| exprReads(e, name, skip) else false, + .assign => |x| exprReads(x.e, name, skip) or (x.place.kind != .name and exprReads(x.place, name, skip)), + .borrow => |x| exprReads(x.place, name, skip), + .@"return" => |e| if (e) |x| exprReads(x, name, skip) else false, + .expr => |e| exprReads(e, name, skip), + .@"while" => |x| exprReads(x.cond, name, skip) or blockReads(x.body, name, skip), + .@"for" => |x| exprReads(x.lo, name, skip) or exprReads(x.hi, name, skip) or blockReads(x.body, name, skip), + .loop, .shield => |b| blockReads(b, name, skip), + .scope => |x| blockReads(x.body, name, skip), + .lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip), + .select => |x| selectReads(x, name, skip), + .@"break", .@"continue", .trap => false, + }; + } + + fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool { + if (skip) |sk| if (spanEq(e.span, sk)) return false; + return switch (e.kind) { + .name => |n| std.mem.eql(u8, n, name), + .move => |n| std.mem.eql(u8, n, name), + .int, .boolean, .bytes, .variant, .specialize => false, + .neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip), + .borrow => |x| exprReads(x.place.*, name, skip), + .binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip), + .cast => |x| exprReads(x.e.*, name, skip), + .call => |x| blk: { + if (exprReads(x.callee.*, name, skip)) break :blk true; + for (x.args) |a| if (exprReads(a, name, skip)) break :blk true; + break :blk false; + }, + .field => |x| exprReads(x.e.*, name, skip), + .index => |x| exprReads(x.e.*, name, skip) or exprReads(x.lo.*, name, skip) or (if (x.hi) |h| exprReads(h.*, name, skip) else false), + .struct_lit => |x| blk: { + for (x.fields) |f| if (exprReads(f.e, name, skip)) break :blk true; + break :blk false; + }, + .array_rep => |x| exprReads(x.e.*, name, skip), + .array_list => |xs| for (xs) |x| { + if (exprReads(x, name, skip)) break true; + } else false, + .if_expr => |x| ifReads(x.*, name, skip), + .match_expr => |x| blk: { + if (exprReads(x.scrutinee, name, skip)) break :blk true; + for (x.arms) |a| if (exprReads(a.body, name, skip)) break :blk true; + break :blk false; + }, + .block => |b| blockReads(b.*, name, skip), + }; + } + + fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool { + for (x.arms) |a| { + if (std.mem.eql(u8, a.endpoint, name)) return true; + if (a.value) |v| if (exprReads(v, name, skip)) return true; + for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true; + } + return exprReads(x.cancelled, name, skip); + } + + fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool { + if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true; + if (x.@"else") |els| return switch (els) { + .block => |b| blockReads(b, name, skip), + .@"if" => |inner| ifReads(inner.*, name, skip), + }; + return false; + } + + /// Reads of `name` after `construct`, in evaluation order, within the + /// statement or expression that contains it. Once the construct is found in + /// one arm of an `if` or `match`, the other arms are not "after" it; once it + /// is found in a loop, the whole loop is (the back edge). + const OldAfter = struct { + name: []const u8, + construct: Span, + seen: bool = false, + + fn expr(w: *OldAfter, e: ast.Expr) bool { + if (!w.seen and spanEq(e.span, w.construct)) { + w.seen = true; + return false; + } + return switch (e.kind) { + .name, .move => |n| w.seen and std.mem.eql(u8, n, w.name), + .int, .boolean, .bytes, .variant, .specialize => false, + .neg, .not, .deref, .or_trap => |x| w.expr(x.*), + .borrow => |x| w.expr(x.place.*), + .binary => |x| w.expr(x.l.*) or w.expr(x.r.*), + .cast => |x| w.expr(x.e.*), + .call => |x| blk: { + if (w.expr(x.callee.*)) break :blk true; + for (x.args) |a| if (w.expr(a)) break :blk true; + break :blk false; + }, + .field => |x| w.expr(x.e.*), + .index => |x| w.expr(x.e.*) or w.expr(x.lo.*) or (if (x.hi) |h| w.expr(h.*) else false), + .struct_lit => |x| blk: { + for (x.fields) |f| if (w.expr(f.e)) break :blk true; + break :blk false; + }, + .array_rep => |x| w.expr(x.e.*), + .array_list => |xs| for (xs) |x| { + if (w.expr(x)) break true; + } else false, + .if_expr => |x| w.ifExpr(x.*), + .match_expr => |x| blk: { + if (w.expr(x.scrutinee)) break :blk true; + if (w.seen) { + for (x.arms) |a| if (w.expr(a.body)) break :blk true; + break :blk false; + } + for (x.arms) |a| { + const r = w.expr(a.body); + if (w.seen) break :blk r; // found in this arm: siblings are not after it + } + break :blk false; + }, + .block => |b| w.block(b.*), + }; + } + + fn select(w: *OldAfter, x: ast.Select) bool { + for (x.arms) |a| { + if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true; + if (a.value) |v| if (w.expr(v)) return true; + } + var bodies: std.ArrayList(ast.Expr) = .empty; + defer bodies.deinit(std.heap.page_allocator); + for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true; + bodies.append(std.heap.page_allocator, x.cancelled) catch return true; + if (w.seen) { + for (bodies.items) |b| if (w.expr(b)) return true; + return false; + } + for (bodies.items) |b| { + const r = w.expr(b); + if (w.seen) return r; + } + return false; + } + + fn ifExpr(w: *OldAfter, x: ast.If) bool { + if (w.expr(x.cond)) return true; + if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false); + const r = w.block(x.then); + if (w.seen) return r; + if (x.@"else") |els| return w.elseBranch(els); + return false; + } + + fn elseBranch(w: *OldAfter, els: ast.Else) bool { + return switch (els) { + .block => |b| w.block(b), + .@"if" => |inner| w.ifExpr(inner.*), + }; + } + + fn block(w: *OldAfter, b: ast.Block) bool { + for (b.stmts) |st| if (w.stmt(st)) return true; + if (b.tail) |t| if (w.expr(t.*)) return true; + return false; + } + + fn loopBody(w: *OldAfter, cond: ?ast.Expr, body: ast.Block, step: ?[]const u8) bool { + const was = w.seen; + if (cond) |c| if (w.expr(c)) return true; + const r = w.block(body); + if (r) return true; + // Found inside this loop: everything in it can run again. + if (!was and w.seen) return loopReads(.{ .cond = cond, .body = body, .step = step }, w.name); + return false; + } + + fn stmt(w: *OldAfter, st: ast.Stmt) bool { + if (!w.seen and spanEq(st.span, w.construct)) { + w.seen = true; + return false; + } + return switch (st.kind) { + .let => |x| w.expr(x.e), + .@"var" => |x| if (x.init) |e| w.expr(e) else false, + .assign => |x| w.expr(x.e) or (x.place.kind != .name and w.expr(x.place)), + .borrow => |x| w.expr(x.place), + .@"return" => |e| if (e) |x| w.expr(x) else false, + .expr => |e| w.expr(e), + .@"while" => |x| w.loopBody(x.cond, x.body, null), + .@"for" => |x| w.expr(x.lo) or w.expr(x.hi) or w.loopBody(null, x.body, x.name), + .loop => |b| w.loopBody(null, b, null), + .shield => |b| w.block(b), + .scope => |x| w.block(x.body), + .lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled), + .select => |x| w.select(x), + .@"break", .@"continue", .trap => false, + }; + } + }; + + /// The code of a branching construct, for deciding which variables it + /// assigns: a join carries only variables that may change inside. + const OldRegion = union(enum) { + loop: LoopAst, + @"if": ast.If, + match: ast.Match, + lock: struct { ast.Block, ast.Block }, + select: ast.Select, + + fn assigns(r: OldRegion, name: []const u8) bool { + return switch (r) { + .loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name), + .@"if" => |x| ifAssigns(x, name), + .match => |m| matchAssigns(m, name), + .lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name), + .select => |x| selectAssigns(x, name), + }; + } + }; + + /// Whether code assigns variable `name`: `name = e;`, or a pattern of an + /// outcome or `select` edge rebinding it (spec 15 §6). + fn blockAssigns(b: ast.Block, name: []const u8) bool { + for (b.stmts) |st| if (stmtAssigns(st, name)) return true; + if (b.tail) |t| if (exprAssigns(t.*, name)) return true; + return false; + } + + fn stmtAssigns(st: ast.Stmt, name: []const u8) bool { + return switch (st.kind) { + .assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name), + .let => |x| exprAssigns(x.e, name), + .@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false, + .borrow => |x| exprAssigns(x.place, name), + .@"return" => |e| if (e) |x| exprAssigns(x, name) else false, + .expr => |e| exprAssigns(e, name), + .@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name), + .@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name), + .loop, .shield => |b| blockAssigns(b, name), + .scope => |x| blockAssigns(x.body, name), + .lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name), + .select => |x| selectAssigns(x, name), + .@"break", .@"continue", .trap => false, + }; + } + + fn exprAssigns(e: ast.Expr, name: []const u8) bool { + return switch (e.kind) { + .if_expr => |x| ifAssigns(x.*, name), + .match_expr => |x| matchAssigns(x.*, name), + .block => |b| blockAssigns(b.*, name), + .neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name), + .binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name), + .cast => |x| exprAssigns(x.e.*, name), + .call => |x| blk: { + for (x.args) |a| if (exprAssigns(a, name)) break :blk true; + break :blk false; + }, + .struct_lit => |x| blk: { + for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true; + break :blk false; + }, + .field => |x| exprAssigns(x.e.*, name), + .index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false), + .array_rep => |x| exprAssigns(x.e.*, name), + .array_list => |xs| for (xs) |x| { + if (exprAssigns(x, name)) break true; + } else false, + else => false, + }; + } + + fn ifAssigns(x: ast.If, name: []const u8) bool { + if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true; + if (x.@"else") |els| return switch (els) { + .block => |b| blockAssigns(b, name), + .@"if" => |inner| ifAssigns(inner.*, name), + }; + return false; + } + + fn matchAssigns(m: ast.Match, name: []const u8) bool { + if (exprAssigns(m.scrutinee, name)) return true; + for (m.arms) |a| { + if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true; + if (exprAssigns(a.body, name)) return true; + } + return false; + } + + fn selectAssigns(x: ast.Select, name: []const u8) bool { + for (x.arms) |a| for (a.arms) |arm| { + if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true; + if (exprAssigns(arm.body, name)) return true; + }; + for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true; + return exprAssigns(x.cancelled, name); + } + + fn liveAfter(l: *const Lowerer, name: []const u8, construct: Span) bool { + 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: OldAfter = .{ .name = name, .construct = construct }; + if (fr.current) |c| if (w.stmt(c)) return true; + if (fr.current_expr) |ce| if (w.expr(ce.*)) return true; + switch (firstUse(fr.stmts, fr.tail, name)) { + .read => return true, + .kill => return false, + .none => {}, + } + if (fr.loop) |lp| if (loopReads(lp, name)) return true; + } + return false; + } +}; + +fn compareLivenessBlock(a: Allocator, b: ast.Block) !void { + var workspace: liveness.Workspace = .{}; + defer workspace.deinit(a); + const names = [_][]const u8{ "x", "v", "rx", "tx", "i", "s", "missing" }; + // Every AST span is a possible construct or skip span, plus absent and + // duplicate-provenance positions. Only shallow fixtures use this collector. + var spans: std.ArrayList(Span) = .empty; + try collectQuerySpans(a, b, &spans); + if (spans.items.len != 0) { + var twin = spans.items[0]; + twin.file = "another.aji"; + twin.namespace = "other"; + try spans.append(a, twin); + } + try spans.append(a, .{ .start = .{ .line = 999, .col = 1 }, .end = .{ .line = 999, .col = 2 } }); + for (names) |name| { + try std.testing.expectEqual(ReferenceLiveness.blockReads(b, name, null), try workspace.reads(a, .{ .block = b }, name, null)); + try std.testing.expectEqual(ReferenceLiveness.blockAssigns(b, name), try workspace.assigns(a, .{ .block = b }, name)); + try std.testing.expectEqualStrings(@tagName(ReferenceLiveness.firstUse(b.stmts, b.tail, name)), @tagName(try workspace.firstUse(a, b.stmts, b.tail, name))); + for (spans.items) |span| { + try std.testing.expectEqual(ReferenceLiveness.blockReads(b, name, span), try workspace.reads(a, .{ .block = b }, name, span)); + for ([_]bool{ false, true }) |seen| { + var old: ReferenceLiveness.OldAfter = .{ .name = name, .construct = span, .seen = seen }; + var current: After = .{ .name = name, .construct = span, .seen = seen }; + for (b.stmts) |stmt| { + try std.testing.expectEqual(old.stmt(stmt), try current.stmt(a, &workspace, stmt)); + try std.testing.expectEqual(old.seen, current.seen); + } + if (b.tail) |tail| { + try std.testing.expectEqual(old.expr(tail.*), try current.expr(a, &workspace, tail.*)); + try std.testing.expectEqual(old.seen, current.seen); + } + } + } + } + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); +} + +fn compareLivenessRegion(a: Allocator, region: Region) !void { + var workspace: liveness.Workspace = .{}; + defer workspace.deinit(a); + const old: ReferenceLiveness.OldRegion = switch (region) { + .loop => |x| .{ .loop = x }, + .@"if" => |x| .{ .@"if" = x }, + .match => |x| .{ .match = x }, + .lock => |x| .{ .lock = .{ x[0], x[1] } }, + .select => |x| .{ .select = x }, + }; + for ([_][]const u8{ "x", "v", "i", "rx", "tx", "missing" }) |name| { + try std.testing.expectEqual(old.assigns(name), try region.assigns(a, &workspace, name)); + if (region == .loop) try std.testing.expectEqual(ReferenceLiveness.loopReads(region.loop, name), try workspace.reads(a, .{ .loop = region.loop }, name, null)); + } +} + +test "liveness region roots preserve assignments and explicit loop steps" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const texts = [_][]const u8{ + "while x { v = x; }", "for i in v..x { x = v; }", "loop { x = v; }", + "if x { v = x; } else if v { x = v; } else { f(); }", "match x { E::A(v) => { x = v; v }, E::B => x }", "lock ref x as g { x = v; } cancelled { v = x; }", + "select { send(tx, x) { ok => v, closed(x) => x } recv(rx) { ok(v) => x, closed => v } cancelled(i,) => x }", + }; + for (texts) |text| { + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "module q fn f() -> void effects [] {{ {s} }}", .{text})); + try std.testing.expect(parsed == .ok); + const body = parsed.ok.functions[0].body; + const st: ast.Stmt = if (body.stmts.len != 0) body.stmts[0] else .{ .span = body.tail.?.span, .kind = .{ .expr = body.tail.?.* } }; + const region: Region = switch (st.kind) { + .@"while" => |x| .{ .loop = .{ .cond = x.cond, .body = x.body, .step = null } }, + .@"for" => |x| .{ .loop = .{ .cond = null, .body = x.body, .step = x.name } }, + .loop => |b| .{ .loop = .{ .cond = null, .body = b, .step = "x" } }, + .lock => |x| .{ .lock = .{ x.body, x.cancelled } }, + .select => |x| .{ .select = x }, + .expr => |e| switch (e.kind) { + .if_expr => |x| .{ .@"if" = x.* }, + .match_expr => |x| .{ .match = x.* }, + else => unreachable, + }, + else => unreachable, + }; + try compareLivenessRegion(a, region); + } +} + +test "liveAfter rest frames preserve shared seen kills backedges and inner first order" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const x: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .name = "x" } }; + const v: ast.Expr = .{ .span = unaryTestSpan(2), .kind = .{ .name = "v" } }; + const kill: ast.Stmt = .{ .span = unaryTestSpan(3), .kind = .{ .assign = .{ .place = x, .e = v } } }; + const read: ast.Stmt = .{ .span = unaryTestSpan(4), .kind = .{ .expr = x } }; + const b: ast.Block = .{ .span = unaryTestSpan(5), .stmts = &.{}, .tail = &v }; + const cases = [_]Rest{ + .{ .stmts = &.{}, .tail = null }, + .{ .stmts = &.{kill}, .tail = &x, .loop = .{ .cond = x, .body = b, .step = "x" } }, + .{ .stmts = &.{ read, kill }, .tail = null }, + .{ .stmts = &.{ kill, read }, .tail = null }, + .{ .stmts = &.{}, .tail = &x }, + .{ .stmts = &.{}, .tail = null, .current = kill, .current_expr = &x }, + .{ .stmts = &.{}, .tail = null, .current = read, .current_expr = &v }, + .{ .stmts = &.{}, .tail = null, .loop = .{ .cond = x, .body = b, .step = null } }, + .{ .stmts = &.{}, .tail = null, .loop = .{ .cond = null, .body = b, .step = "x" } }, + .{ .stmts = &.{}, .tail = null, .current_expr = &x }, + }; + var l: Lowerer = .{ .arena = a, .m = .{ .name = "q", .types = &.{}, .functions = &.{} } }; + defer l.live_queries.deinit(a); + for (cases) |outer| for (cases) |middle| for (cases) |inner| { + var frames = [_]Rest{ outer, middle, inner }; + l.rest.items = &frames; + l.rest.capacity = frames.len; + for ([_][]const u8{ "x", "v", "missing" }) |name| for (1..7) |line| { + const span = unaryTestSpan(@intCast(line)); + try std.testing.expectEqual(ReferenceLiveness.liveAfter(&l, name, span), try l.liveAfter(name, span)); + }; + }; + // Exact assertions ensure the differential test includes the intended traps. + var shared = [_]Rest{cases[5]}; + l.rest.items = &shared; + try std.testing.expect(try l.liveAfter("x", kill.span)); + var suppressed = [_]Rest{ cases[4], cases[1] }; + l.rest.items = &suppressed; + try std.testing.expect(!try l.liveAfter("x", unaryTestSpan(999))); + var fresh = [_]Rest{ cases[9], .{ .stmts = &.{}, .tail = null, .current = kill } }; + l.rest.items = &fresh; + try std.testing.expect(!try l.liveAfter("x", kill.span)); +} + +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;", + "x = v;", "x = x + 1u8;", "v = x;", "*p = x;", + "v[x] = y;", "ref v = x;", "mut v = xs[x..y];", "return x;", + "return;", "trap;", "break;", "continue;", + "f(x, v);", "f(if c { x } else { v });", "[x, v];", "[x; 2];", + "R { a: x, b: v };", "not x;", "-x;", "*x;", + "x as! u8;", "x.field;", "f(ref x);", "move x;", + "f() or trap;", "if x { v; } else if v { x; } else { f(); }", "match x { E::A(v) => v, E::B => x }", "match x { ok(v) => x, err(x) => v, _ => x }", + "while x { if v { x = v; } else { continue; } }", "for i in x..v { x = i; }", "loop { x = v; break; }", "shield { f(x); }", + "scope s { f(x); }", "lock ref x as v { f(v); } cancelled { f(x); }", "select { send(tx, x) { ok => v, closed(x) => x } recv(rx) { ok(v) => x, closed => v } cancelled(x,) => x }", "{ x = v; }", + "(if c {} else {}) f(x);", "match v { E::A => { while v { f(); } v }, E::B => x, _ => x }", "select { recv(rx) { ok(v) => { while v { f(); } v }, closed => x } cancelled => x }", "if c { while v { f(); } } else if x { x; } else { x; }", + "while v { f(); } x;", "while v { f(); } v; x;", "while v { f(); } x", "while x { f(); } v;", + "for x in v..v { f(); } x;", "if f(x) { v; } else if c { f(); v; } else { x; } x;", "match f(x) { E::A(v) => v, E::B => { f(); x }, _ => x } x;", "select { send(tx, f(x)) { ok => { f(); v }, closed(x) => x } recv(rx) { ok(v) => { f(); x }, closed => v } cancelled(x,) => x } x;", + }; + const forms = [_]struct { before: []const u8, after: []const u8 }{ + .{ .before = "", .after = "" }, + .{ .before = "if c { ", .after = " } else { x; }" }, + .{ .before = "loop { ", .after = " }" }, + .{ .before = "f({ ", .after = " });" }, + }; + for (statements) |statement| for (forms) |form| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const text = try std.fmt.allocPrint(a, "module query fn main() -> void effects [] {{ {s}{s}{s} }}", .{ form.before, statement, form.after }); + const parsed = try parse_mod.parse(a, text); + try std.testing.expect(parsed == .ok); + try compareLivenessBlock(a, parsed.ok.functions[0].body); + }; +} + +// Test-only structural reflection, independent of the production child tables. +fn collectQuerySpans(a: Allocator, value: anytype, out: *std.ArrayList(Span)) Allocator.Error!void { + const T = @TypeOf(value); + if (T == Span) { + try out.append(a, value); + return; + } + switch (@typeInfo(T)) { + .@"struct" => |info| inline for (info.field_names) |field| try collectQuerySpans(a, @field(value, field), out), + .@"union" => switch (value) { + inline else => |payload| try collectQuerySpans(a, payload, out), + }, + .optional => if (value) |inner| try collectQuerySpans(a, inner, out), + .pointer => |info| if (info.child != u8) { + if (info.size == .one) try collectQuerySpans(a, value.*, out) else if (info.size == .slice) for (value) |inner| try collectQuerySpans(a, inner, out); + }, + else => {}, + } +} + +fn queryNest(a: Allocator, child: ast.Expr, form: usize, level: usize) Error!ast.Expr { + const span = unaryTestSpan(@intCast(level + 100)); + const v = try box(a, .{ .span = unaryTestSpan(2), .kind = .{ .name = "v" } }); + const inner = try box(a, child); + const b: ast.Block = .{ .span = span, .stmts = &.{}, .tail = inner }; + const empty: ast.Block = .{ .span = unaryTestSpan(3), .stmts = &.{}, .tail = null }; + return .{ .span = span, .kind = switch (form) { + 0 => .{ .not = inner }, + 1 => .{ .binary = .{ .op = .add, .l = inner, .r = v } }, + 2 => .{ .binary = .{ .op = .add, .l = v, .r = inner } }, + 3 => .{ .block = blk: { + const x = try a.create(ast.Block); + x.* = b; + break :blk x; + } }, + 4 => .{ .if_expr = blk: { + const x = try a.create(ast.If); + x.* = .{ .cond = v.*, .then = b, .@"else" = .{ .block = empty } }; + break :blk x; + } }, + 5 => .{ .if_expr = blk: { + const x = try a.create(ast.If); + x.* = .{ .cond = v.*, .then = empty, .@"else" = if (child.kind == .if_expr) .{ .@"if" = child.kind.if_expr } else .{ .block = b } }; + break :blk x; + } }, + 6 => .{ .match_expr = blk: { + const x = try a.create(ast.Match); + x.* = .{ .span = span, .kind = .integer, .scrutinee = v.*, .arms = try a.dupe(ast.Arm, &.{ .{ .pattern = .{ .span = span, .kind = .wildcard }, .body = child }, .{ .pattern = .{ .span = span, .kind = .{ .int = "0" } }, .body = v.* } }) }; + break :blk x; + } }, + 7 => .{ .call = .{ .callee = v, .type_arg = null, .args = try a.dupe(ast.Expr, &.{ child, v.* }) } }, + 8 => .{ .block = blk: { + const x = try a.create(ast.Block); + x.* = .{ .span = span, .tail = null, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = span, .kind = .{ .@"while" = .{ .cond = v.*, .body = b } } }}) }; + break :blk x; + } }, + 9 => .{ .block = blk: { + const x = try a.create(ast.Block); + x.* = .{ .span = span, .tail = null, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = span, .kind = .{ .lock = .{ .place = v.*, .name = "g", .body = b, .cancelled = empty } } }}) }; + break :blk x; + } }, + 10 => .{ .block = blk: { + const x = try a.create(ast.Block); + const arms = try a.dupe(ast.Arm, &.{.{ .pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = null, .name = "ok", .binds = &.{} } } }, .body = child }}); + const sel: ast.Select = .{ .span = span, .arms = try a.dupe(ast.SelectArm, &.{.{ .span = span, .send = false, .endpoint = "rx", .value = null, .arms = arms }}), .cancelled_binds = &.{}, .cancelled = v.* }; + x.* = .{ .span = span, .tail = null, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = span, .kind = .{ .select = sel } }}) }; + break :blk x; + } }, + else => unreachable, + } }; +} + +fn queryLeaf(a: Allocator) Error!ast.Expr { + const x: ast.Expr = .{ .span = unaryTestSpan(10), .kind = .{ .name = "x" } }; + const v: ast.Expr = .{ .span = unaryTestSpan(11), .kind = .{ .name = "v" } }; + const b = try a.create(ast.Block); + b.* = .{ .span = unaryTestSpan(12), .tail = try box(a, x), .stmts = try a.dupe(ast.Stmt, &.{.{ .span = unaryTestSpan(13), .kind = .{ .assign = .{ .place = x, .e = v } } }}) }; + return .{ .span = unaryTestSpan(14), .kind = .{ .block = b } }; +} + +test "deep liveness queries retain child order sibling exclusion and loop reads" { + for (0..12) |form| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var e = try queryLeaf(a); + const depth = 32_768; + for (0..depth) |i| { + const kind = if (form == 11) i % 11 else form; + e = try queryNest(a, e, kind, i); + } + var workspace: liveness.Workspace = .{}; + defer workspace.deinit(a); + try std.testing.expect(try workspace.reads(a, .{ .expr = e }, "x", null)); + try std.testing.expect(try workspace.assigns(a, .{ .expr = e }, "x")); + try std.testing.expect(!try workspace.reads(a, .{ .expr = e }, "missing", null)); + try std.testing.expect(!try workspace.assigns(a, .{ .expr = e }, "missing")); + var after: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + try std.testing.expect(try after.expr(a, &workspace, e)); + try std.testing.expect(after.seen); + const loop_shape = form == 8 or form == 11; + var absent: After = .{ .name = "missing", .construct = unaryTestSpan(if (loop_shape) 999_999 else 13) }; + try std.testing.expect(!try absent.expr(a, &workspace, e)); + try std.testing.expectEqual(!loop_shape, absent.seen); + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + } +} + +test "wide liveness sequences use one lazy cursor and decisive leaves allocate nothing" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const values = try a.alloc(ast.Expr, 65_536); + for (values) |*e| e.* = .{ .span = unaryTestSpan(1), .kind = .{ .name = "v" } }; + values[values.len - 1].kind = .{ .name = "x" }; + const e: ast.Expr = .{ .span = unaryTestSpan(2), .kind = .{ .array_list = values } }; + var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 }); + var workspace: liveness.Workspace = .{}; + try std.testing.expect(try workspace.reads(backing.allocator(), .{ .expr = e }, "x", null)); + try std.testing.expect(!try workspace.reads(backing.allocator(), .{ .expr = e }, "missing", null)); + try std.testing.expect(!backing.has_induced_failure); + workspace.deinit(backing.allocator()); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + var zero: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + workspace = .{}; + try std.testing.expect(try workspace.reads(zero.allocator(), .{ .expr = values[values.len - 1] }, "x", null)); + try std.testing.expect(!try workspace.assigns(zero.allocator(), .{ .expr = values[0] }, "x")); + var after: After = .{ .name = "x", .construct = values[0].span }; + try std.testing.expect(!try after.expr(zero.allocator(), &workspace, values[0])); + try std.testing.expect(after.seen and !zero.has_induced_failure); + workspace.deinit(zero.allocator()); +} + +test "grown liveness and carried set queries propagate recovering and persistent OOM" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var e = try queryLeaf(a); + for (0..64) |i| e = try queryNest(a, e, if (i % 2 == 0) 4 else 10, i); + const statement: ast.Stmt = .{ .span = unaryTestSpan(999), .kind = .{ .expr = e } }; + for (0..5) |mode| for ([_]bool{ false, true }) |sticky| { + var fail_at: usize = 0; + var query_failure = false; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 128); + 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 }; + var workspace: liveness.Workspace = .{}; + var after: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + var l: Lowerer = .{ .arena = allocation.allocator(), .m = .{ .name = "query", .types = &.{}, .functions = &.{} } }; + // Setup is fixture-owned and precedes injection. Queries only + // borrow it; new output and metadata use the failing allocator. + l.bindings.items = try a.dupe(Binding, &.{.{ .name = "x", .mutable = true, .value = "x0", .ty = .{ .int = "i64" } }}); + l.bindings.capacity = l.bindings.items.len; + l.rest.items = try a.dupe(Rest, &.{.{ .stmts = &.{}, .tail = null, .current = statement }}); + l.rest.capacity = l.rest.items.len; + const result: Error!bool = switch (mode) { + 0 => workspace.reads(allocation.allocator(), .{ .expr = e }, "x", null), + 1 => workspace.assigns(allocation.allocator(), .{ .expr = e }, "x"), + 2 => after.expr(allocation.allocator(), &workspace, e), + 3 => l.liveAfter("x", unaryTestSpan(13)), + 4 => blk: { + const region: Region = .{ .@"if" = .{ .cond = .{ .span = unaryTestSpan(1), .kind = .{ .boolean = true } }, .then = .{ .span = unaryTestSpan(2), .stmts = &.{}, .tail = try box(a, e) }, .@"else" = null } }; + l.rest.items[0] = .{ .stmts = &.{}, .tail = try box(a, .{ .span = unaryTestSpan(3), .kind = .{ .name = "x" } }) }; + const indices = l.carriedLive(1, unaryTestSpan(999), region) catch |err| break :blk err; + break :blk indices.len == 1 and indices[0] == 0; + }, + else => unreachable, + }; + if (allocation.failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!sticky) try std.testing.expectEqual(fail_at + 1, allocation.attempts); + if (workspace.work.capacity != 0 or l.live_queries.work.capacity != 0) query_failure = true; + } else try std.testing.expect(try result); + try std.testing.expect(l.problem == null and l.problems.items.len == 0 and l.out.items.len == 0); + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + try std.testing.expectEqual(@as(usize, 0), l.live_queries.work.items.len); + workspace.deinit(allocation.allocator()); + l.live_queries.deinit(allocation.allocator()); + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!allocation.failed) break; + } + try std.testing.expect(query_failure); + }; +} + +test "liveness scratch frees every grown allocation on direct heap OOM" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var e = try queryLeaf(a); + for (0..64) |i| e = try queryNest(a, e, if (i % 2 == 0) 4 else 10, i); + for (0..3) |mode| for ([_]bool{ false, true }) |sticky| { + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 128); + var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + var allocation: QueryAllocationFailure = .{ .backing = backing.allocator(), .fail_at = fail_at, .sticky = sticky }; + var workspace: liveness.Workspace = .{}; + var after: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + const result = switch (mode) { + 0 => workspace.reads(allocation.allocator(), .{ .expr = e }, "x", null), + 1 => workspace.assigns(allocation.allocator(), .{ .expr = e }, "x"), + 2 => after.expr(allocation.allocator(), &workspace, e), + else => unreachable, + }; + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + if (allocation.failed) try std.testing.expectError(error.OutOfMemory, result) else { + try std.testing.expect(try result); + // Repeated queries must reuse capacity with the same allocator. + const attempts = allocation.attempts; + var again: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + const repeated = switch (mode) { + 0 => workspace.reads(allocation.allocator(), .{ .expr = e }, "x", null), + 1 => workspace.assigns(allocation.allocator(), .{ .expr = e }, "x"), + 2 => again.expr(allocation.allocator(), &workspace, e), + else => unreachable, + }; + try std.testing.expect(try repeated); + try std.testing.expectEqual(attempts, allocation.attempts); + } + if (allocation.failed and !sticky) { + // A recovering allocator permits new requests after its one + // injected failure. Retry the same query with fresh After state. + var retry_after: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + const retry = switch (mode) { + 0 => workspace.reads(allocation.allocator(), .{ .expr = e }, "x", null), + 1 => workspace.assigns(allocation.allocator(), .{ .expr = e }, "x"), + 2 => retry_after.expr(allocation.allocator(), &workspace, e), + else => unreachable, + }; + try std.testing.expect(try retry); + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + } + workspace.deinit(allocation.allocator()); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!allocation.failed) break; + } + }; +} + +test "public liveness lowering propagates host OOM without diagnostics or partial AIR" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var chain: std.ArrayList(u8) = .empty; + for (0..64) |_| try chain.appendSlice(a, "- "); + for ([_]bool{ false, true }) |invalid| { + const text = try std.fmt.allocPrint( + a, + "module oom fn main() -> i64 effects [] {{ var x: i64 = 0i64; if true {{ x = 1i64; }} let y: i64 = {s}x; let z: i64 = {s}(if true {{ x = 2i64; 0i64 }} else {{ 1i64 }}); return {s}; }}", + .{ chain.items, chain.items, if (invalid) "missing" else "x" }, + ); + const parsed = try parse_mod.parse(a, text); + try std.testing.expect(parsed == .ok); + const baseline = try lower(a, parsed.ok); + if (invalid) try std.testing.expectEqualStrings("E7002", baseline.err.code) else try std.testing.expect(baseline == .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 = lower(allocation.allocator(), parsed.ok); + if (allocation.failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!sticky) try std.testing.expectEqual(fail_at + 1, allocation.attempts); + } else if (invalid) { + try std.testing.expectEqualDeep(baseline.err, (try result).err); + } else try std.testing.expect((try result) == .ok); + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!allocation.failed) break; + } + } + } +} + +test "deep After loop resumes preserve competing sibling exclusion and entry state" { + for (0..3) |form| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const x: ast.Expr = .{ .span = unaryTestSpan(1), .kind = .{ .name = "x" } }; + const v: ast.Expr = .{ .span = unaryTestSpan(2), .kind = .{ .name = "v" } }; + const leaf: ast.Block = .{ .span = unaryTestSpan(3), .tail = &v, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = unaryTestSpan(13), .kind = .{ .assign = .{ .place = x, .e = v } } }}) }; + const loop_block = try a.create(ast.Block); + loop_block.* = .{ .span = unaryTestSpan(4), .tail = null, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = unaryTestSpan(5), .kind = .{ .@"while" = .{ .cond = v, .body = leaf } } }}) }; + var e: ast.Expr = .{ .span = unaryTestSpan(6), .kind = .{ .block = loop_block } }; + for (0..32_768) |level| { + const span = unaryTestSpan(@intCast(level + 100)); + const body: ast.Block = .{ .span = span, .stmts = &.{}, .tail = try box(a, e) }; + if (form == 0) { + const conditional = try a.create(ast.If); + conditional.* = .{ .cond = v, .then = body, .@"else" = .{ .block = .{ .span = span, .stmts = &.{}, .tail = &x } } }; + e = .{ .span = span, .kind = .{ .if_expr = conditional } }; + } else { + const arms = try a.dupe(ast.Arm, &.{ + .{ .pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = null, .name = "ok", .binds = &.{} } } }, .body = e }, + .{ .pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = null, .name = "closed", .binds = &.{} } } }, .body = x }, + }); + if (form == 1) { + const match = try a.create(ast.Match); + match.* = .{ .span = span, .kind = .outcome, .scrutinee = v, .arms = arms }; + e = .{ .span = span, .kind = .{ .match_expr = match } }; + } else { + const block = try a.create(ast.Block); + const sel: ast.Select = .{ .span = span, .arms = try a.dupe(ast.SelectArm, &.{.{ .span = span, .send = false, .endpoint = "rx", .value = null, .arms = arms }}), .cancelled_binds = &.{}, .cancelled = x }; + block.* = .{ .span = span, .tail = null, .stmts = try a.dupe(ast.Stmt, &.{.{ .span = span, .kind = .{ .select = sel } }}) }; + e = .{ .span = span, .kind = .{ .block = block } }; + } + } + } + var workspace: liveness.Workspace = .{}; + defer workspace.deinit(a); + // The innermost loop rescan is false; pending After groups must exclude + // each later x arm, including select.cancelled, all the way to the root. + var after: After = .{ .name = "x", .construct = unaryTestSpan(13) }; + try std.testing.expect(!try after.expr(a, &workspace, e)); + try std.testing.expect(after.seen); + try std.testing.expect(try workspace.reads(a, .{ .expr = e }, "x", null)); + // If the construct was before the entire group, competing arms count. + var entered: After = .{ .name = "x", .construct = unaryTestSpan(999_999), .seen = true }; + try std.testing.expect(try entered.expr(a, &workspace, e)); + try std.testing.expectEqual(@as(usize, 0), workspace.work.items.len); + } +} diff --git a/tests/hosted/source_liveness_depth.py b/tests/hosted/source_liveness_depth.py new file mode 100644 index 0000000..3547328 --- /dev/null +++ b/tests/hosted/source_liveness_depth.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Deep pruned-SSA queries through the public CLI; Q-061 control lowering stays open.""" +import json +from pathlib import Path +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / 'zig-out/bin/aji' +checks = 0 + + +def cli(command, path, *options, code=0): + global checks + result = subprocess.run([str(AJI), command, *map(str, options), str(path)], capture_output=True) + assert (result.returncode, result.stderr) == (code, b''), (command, path, result.returncode, result.stdout, result.stderr) + checks += 1 + return result.stdout + + +def source(kind, depth, branch, killed=False, leaf='x'): + flag = 'true' if branch else 'false' + prefix = 'module depth\nfn main() -> i64 effects [] { var x: i64 = 0i64; ' + chain = '- ' * depth + if kind == 'read': + expression = chain + leaf + text = prefix + f'if {flag} {{ x = 1i64; }} let y: i64 = {expression}; return y; }}\n' + fuel = 2 * depth + (6 if branch else 5) + expected = (1 if depth % 2 == 0 else -1) if branch else 0 + else: + expression = chain + f'(if {flag} {{ x = 1i64; 0i64 }} else {{ 1i64 }})' + suffix = 'x = 9i64; ' if killed else '' + text = prefix + f'let y: i64 = {expression}; {suffix}return x; }}\n' + fuel = 2 * depth + (7 if branch else 6) + int(killed) + expected = 9 if killed else int(branch) + return text, fuel, expected + + +with tempfile.TemporaryDirectory(prefix='aji-liveness-depth-') as directory: + root = Path(directory) + for depth in (0, 1, 16, 1024, 16384, 32768, 65536): + for kind, killed in (('read', False), ('after', False), ('after', True)): + for branch in (False, True): + path = root / f'{kind}-{killed}-{branch}-{depth}.aji' + text, fuel, expected = source(kind, depth, branch, killed) + path.write_text(text) + assert cli('check', path) == b'' + lowered = cli('lower', path) + # Check the liveness decision directly in canonical AIR: + # assignment before a later kill must not be carried to the join. + join = next(line for line in lowered.splitlines() if line.startswith(b'endif_')) + assert (b'%x_' in join) == (not killed), join + formatted = cli('fmt', path) + formatted_path = root / 'formatted.aji' + formatted_path.write_bytes(formatted) + assert cli('fmt', formatted_path) == formatted + assert cli('check', formatted_path) == b'' + assert cli('lower', formatted_path) == lowered + air = root / 'canonical.air' + air.write_bytes(lowered) + assert cli('check', air) == b'' + if depth <= 1024: + record = cli('run', path, '--fuel', fuel) + assert json.loads(record) == {'status': 'returned', 'value': expected} + assert cli('run', air, '--fuel', fuel) == record + assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1} + hosted = root / 'hosted.json' + assert cli('run', path, '--profile', 'hosted', '--result-file', hosted, '--fuel', fuel) == b'' + assert json.loads(hosted.read_text()) == json.loads(record) + print(f'liveness depth: {kind} killed={killed} branch={branch} {depth}', flush=True) + + for depth in (0, 1024, 16384, 65536): + path = root / f'missing-{depth}.aji' + text, _, _ = source('read', depth, True, leaf='missing') + path.write_text(text) + errors = cli('check', path, code=1).splitlines() + assert len(errors) == 1, errors + error = json.loads(errors[0]) + line = text.splitlines()[1] + assert (error['code'], error['file'], error['line'], error['col']) == ( + 'E7002', str(path), 2, line.index('missing') + 1), error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, path, code=1)) == error + formatted_path = root / 'rejected-formatted.aji' + formatted_path.write_bytes(cli('fmt', path)) + formatted_error = json.loads(cli('check', formatted_path, code=1)) + contents = formatted_path.read_text().splitlines() + at = next((i + 1, line.index('missing') + 1) for i, line in enumerate(contents) if 'missing' in line) + assert (formatted_error['code'], formatted_error['file'], formatted_error['line'], formatted_error['col']) == ( + 'E7002', str(formatted_path), *at), formatted_error + +print(f'source liveness depth: {checks} CLI checks passed')