cli: query SSA liveness with iterative continuations

This commit is contained in:
dev committed 2026-10-11 23:44:20 +03:00
1 parent b2c551047c
commit 5c883ace54
7 files changed
+1427 -339

No files matched your search

+1
View File
@@ -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
+11
View File
@@ -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
+33 -1
View File
@@ -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
+19
View File
@@ -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.
+407
View File
@@ -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;
}
}
};
+863 -338
View File
File diff suppressed because it is too large. Load diff
+93
View File
@@ -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')