cli: lower scalar index operands iteratively

This commit is contained in:
dev committed 2026-10-11 19:15:23 +03:00
1 parent 7ccded2b59
commit 29c1928aa1
5 files changed
+557 -14

No files matched your search

+4 -1
View File
@@ -566,4 +566,7 @@ The [task.join increment](source-expression-depth-audit.md#task-join-operand-con
The [spawn increment](source-expression-depth-audit.md#task-spawn-argument-continuations) preserves scope/worker/arity/per-argument priority, moves, bound loans, emission and host OOM with shared continuations. Build/units/format, exact ordinary conformance coverage, public check/lower parity and lifetime/related/CFG/static-worker checks pass. The focused gate completes 497 distinct CLI checks across split runs, with original/formatted lower parity through 65,536, scalar/pair check through 65,536, mixed check through 32,768 then existing E5101, runtime/source-AIR/fuel through 1,024 and rejected positions through 65,536. Read-only Claude core/final follow-up reviews found no production or fixture defect, within their recorded scope. At that spawn checkpoint nested mutex.make/take aborted at 256/1,024 before/after and was next. Graph/place/control/liveness and multi-result callbacks, Q-060 full GC and Phase 6 exit gates remain open; no semantic/depth-limit change.
The [mutex make/take increment](source-expression-depth-audit.md#mutex-maketake-operand-continuations) preserves consuming/content/type priority, explicit moves, spans, loans, emission and host OOM. Build/units/format, lifetime/related/CFG and 310 focused CLI checks pass; scalar checks and original/formatted lower reach 65,536, mixed checks reach 32,768 then existing E5101, runtime/source-AIR/fuel reach 1,024 and rejected positions reach 65,536. All 1,793 ordinary conformance files have exact successful coverage. Frozen public check/lower parity passes (1,423/506) over `tests/conformance/**/*.aji`; read-only Claude core/final reviews found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. Index operands still abort at 1,024 before/after; other walks, Q-060 and Phase 6 remain open. No semantic or depth-limit change.
The [mutex make/take increment](source-expression-depth-audit.md#mutex-maketake-operand-continuations) preserves consuming/content/type priority, explicit moves, spans, loans, emission and host OOM. Build/units/format, lifetime/related/CFG and 310 focused CLI checks pass; scalar checks and original/formatted lower reach 65,536, mixed checks reach 32,768 then existing E5101, runtime/source-AIR/fuel reach 1,024 and rejected positions reach 65,536. All 1,793 ordinary conformance files have exact successful coverage. Frozen public check/lower parity passes (1,423/506) over `tests/conformance/**/*.aji`; read-only Claude core/final reviews found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. At that mutex checkpoint index operands aborted at 1,024 before/after; other walks, Q-060 and Phase 6 remain open. No semantic or depth-limit change.
The [scalar index operand increment](source-expression-depth-audit.md#scalar-index-operand-continuations) preserves base/type/operand priority, usize hints, bounds facts, unchecked state, loans, load/end order, spans and host OOM. Build/units/format and store-mode/array-argument/lifetime/CFG suites pass; exact ordinary conformance (1,793), public frozen parity (1,423/506), the original focused run passes 318 CLI checks (check through 32,768 then existing E5101 at 65,536; lower/fmt through 65,536; runtime/fuel through 1,024), and separate overlapping 30-call fuel/28-call CFG/deref/proven-context subsets pass. Read-only Claude core/final reviews found no production defect and their fixture/wording suggestions are covered. The recorded nested-array base-index probe still aborts at 1,024 before/after, with other place/control/liveness callbacks, Q-060 and Phase 6 open. No semantic or new depth-limit change.
+76 -4
View File
@@ -996,11 +996,83 @@ checked separately; they do not compare failure-free error spans. Accepted
report/explore and full expression-suite execution are not claimed. No arbitrary
control/liveness or runtime-depth closure is established.
Follow-up index-operand nesting `a[a[...0usize]]` on `[usize; 1]` accepts
At this mutex checkpoint index-operand nesting `a[a[...0usize]]` on `[usize; 1]` accepts
16/256 but aborts at 1,024 before/after. `task-mutex-next-probes.json` and raw
stdout/stderr record the confirmed remaining callback. An initial probe used
invalid `array<usize, 1>` syntax and was corrected before this failure claim.
## Scalar index operand continuations
Value indices now share the operand driver (spec 15 §5). Range-as-value
rejection precedes base work. Base borrowing runs with unchecked cleared;
the saved outer flag is restored for base-type rejection and cleared for the
usize-hinted operand. After that operand, type checking precedes the current
SSA bounds-fact lookup, unsafe feature use, element borrow, load and reverse
child/base endings. Base identity, element type, spans and ends are stored by
value before child shadowing/CFG. No consuming check is added to the index.
Bounds proof still requires the same SSA index/slice (spec 08 §12); ownership,
aliasing and lifetime rules remain verifier-owned. Checked indexing retains
T0008; unchecked access still needs the explicit unsafe contract. Runtime,
interpreter fuel, effects, diagnostics, AIR/features/bundle and existing
complexity limits are unchanged. No semantic acceptance-depth limit is added.
Work frames and their borrowed AST/type/name data keep caller-arena lifetime.
Frame-stack memory is unmeasured; list deinit does not imply early arena release.
Copied `ReferenceIndexPlaces` retains the old recursive place/index descent,
using recursive operand references; leaf/type/borrow/emission and other
fallback helpers remain shared. Its 41 expressions × 8 wrappers × 3 hints ×
2 unchecked states compare values/errors, problem/unimplemented, blocks,
allocations/constants/bindings, counter/current block, feature-use set, linear/
constant flags, borrow parents, unchecked and bounds facts. Other state and
arbitrary statement contexts are unverified. New-driver 32,768-depth tests
check base-first and load/end order, exact spans, unknown/wrong-int partial
prefixes. Six public recovering/persistent OOM sweeps retain host errors and
actual backing cleanup. An additional private 64-level recovering sweep
covers every allocation through grown worklist capacities, late base prefixes,
no false diagnostic/output and physical backing cleanup; failure-free tags, not full error spans, are compared.
Build/follow-up units/format pass, as do store-mode/array-argument/lifetime/CFG
suites (348/85/188/146). All 1,793 ordinary conformance files have exact
successful coverage; frozen public checks/lowerings are byte-exact (1,423/506)
over `tests/conformance/**/*.aji`. The original focused run terminates with
318 successful CLI checks, before the later AIR fuel-1/context additions.
Both depth families check through 32,768; at 65,536 they receive existing
E5101 (pure main 327686; mixed main 458758/module 458759). Original/formatted
lower and formatter fixed points reach 65,536; repeated formatted accepted
checks reach 1,024. Eight rejected families preserve code/fields/positions and
identical check/lower/run/report/explore JSON through 65,536, including formatted
positions. Source/AIR accepted runs and fuel boundaries reach 1,024.
`index-operand-fuel-subset.py` completes 30 follow-up calls (10 lower,
10 source exhaustion, 10 AIR exhaustion), with quantum one/seed 7 through
1,024. Its checks overlap the earlier run and are not added as distinct tests.
The separate 28-call context subset verifies bounded CFG, dereferenced
array bases and a proven index inside a child. Runtime bound remains 1,024.
Read-only Claude core review found no production defect. Its bare linear
index/deref-base/grown-OOM/CFG/fuel fixture suggestions are implemented. Final
read-only follow-up found no production defect or fixture defect invalidating
passing results; it re-read the new driver/preparation/finish, copied old path,
tests, docs and base-probe evidence without running tests. Its subset-count,
probe-scope and frame-memory wording suggestions are integrated. Synthetic
unchecked=true equality runs are not public unchecked-index depth evidence;
public unchecked accesses retain their existing conformance coverage. The
64-level private OOM sweep starts after lowerer setup; setup is covered only
by the small public sweeps. Arbitrary/deep accepted CFG remains unverified.
Bounded source/AIR probes establish static/fuel counts: pure d>0 is 5d+6; mixed double-call
index d>0 is 7d+7 module instructions and 9d+6 fuel. At d0 the unused array
stays SSA (4 instructions/fuel; mixed's unused worker adds one static ret).
The test record includes the existing empty stdout/stderr/files capture.
Existing valid `source/layer6/unchecked.aji`, rejected
`source/layer34/reject/index_scalar.aji` (E7005), and
`source/layer34/bounds_trap.aji` (T0008) retain their contracts. No whole
expression-suite, control/liveness or runtime-depth closure claim.
Follow-up base-index nesting `a[0usize][0usize]...` on nested length-one arrays
accepts 16/256 but aborts at 1,024 before/after this operand repair.
`index-operand-next-probes.json` and matching raw files retain the evidence.
Place base/range/borrow, graph/control and other native callbacks still need
repair/audit; Q-061, Q-060 full GC and Phase 6 remain open.
## Remaining work
Follow-up checks accept 16 parenthesized/mixed-call levels but abort
@@ -1015,7 +1087,7 @@ includes a confirmed lowerer failure and inspection-only risks:
| Production path | Evidence and next scope |
|---|---|
| Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. |
| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, 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, with final gates pending. Index operands independently abort at 1,024 before/after the mutex repair. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. |
| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Boolean, consuming own/region, atomic, task.join and spawn operands are repaired above. Mutex make/take operands are repaired above. Scalar index operands use continuations above; the recorded nested-array base-index probe still aborts at 1,024 before/after this repair. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. |
| Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. |
The formatter's expression-marking traversal already uses a worklist, as
@@ -1024,5 +1096,5 @@ claim every listed callback fails, or that all other paths have been cleared.
Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is
independent. The five reviewed increments now have a scoped external review;
the host-OOM follow-up and intermediate repairs have no separate review.
The struct/value-field, array, enum-payload, task.join, task.spawn and mutex
increments have the scoped reviews recorded above.
The struct/value-field, array, enum-payload, task.join, task.spawn, mutex and
scalar index operand increments have the scoped reviews recorded above.
+19 -1
View File
@@ -794,6 +794,24 @@ fuel and formatted accepted checks reach 1,024; rejected positions reach
65,536. Lifetime/related/CFG suites and all 1,793 ordinary conformance
files with exact coverage and public frozen check/lower parity (1,423/506)
pass over `tests/conformance/**/*.aji`. Read-only Claude core/final reviews
found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. Index operands still abort
found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. At this mutex checkpoint index operands abort
at 1,024 before/after; other callbacks/walks, Q-060 and Phase 6 remain open.
No semantic or depth-limit change.
### Scalar index operand depth increment
The [index operand increment](../design/source-expression-depth-audit.md#scalar-index-operand-continuations)
preserves base/type/operand priority, usize hints, bounds facts, unchecked
state, loans, load/end order, spans and host OOM. Build/units/format and
store-mode/array-argument/lifetime/CFG suites pass. Exact ordinary conformance
coverage (1,793) and frozen public parity (1,423/506) pass. The original focused CLI run
passes 318 checks; both families check through 32,768 then reach existing
E5101 at 65,536. Original/formatted lower reaches 65,536; runtime/fuel and
repeated formatted accepted checks reach 1,024. Separate fuel follow-up passes
30 calls (10 lower, 20 source/AIR exhaustion); CFG/deref/proven contexts pass
28. These overlapping subsets do not establish a full current expression-suite
run. Read-only Claude core/final reviews found no production defect and their
fixture/wording suggestions are covered. The recorded nested-array base-index
probe still aborts at 1,024 before/after; place/range/borrow,
control/liveness and other paths, Q-060 and Phase 6 remain open. No semantic or
new depth-limit change.
+352 -8
View File
@@ -1983,7 +1983,7 @@ const Lowerer = struct {
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
.not, .neg, .deref, .cast, .binary, .array_list, .array_rep => return l.operandExpr(e, want),
.not, .neg, .deref, .cast, .binary, .array_list, .array_rep, .index => return l.operandExpr(e, want),
.specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}),
.int => |x| {
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
@@ -2002,13 +2002,6 @@ const Lowerer = struct {
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
.index => |x| {
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
},
.bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
.borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
.call => |x| return switch (try l.prepareCall(e, x.callee.*, x.args, false)) {
@@ -2058,6 +2051,7 @@ const Lowerer = struct {
call_argument: *OrdinaryCall,
struct_field: *StructConstruction,
field_value: *FieldRead,
index_value: IndexRead,
array_element: *ArrayConstruction,
array_repeat: ast.Expr,
variant_argument: *VariantConstruction,
@@ -2245,6 +2239,12 @@ const Lowerer = struct {
.done => |v| break v,
.read => |f| prepared = .{ .field = f },
},
.index => {
const c = try l.prepareIndexRead(e);
try pending.append(l.arena, .{ .index_value = c });
e = c.input;
want = .{ .int = "usize" };
},
else => break try l.expr(e, want),
}
};
@@ -2360,6 +2360,7 @@ const Lowerer = struct {
.consuming_builtin => |c| v = try l.finishConsumingBuiltin(c, v),
.atomic => |c| v = try l.finishAtomic(c, v),
.field_value => |f| v = try l.finishField(f, v),
.index_value => |c| v = try l.finishIndexRead(c, v),
.array_element => |c| {
const input = c.inputs[c.index];
try l.arrayElement(input.span, v.ty, false);
@@ -2380,6 +2381,34 @@ const Lowerer = struct {
}
}
const IndexRead = struct { span: Span, input: ast.Expr, base: Placed, elem: Ty, unchecked: bool };
fn prepareIndexRead(l: *Lowerer, e: ast.Expr) Error!IndexRead {
const x = e.kind.index;
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try l.placeRaw(x.e.*, false, e.span);
l.unchecked = outer_unchecked;
const elem = elemOf(base.v.ty) orelse return l.fail("E7005", e.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(base.v.ty) }});
l.unchecked = false;
return .{ .span = e.span, .input = x.lo.*, .base = base, .elem = elem, .unchecked = outer_unchecked };
}
fn finishIndexRead(l: *Lowerer, c: IndexRead, i: Value) Error!Value {
try l.checkOperandTy(c.input.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, c.base.v.name)) break true;
} else false;
if (c.unchecked) l.uses.insert(.unsafe);
const index_op = if (c.unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.defBorrow("e", if (c.base.v.ty.isMutBorrow()) try l.wrap(.mut, c.elem) else try l.wrap(.ref, c.elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, c.base.v.name, i.name }), c.base.v.name, c.span);
const ends = try l.concat(c.base.ends, v.name);
const result = try l.def("v", c.elem, try l.fmt("load %{s}", .{v.name}), c.span);
try l.endNow(ends, c.span);
return result;
}
// Both operands and their type checks are complete before this step.
fn binaryValue(l: *Lowerer, e: ast.Expr, ty: Ty, lv: Value, rv: Value) Error!Value {
const op = e.kind.binary.op;
@@ -5744,6 +5773,7 @@ const ReferenceOperands = struct {
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
.index => return ReferenceIndexPlaces.value(l, e),
.variant => |v| return ReferenceVariants.value(l, e, v.@"enum", v.name, &.{}),
.array_list, .array_rep => return ReferenceArrays.expr(l, e, want),
.call => |x| return ReferenceCalls.call(l, e, x.callee.*, x.args, false),
@@ -9447,3 +9477,317 @@ test "public mutex continuations propagate host OOM and free arena backing" {
}
}
}
// Copied pre-continuation place descent; type/borrow/emission helpers remain shared.
const ReferenceIndexPlaces = struct {
fn placeRaw(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed {
const op = if (mutable) "borrow.mut" else "borrow.ref";
switch (place.kind) {
.name => |n| {
const b = l.lookup(n) orelse return l.unknown(place.span, n);
switch (b.kind) {
.storage => {
const v = try l.def(n, if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
.ssa => {
// A linear value (owner, region) is borrowed in place.
const bt: ?Ty = switch (b.ty) {
.named, .array => if (l.isLinear(b.ty)) (if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty)) else null,
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.buffer => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
// Atomic operations go through a shared borrow (spec 04 §23).
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.invalid(.invalid_place, place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
const v = try l.def(n, t, try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
}
},
.bytes => |bytes| {
const st = try l.materializeBytes(bytes, place.span);
const v = try l.def("b", if (mutable) try l.wrap(.mut, st.ty) else try l.wrap(.ref, st.ty), try l.fmt("{s} %{s}", .{ op, st.name }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.deref => |d| {
const r = try ReferenceOperands.expr(l, d.*, null);
if (!r.ty.isBorrow()) return l.fail("E7005", place.span, "`*` needs a borrow", &.{});
return .{ .v = r, .ends = &.{} };
},
.field => |f| {
const base = try placeRaw(l, f.e.*, mutable, span);
const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{});
const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }});
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
const fd = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(fd.ty);
const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try placeRaw(l, x.e.*, mutable, span);
l.unchecked = outer_unchecked;
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
if (x.hi) |hi| {
// `s[a..b]`: slice.sub with start a and length b - a (checked).
var sl = base.v;
var ends = base.ends;
if (bt == .ref or bt == .mut) {
sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span);
ends = try l.concat(ends, sl.name);
}
const a = try ReferenceOperands.expr(l, x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, a.ty, .{ .int = "usize" });
const b = try ReferenceOperands.expr(l, hi.*, .{ .int = "usize" });
try l.checkOperandTy(hi.span, b.ty, .{ .int = "usize" });
const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span);
const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
const unchecked = l.unchecked;
l.unchecked = false;
const i = try ReferenceOperands.expr(l, x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true;
} else false;
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.invalid(.invalid_place, place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
}
}
fn value(l: *Lowerer, e: ast.Expr) Error!Value {
if (e.kind.index.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try placeRaw(l, e, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
}
};
const indexTestDeclarations = fieldTestDeclarations ++ "struct Indexed { data: [usize; 1] }\nstruct Matrix { data: [[usize; 1]; 1] }\n";
fn indexTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer {
var l = try consumingTestLowerer(a, m, span);
const integer: Ty = .{ .int = "usize" };
const array = try l.arrayOf(integer, 1);
const indexed = l.enumOrStruct("Indexed", span).?;
try l.bindings.appendSlice(a, &.{
.{ .name = "ra", .value = "array_loan", .mutable = false, .ty = try l.wrap(.ref, array), .kind = .borrow },
.{ .name = "xs", .value = "index_storage", .mutable = false, .ty = array, .kind = .storage },
.{ .name = "ss", .value = "shared_slice", .mutable = false, .ty = try l.wrap(.slice, integer), .kind = .borrow },
.{ .name = "sm", .value = "exclusive_slice", .mutable = false, .ty = try l.wrap(.slice_mut, integer), .kind = .borrow },
.{ .name = "ix", .value = "known_index", .mutable = false, .ty = integer },
.{ .name = "indexed", .value = "indexed_storage", .mutable = false, .ty = indexed, .kind = .storage },
.{ .name = "matrix", .value = "matrix_storage", .mutable = false, .ty = l.enumOrStruct("Matrix", span).?, .kind = .storage },
.{ .name = "ir", .value = "indexed_loan", .mutable = false, .ty = try l.wrap(.ref, indexed), .kind = .borrow },
});
try l.sigs.put(a, "idx", .{ .params = try a.dupe(Ty, &.{integer}), .ret = integer, .air_name = "idx", .display_name = "idx" });
try l.facts.appendSlice(a, &.{ .{ .index = "known_index", .slice = "shared_slice" }, .{ .index = "known_index", .slice = "exclusive_slice" } });
try l.borrow_parents.put(a, "indexed_loan", "indexed_storage");
return l;
}
fn expectIndexMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty, unchecked: bool) !void {
var old = try indexTestLowerer(a, m, e.span);
var current = try indexTestLowerer(a, m, e.span);
old.unchecked = unchecked;
current.unchecked = unchecked;
const expected = ReferenceOperands.expr(&old, e, want);
const actual = current.expr(e, want);
if (expected) |v| {
const result = try actual;
try std.testing.expectEqualStrings(v.name, result.name);
try std.testing.expect(v.ty.eql(result.ty));
} else |err| try std.testing.expectError(err, actual);
try std.testing.expectEqualDeep(old.problem, current.problem);
try std.testing.expectEqualDeep(old.unimpl, current.unimpl);
try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items);
try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items);
try std.testing.expectEqualDeep(old.constants.items, current.constants.items);
try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items);
try std.testing.expectEqual(old.unchecked, current.unchecked);
try std.testing.expectEqualDeep(old.facts.items, current.facts.items);
try std.testing.expectEqual(old.counter, current.counter);
try std.testing.expectEqual(old.cur, current.cur);
try std.testing.expectEqualDeep(old.uses, current.uses);
try std.testing.expectEqual(old.linear_enabled, current.linear_enabled);
try std.testing.expectEqual(old.in_constant, current.in_constant);
try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count());
var parents = old.borrow_parents.iterator();
while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?);
}
test "index continuations preserve former place priority loans facts unchecked and CFG" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const expressions = [_][]const u8{
"xs[o]", "(*ra)[xs[0]]", "(*ra)[unknown]", "(*ra)[o]",
"xs[0]", "xs[xs[0]]", "xs[idx(0usize)]", "xs[id(0i64)]",
"ss[ix]", "sm[ix]", "ss[0usize]", "sm[0usize]",
"indexed.data[0usize]", "ir.data[0usize]", "matrix.data[0usize][0usize]", "xs[ss[ix]]",
"ss[xs[sm[ix]]]", "xs[{ let ix: usize = 0usize; idx(ix) }]", "xs[if true { 0usize } else { 0usize }]", "xs[true and bool_id(false)]",
"xs[unknown]", "unknown[unknown]", "n[unknown]", "o[unknown]",
"p[unknown]", "indexed.data[true]", "xs[1i64]", "xs[ref n]",
"xs[b\"xy\"]", "xs[void_call(b\"xy\")]", "xs[stop(b\"xy\")]", "xs[move o]",
"xs[0usize..1usize]", "unknown[unknown..unknown]", "box.n[unknown]", "box.missing[unknown]",
"xs[xs[unknown]]", "xs[xs[true]]", "oa[0usize]", "xs[mutex.take(mutex.make(0usize))]",
"xs[[0usize][0usize]]",
};
const forms = [_][]const u8{ "{s}", "xs[{s}]", "idx({s})", "-{s}", "{s} as usize", "true and ({s})", "Box {{ n: {s} }}.n", "[{s}]" };
inline for (forms) |form| for (expressions) |text| {
const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ indexTestDeclarations, try std.fmt.allocPrint(a, form, .{text}) }));
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .bool, .{ .int = "usize" } }) |want| for ([_]bool{ false, true }) |unchecked| try expectIndexMatches(a, parsed.ok, e, want, unchecked);
};
}
test "deep index operands keep borrow load end spans and partial error emission" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, indexTestDeclarations)).ok;
const count = 32_768;
for (0..3) |leaf| {
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = switch (leaf) {
0 => .{ .int = .{ .text = "0usize" } },
1 => .{ .name = "unknown" },
else => .{ .int = .{ .text = "0i64" } },
} };
for (0..count) |i| {
const base: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .name = "xs" } };
const items = try a.dupe(ast.Expr, &.{ base, e });
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = null } } };
}
var l = try indexTestLowerer(a, m, e.span);
const counter = l.counter;
if (leaf != 0) {
try std.testing.expectError(error.Lower, l.expr(e, null));
try std.testing.expectEqualStrings(if (leaf == 1) "E7002" else "E7005", l.problem.?.code);
try std.testing.expectEqualDeep(unaryTestSpan(90_000), l.problem.?.span);
try std.testing.expectEqual(count + @as(usize, if (leaf == 1) 0 else 1), l.blocks.items[0].insts.items.len);
} else {
const v = try l.expr(e, null);
try std.testing.expect(v.ty.eql(.{ .int = "usize" }));
const insts = l.blocks.items[0].insts.items;
try std.testing.expectEqual(5 * count + 1, insts.len);
try std.testing.expectEqual(counter + 3 * count + 1, l.counter);
for (insts[0..count], 0..) |inst, i| {
try std.testing.expect(std.mem.indexOf(u8, inst.text, " = borrow.ref %index_storage") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(count - i))), inst.span);
}
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(90_000)), insts[count].span);
for (0..count) |i| {
const start = count + 1 + 4 * i;
try std.testing.expect(std.mem.indexOf(u8, insts[start].text, " = borrow.index %") != null);
try std.testing.expect(std.mem.indexOf(u8, insts[start + 1].text, " = load %") != null);
try std.testing.expect(std.mem.startsWith(u8, insts[start + 2].text, "borrow.end %"));
try std.testing.expect(std.mem.startsWith(u8, insts[start + 3].text, "borrow.end %"));
for (insts[start .. start + 4]) |inst| try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), inst.span);
}
}
}
}
test "public index operand continuation OOM stays host error with arena cleanup" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const programs = [_][]const u8{
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[0usize]]; }\n",
"module oom\nfn main() -> usize effects [] { var a: [usize; 1] = [0usize]; mut s = a; return s[s[0usize]]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[unknown]]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[true]]; }\n",
"module oom\nfn main() -> usize effects [] { let n: usize = 0usize; return n[unknown]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[0usize..1usize]; }\n",
};
for (programs, 0..) |program, index| {
const parsed = try parse_mod.parse(fixture.allocator(), program);
try std.testing.expect(parsed == .ok);
const baseline = try lower(fixture.allocator(), parsed.ok);
if (index < 2) try std.testing.expect(baseline == .ok) else {
try std.testing.expect(baseline == .err);
try std.testing.expectEqualStrings(switch (index) {
2 => "E7002",
5 => "E7006",
else => "E7005",
}, baseline.err.code);
}
for ([_]bool{ false, true }) |persistent| {
var fail_at: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 1024);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at });
var output: std.heap.ArenaAllocator = .init(if (persistent) failing.allocator() else std.testing.allocator);
var recovering: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
const result = lower(if (persistent) output.allocator() else recovering.allocator(), parsed.ok);
output.deinit();
if (persistent) try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
const failed = if (persistent) failing.has_induced_failure else recovering.failed;
if (failed) {
try std.testing.expectError(error.OutOfMemory, result);
if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts);
} else {
try std.testing.expect(std.meta.activeTag(try result) == std.meta.activeTag(baseline));
break;
}
}
}
}
}
test "grown index continuation stack propagates every allocation failure" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, indexTestDeclarations)).ok;
const count = 64;
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "0usize" } } };
for (0..count) |i| {
const base: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .name = "xs" } };
const items = try a.dupe(ast.Expr, &.{ base, e });
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = null } } };
}
var fail_at: usize = 0;
var later_prefix_failures: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 4096);
var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
var output: std.heap.ArenaAllocator = .init(backing.allocator());
var l = try indexTestLowerer(output.allocator(), m, e.span);
var failing: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
l.arena = failing.allocator();
const result = l.expr(e, null);
if (failing.failed) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expectEqual(fail_at + 1, failing.attempts);
try std.testing.expect(l.problem == null and l.unimpl == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
const emitted = l.blocks.items[0].insts.items.len;
if (emitted > 16 and emitted < count) later_prefix_failures += 1;
} else {
try std.testing.expect((try result).ty.eql(.{ .int = "usize" }));
}
output.deinit();
try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes);
if (!failing.failed) break;
}
try std.testing.expect(later_prefix_failures > 0);
}
+106
View File
@@ -1176,4 +1176,110 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
print(f'mutex operand rejection depth: {leaf}', flush=True)
# Value indices preserve base borrows, usize hints, bounds and child-first endings.
for mixed in (False, True):
for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536):
opening, closing = ('a[idx(idx(', '))]') if mixed else ('a[', ']')
expression = opening * depth + '0usize' + closing * depth
worker = 'fn idx(x: usize) -> usize effects [] { x }\n' if mixed else ''
path = root / f'index-operand-{mixed}-{depth}.aji'
path.write_text('module depth\n' + worker + 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return ' + expression + '; }\n')
instructions = (7 * depth + 7 if depth else 5) if mixed else (5 * depth + 6 if depth else 4)
fuel = (9 * depth + 6 if depth else 4) if mixed else (5 * depth + 6 if depth else 4)
limited = depth == 65536
checked = cli('check', path, code=1 if limited else 0)
if limited:
error = json.loads(checked)
main_instructions = instructions - int(mixed)
assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, main_instructions), error
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == checked
else:
assert checked == b''
lowered = cli('lower', path)
actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith((b'ret', b'borrow.end ', b'local.store ')) for line in lowered.splitlines())
assert actual == instructions, (mixed, depth, actual, instructions)
if depth <= 1024:
options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel)
result = cli('run', path, *options)
assert json.loads(result) == {'status': 'returned', 'value': 0, 'stdout': '', 'stderr': '', 'files': {}}, result
exhausted = {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'stdout': '', 'stderr': '', 'files': {}}
assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, *options) == result
assert json.loads(cli('run', air, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert cli('lower', formatted) == lowered
if depth <= 1024:
assert cli('check', formatted) == b''
print(f'index operand accepted depth: mixed={mixed} depth={depth}', flush=True)
# Bounded public CFG/dereference/proven-fact cases complement scalar depth probes.
for label, source, proven in (
('if-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[if true { a[0usize] } else { 0usize }]; }', False),
('boolean-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[if false or true { 0usize } else { 0usize }]; }', False),
('deref-base', 'fn read(p: ref<[usize; 1]>, i: usize) -> usize effects [] { (*p)[i] }\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return read(ref a, a[0usize]); }', False),
('proven-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; ref s = a; let i: usize = 0usize; if i < s.len { return a[s[i]]; } else { return 0usize; } }', True),
):
path = root / f'index-context-{label}.aji'
path.write_text('module depth\n' + source + '\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
if proven:
assert b' = borrow.index.proven ' in lowered, lowered
options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 128)
result = cli('run', path, *options)
assert json.loads(result) == {'status': 'returned', 'value': 0, 'stdout': '', 'stderr': '', 'files': {}}, result
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, *options) == result
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert cli('lower', formatted) == lowered
print('index operand bounded CFG/dereference/proven contexts passed', flush=True)
for leaf, code, offset, extra in (
('unknown', 'E7002', 0, {}),
('true', 'E7005', 0, {'found': 'bool', 'expected': 'usize'}),
('1i64', 'E7005', 0, {'found': 'i64', 'expected': 'usize'}),
('ref n', 'E7006', 0, {'reason': 'invalid_borrow'}),
('b"xy"', 'E7006', 0, {'reason': 'invalid_literal'}),
('a[0usize..1usize]', 'E7006', 0, {'reason': 'invalid_borrow'}),
('n[unknown]', 'E7005', 0, {'found': 'ref<usize>'}),
('a[stop()]', 'E7005', len('a['), {'found': 'never', 'expected': 'usize'}),
):
for depth in (16, 1024, 65536):
prefix = 'module depth\nfn stop() -> never effects [] { trap; }\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; var n: usize = 0usize; return '
opening = 'a['
leaf_name = re.sub(r'[^A-Za-z0-9]+', '-', leaf).strip('-')
path = root / f'index-reject-{code}-{leaf_name}-{depth}.aji'
path.write_text(prefix + opening * depth + leaf + ']' * depth + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 3, len(prefix.split('\n')[-1]) + len(opening) * depth + offset + 1), error
for key, value in extra.items():
assert error[key] == value, error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
formatted_error = json.loads(cli('check', formatted, code=1))
text = output.decode()
pos = text.rfind(leaf)
assert pos >= 0, (leaf, depth)
pos += offset
assert (formatted_error['code'], formatted_error['file'], formatted_error['line'], formatted_error['col']) == (code, str(formatted), text[:pos].count('\n') + 1, pos - text.rfind('\n', 0, pos)), formatted_error
for key, value in extra.items():
assert formatted_error[key] == value, formatted_error
print(f'index operand rejection depth: {leaf}', flush=True)
print(f'source expression depth: {checks} checks passed')