cli: lower atomic value operands iteratively

This commit is contained in:
dev committed 2026-10-11 15:54:37 +03:00
1 parent 062fce5cfd
commit 8d6792d4f1
5 files changed
+422 -32

No files matched your search

+2
View File
@@ -554,3 +554,5 @@ The [enum-payload increment](source-expression-depth-audit.md#enum-payload-conti
The [boolean builtin increment](source-expression-depth-audit.md#boolean-builtin-operand-continuations) preserves assert/assume arity, non-consuming operands, type/error spans, unsafe registration and emission order, using shared continuations. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 282 focused depth checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up reviews found no production defect. Final span/counter unit checks pass. Own/region argument callbacks still abort at 1,024 before and after; remaining callbacks/walks keep Q-061 and Phase 6 open. No new semantic or depth limit changes.
The [consuming ownership builtin increment](source-expression-depth-audit.md#consuming-ownership-builtin-continuations) preserves own.take/free and region.destroy arity, explicit transfers, type/error priority, emission and OOM separation. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 351 frozen-core CLI checks pass; corrected OOM/expanded units pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews found no production defect. Final `own<bool>` CFG unit comparisons pass. Atomic-new/take pairs and task.join still abort at 1,024. Q-061, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change.
The [atomic operand increment](source-expression-depth-audit.md#atomic-operand-continuations) preserves new/take and ordinary update operand rules, cell/ordering/type priority, temporary loans, emission and host OOM separation through shared continuations. Build/units/format, all 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 33/635/234 targeted checks pass. Focused depth validation passes 270 checks in two subset runs (57/213), including exact rejections and temporary-loan updates through 65,536; mixed chains reach the existing E5101 instruction limit, with runtime/fuel checked through 1,024. Read-only Claude core/follow-up reviews found no production defect. Task.join still aborts at 1,024; other callbacks/walks, Q-060 full GC and Phase 6 gates remain open. No semantic/order-default/depth-limit change.
+49 -1
View File
@@ -798,6 +798,54 @@ not completion of every pending call. Separate atomic-new/take pairs accept 16 i
established. Other builtin/place/control and liveness callbacks, Q-060 full GC
validation and Phase 6 gates remain open.
## Atomic operand continuations
Atomic new/take and ordinary store/RMW value operands now share the expression
driver (spec 15 §12; spec 04). Arity precedes children; take checks explicit
consumption, while new has no type hint. Updates retain cell/ordering-before-
value priority, exact type checks and temporary-borrow endings after emission.
Load/fence and multi-result compare-exchange retain their existing paths. The
invariant is unchanged: cells are linear and atomic operations use a shared
borrow with explicit ordering. Verifier/effect/runtime rules, instruction text,
names, spans and CFG are unchanged; no default ordering, new feature/code/
format/bundle/limit or ownership/concurrency rule. Public output parity and
existing positive/rejected atomic conformance cases establish compatibility.
Copied `ReferenceAtomics` bodies use the former recursive operand path;
shared leaf/place/type/emission helpers limit oracle independence. Shallow
comparisons include bool/integer cells, temporary/bound borrows, orders, arity,
non-values and scalar/aggregate/CFG consumers. Deep units pass 32,768 new/take
pairs and RMW operands with exact counts/spans. Recovering/persistent public
OOM sweeps check successful and E7003/E7005/E7006 baselines, no swallowed OOM
and backing cleanup. States and work buffers retain caller-arena lifetime.
Build/units/format pass.
Ordinary conformance passes all 1,793 cases with exact coverage
(`atomic-operand-conformance.jsonl` and its audit), including schedule cases;
frozen public check/lower outputs are exact (1,423/506). Atomic-access/nonvalue/
independent-error suites pass 33/635/234 checks. Focused CLI validation passes
270 checks in two corrected subset runs: pair 57 and mixed/update/rejection 213
(`atomic-operand-pair-depth.log`, `atomic-operand-followup-depth.log`). New/take
pairs and temporary shared-borrow updates accept through 65,536; mixed
call/negation/atomic chains accept through 32,768 and reach the existing E5101
instruction limit at 65,536 (`max: 262144`, `found: 327683`). Six error families
retain exact code/position/priority through 65,536 across check/lower/run/report/
explore. Formatter fixed points and lower parity pass; source/AIR results and
exact fuel are exercised only through 1,024. Existing `source/layer10/sc_only.aji`
passes 30 schedules; `source/layer10/reject/take_while_lent.aji` retains E4101.
Read-only Claude core/follow-up
reviews found no production defect (`/tmp/aji-atomic-operand-review.md` and
`/tmp/aji-atomic-operand-followup-review.md`); fixture arithmetic/limit and
span/type gaps were corrected. Neither reviewer ran tests. The mixed fixture
uses a function call as its leaf, so signed-literal folding does not erase the
first negation.
No new whole-expression-suite, arbitrary callback or runtime-depth claim.
Task.join still aborts at 1,024 before and after
(`atomic-operand-next-probes.json`); bounded 16/256 records remain equal.
Other builtin/place/control and liveness walks, Q-060 full GC and Phase 6
exit gates remain open.
## Remaining work
Follow-up checks accept 16 parenthesized/mixed-call levels but abort
@@ -812,7 +860,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 and consuming own/region builtin operands are repaired above. Atomic-new/take pairs and task.join still abort at 1,024 in both binaries. 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 and consuming own/region builtin operands are repaired above. Ordinary atomic operand callbacks are repaired above; task.join still aborts at 1,024 in both binaries. 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
+15
View File
@@ -734,3 +734,18 @@ expanded units, all 1,793 ordinary conformance cases, public check/lower parity
found no production defect. Final `own<bool>` CFG unit comparisons pass. Atomic-new/take pairs and task.join
still abort at 1,024. No semantic/depth-limit change; Q-061, Q-060 full GC
validation and Phase 6 exit gates remain open.
### Atomic operand depth increment
The [Q-061 atomic operand increment](../design/source-expression-depth-audit.md#atomic-operand-continuations)
shares new/take and ordinary store/RMW operands with the expression driver,
retaining arity, consuming rules, cell/ordering/type priority, emission and
borrow endings. Load/fence and multi-result binding retain their existing
paths. Build/units/format, all 1,793 ordinary conformance cases, public
check/lower parity (1,423/506) and targeted checks (33/635/234) pass. Focused
depth validation passes 270 checks in two subset runs (57/213), through 65,536
for pairs, temporary-loan updates and exact rejections. Mixed chains reach the
existing E5101 instruction limit at 65,536; runtime/fuel is checked through
1,024. Read-only Claude core/follow-up reviews found no production defect.
Task.join still aborts at 1,024. No semantic/order-default/depth-limit change; Q-061, Q-060
full GC validation and Phase 6 exit gates remain open.
+282 -31
View File
@@ -2017,6 +2017,7 @@ const Lowerer = struct {
.variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }),
.boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }),
.consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }),
.atomic => |c| l.operandExprPrepared(e, null, .{ .atomic = c }),
},
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
.block => |b| {
@@ -2061,6 +2062,7 @@ const Lowerer = struct {
variant_argument: *VariantConstruction,
boolean_builtin: *BooleanBuiltin,
consuming_builtin: *ConsumingBuiltin,
atomic: *AtomicOperand,
};
var pending: std.ArrayList(Frame) = .empty;
defer pending.deinit(l.arena);
@@ -2146,6 +2148,14 @@ const Lowerer = struct {
want = null;
continue;
},
.atomic => |c| {
prepared = .none;
if (c.kind == .take) try l.checkConsumingName(c.input);
try pending.append(l.arena, .{ .atomic = c });
e = c.input;
want = c.want;
continue;
},
}
switch (e.kind) {
.not, .deref => |x| {
@@ -2202,6 +2212,7 @@ const Lowerer = struct {
.variant => |c| prepared = .{ .variant = c },
.boolean_builtin => |c| prepared = .{ .boolean_builtin = c },
.consuming_builtin => |c| prepared = .{ .consuming_builtin = c },
.atomic => |c| prepared = .{ .atomic = c },
},
.variant => |x| switch (try l.prepareVariant(e, x.@"enum", x.name, &.{})) {
.done => |v| break v,
@@ -2324,6 +2335,7 @@ const Lowerer = struct {
v = .{ .name = "", .ty = .void };
},
.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),
.array_element => |c| {
const input = c.inputs[c.index];
@@ -2398,6 +2410,7 @@ const Lowerer = struct {
variant: *VariantConstruction,
boolean_builtin: *BooleanBuiltin,
consuming_builtin: *ConsumingBuiltin,
atomic: *AtomicOperand,
};
const OrdinaryCall = struct {
@@ -2412,7 +2425,7 @@ const Lowerer = struct {
};
const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool };
const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy } };
const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin };
const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand };
fn finishConsumingBuiltin(l: *Lowerer, c: *ConsumingBuiltin, o: Value) Error!Value {
if (c.operation == .take) {
@@ -2433,6 +2446,7 @@ const Lowerer = struct {
.variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }),
.boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }),
.consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }),
.atomic => |c| l.operandExprPrepared(e, null, .{ .atomic = c }),
};
}
@@ -2489,7 +2503,10 @@ const Lowerer = struct {
return .{ .done = .{ .name = "", .ty = .void } };
}
if (try l.concurrencyCall(e, p, args)) |v| return .{ .done = v };
if (std.mem.startsWith(u8, p, "atomic.")) return .{ .done = try l.atomicCall(e, p, args) };
if (std.mem.startsWith(u8, p, "atomic.")) return switch (try l.prepareAtomic(e, p, args)) {
.done => |v| .{ .done = v },
.operand => |c| .{ .atomic = c },
};
if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty;
@@ -3483,50 +3500,75 @@ const Lowerer = struct {
return l.fail("E7005", a.span, "an atomic operation takes a `ref<atomic<T>>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
}
fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
const AtomicDispatch = union(enum) { done: Value, operand: *AtomicOperand };
const AtomicOperand = struct {
span: Span,
input: ast.Expr,
kind: enum { create, take, update },
want: ?Ty = null,
cell: Value = undefined,
operation: []const u8 = "",
order: []const u8 = "",
temps: std.ArrayList([]const u8) = .empty,
};
fn prepareAtomic(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!AtomicDispatch {
const eq = std.mem.eql;
if (eq(u8, p, "atomic.new")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
const v = try l.expr(args[0], null);
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
}
if (eq(u8, p, "atomic.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
const c = try l.consuming(args[0], null);
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }});
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
const create = eq(u8, p, "atomic.new");
if (create or eq(u8, p, "atomic.take")) {
if (args.len != 1) return l.fail("E7005", e.span, if (create) "`atomic.new` takes the initial value" else "`atomic.take` takes one cell", &.{});
const state = try l.arena.create(AtomicOperand);
state.* = .{ .span = e.span, .input = args[0], .kind = if (create) .create else .take };
return .{ .operand = state };
}
if (eq(u8, p, "atomic.fence")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
return .{ .name = "", .ty = .void };
return .{ .done = .{ .name = "", .ty = .void } };
}
if (eq(u8, p, "atomic.compare_exchange"))
return l.invalid(.invalid_unpack, e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
const count: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
if (args.len != count) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{count}) } });
const c = try l.cellOperand(args[0], &temps);
const t = c.ty.inner().?.inner().?;
const ord = try l.ordering(args[want - 1]);
const ord = try l.ordering(args[count - 1]);
if (eq(u8, p, "atomic.load")) {
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
return .{ .done = v };
}
const operand = try l.expr(args[1], t);
try l.checkOperandTy(args[1].span, operand.ty, t);
if (eq(u8, p, "atomic.store")) {
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return .{ .name = "", .ty = .void };
const state = try l.arena.create(AtomicOperand);
state.* = .{ .span = e.span, .input = args[1], .kind = .update, .want = t, .cell = c, .operation = p, .order = ord, .temps = temps };
return .{ .operand = state };
}
fn finishAtomic(l: *Lowerer, c: *AtomicOperand, v: Value) Error!Value {
switch (c.kind) {
.create => {
if (!atomicScalar(v.ty)) return l.fail("E7005", c.input.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), c.span);
},
.take => {
if (v.ty != .atomic) return l.fail("E7005", c.input.span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
return l.def("v", v.ty.inner().?, try l.fmt("atomic.take %{s}", .{v.name}), c.span);
},
.update => {
const t = c.want.?;
try l.checkOperandTy(c.input.span, v.ty, t);
if (std.mem.eql(u8, c.operation, "atomic.store")) {
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ c.order, c.cell.name, v.name }), c.span);
try l.endNow(c.temps.items, c.span);
return .{ .name = "", .ty = .void };
}
const op: []const u8 = if (std.mem.eql(u8, c.operation, "atomic.swap")) "xchg" else c.operation["atomic.".len..];
if ((std.mem.eql(u8, op, "add.wrap") or std.mem.eql(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", c.input.span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = try l.diagnosticTyText(t) }});
const result = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, c.order, c.cell.name, v.name }), c.span);
try l.endNow(c.temps.items, c.span);
return result;
},
}
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = try l.diagnosticTyText(t) }});
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
}
/// `let (old, exchanged) = atomic.compare_exchange(c, expected, desired,
@@ -5397,7 +5439,7 @@ const ReferenceCalls = struct {
return .{ .name = "", .ty = .void };
}
if (try l.concurrencyCall(e, p, args)) |v| return v;
if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args);
if (std.mem.startsWith(u8, p, "atomic.")) return ReferenceAtomics.call(l, e, p, args);
if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty;
@@ -8610,3 +8652,212 @@ test "public consuming builtin lowering propagates OOM on success and rejection"
}
}
}
// Independent pre-continuation atomic operand descent; leaf/place/emission helpers remain shared.
const ReferenceAtomics = struct {
fn call(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
const eq = std.mem.eql;
if (eq(u8, p, "atomic.new")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
const v = try ReferenceOperands.expr(l, args[0], null);
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
}
if (eq(u8, p, "atomic.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
const c = try ReferenceCalls.consuming(l, args[0], null);
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }});
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
}
if (eq(u8, p, "atomic.fence")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(u8, p, "atomic.compare_exchange"))
return l.invalid(.invalid_unpack, e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
const c = try l.cellOperand(args[0], &temps);
const t = c.ty.inner().?.inner().?;
const ord = try l.ordering(args[want - 1]);
if (eq(u8, p, "atomic.load")) {
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
}
const operand = try ReferenceOperands.expr(l, args[1], t);
try l.checkOperandTy(args[1].span, operand.ty, t);
if (eq(u8, p, "atomic.store")) {
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = try l.diagnosticTyText(t) }});
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
}
};
fn atomicTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer {
var l = try fieldTestLowerer(a, m, span);
const cell = try l.wrap(.atomic, .{ .int = "i64" });
const boolean = try l.wrap(.atomic, .bool);
try l.bindings.appendSlice(a, &.{
.{ .name = "ac", .value = "integer_cell", .mutable = false, .ty = cell },
.{ .name = "bc", .value = "boolean_cell", .mutable = false, .ty = boolean },
.{ .name = "storage_cell", .value = "integer_cell_storage", .mutable = true, .ty = cell, .kind = .storage },
.{ .name = "mr", .value = "integer_cell_mut", .mutable = false, .ty = try l.wrap(.mut, cell), .kind = .borrow },
.{ .name = "ar", .value = "integer_cell_ref", .mutable = false, .ty = try l.wrap(.ref, cell), .kind = .borrow },
.{ .name = "br", .value = "boolean_cell_ref", .mutable = false, .ty = try l.wrap(.ref, boolean), .kind = .borrow },
});
return l;
}
fn expectAtomicMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void {
var old = try atomicTestLowerer(a, m, e.span);
var current = try atomicTestLowerer(a, m, e.span);
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.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 "atomic continuations match former typing ordering borrowing CFG and errors" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const expressions = [_][]const u8{
"atomic.new(1i64)", "atomic.new(true)", "atomic.new(1)", "atomic.new(1u128)",
"atomic.new()", "atomic.new(unknown, true)", "atomic.new(unknown)", "atomic.new(move o)",
"atomic.take(move ac)", "atomic.take(ac)", "atomic.take(ar)", "atomic.take(move o)",
"atomic.take(atomic.new(- id(1i64)))", "atomic.new(atomic.take(move ac))", "atomic.load(ar, relaxed)", "atomic.load(ref ac, seq_cst)",
"atomic.load(ac, relaxed)", "atomic.load(mut ac, relaxed)", "atomic.load(unknown, unknown)", "atomic.load(ar, unknown)",
"atomic.store(ar, id(n), release)", "atomic.store(ref ac, atomic.take(atomic.new(1i64)), seq_cst)", "atomic.store(ar, unknown, unknown)", "atomic.store(ar, unknown, relaxed)",
"atomic.store(ar, true, relaxed)", "atomic.swap(ref ac, id(n), acq_rel)", "atomic.add.wrap(ar, 1, relaxed)", "atomic.sub.wrap(ref ac, 1i64, seq_cst)",
"atomic.and(br, true and bool_id(false), relaxed)", "atomic.or(ref bc, bool_id(true), relaxed)", "atomic.xor(br, false, seq_cst)", "atomic.add.wrap(br, true, relaxed)",
"atomic.add.wrap(br, unknown, unknown)", "atomic.store(ar, stop(b\"xy\"), relaxed)", "atomic.new(void_call(b\"xy\"))", "atomic.take(stop(b\"xy\"))",
"atomic.fence(seq_cst)", "atomic.fence(unknown)", "atomic.compare_exchange(unknown)", "atomic.load(p, relaxed)",
"atomic.load(mr, relaxed)", "atomic.load(ref storage_cell, seq_cst)", "atomic.and(ar, 1i64, relaxed)", "atomic.or(ar, 2i64, seq_cst)",
"atomic.xor(ref ac, 3i64, acq_rel)", "atomic.add.wrap(br, 1i64, relaxed)", "atomic.swap(ar, 1i64)", "atomic.take(unknown, false)",
"atomic.store(ref ac, unknown, unknown)",
};
const forms = [_][]const u8{ "{s}", "id({s})", "atomic.new({s})", "atomic.take({s})", "atomic.swap(ar, {s}, seq_cst)", "atomic.store(ref ac, {s}, relaxed)", "- ({s})", "not ({s})", "true and ({s})", "({s}) or false", "[{s}]", "Box {{ n: {s} }}.n" };
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}; }}", .{ fieldTestDeclarations, 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 = "i64" } }) |want| try expectAtomicMatches(a, parsed.ok, e, want);
};
}
test "deep alternating atomic new take and updates avoid native operand descent" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok;
const count = 32_768;
const create = try consumingTestCallee(a, "atomic.new");
const take = try consumingTestCallee(a, "atomic.take");
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } };
for (0..count) |i| {
const new_args = try a.alloc(ast.Expr, 1);
new_args[0] = e;
const take_args = try a.alloc(ast.Expr, 1);
const new_span = unaryTestSpan(@intCast(2 * i + 1));
const take_span = unaryTestSpan(@intCast(2 * i + 2));
take_args[0] = .{ .span = new_span, .kind = .{ .call = .{ .callee = create, .type_arg = null, .args = new_args } } };
e = .{ .span = take_span, .kind = .{ .call = .{ .callee = take, .type_arg = null, .args = take_args } } };
}
var l = try atomicTestLowerer(a, m, e.span);
const v = try l.expr(e, null);
try std.testing.expect(v.ty.eql(.{ .int = "i64" }));
const insts = l.blocks.items[0].insts.items;
try std.testing.expectEqual(2 * count + 1, insts.len);
try std.testing.expectEqual(2 * count + 1, l.counter);
for (0..count) |i| {
try std.testing.expect(std.mem.indexOf(u8, insts[2 * i + 1].text, " = atomic.new ") != null);
try std.testing.expect(std.mem.indexOf(u8, insts[2 * i + 2].text, " = atomic.take ") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(2 * i + 1))), insts[2 * i + 1].span);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(2 * i + 2))), insts[2 * i + 2].span);
}
const swap = try consumingTestCallee(a, "atomic.swap");
const reference: ast.Expr = .{ .span = unaryTestSpan(70_003), .kind = .{ .name = "ar" } };
const order: ast.Expr = .{ .span = unaryTestSpan(70_004), .kind = .{ .name = "seq_cst" } };
e = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } };
for (0..count) |i| {
const args = try a.dupe(ast.Expr, &.{ reference, e, order });
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = swap, .type_arg = null, .args = args } } };
}
l = try atomicTestLowerer(a, m, e.span);
_ = try l.expr(e, null);
try std.testing.expectEqual(count + 1, l.blocks.items[0].insts.items.len);
for (l.blocks.items[0].insts.items[1..], 0..) |inst, i| {
try std.testing.expect(std.mem.indexOf(u8, inst.text, " = atomic.xchg.seq_cst %integer_cell_ref,") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), inst.span);
}
}
test "public atomic continuation OOM preserves failure separation and arena cleanup" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const programs = [_][]const u8{
"module oom\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); let v = atomic.swap(ref ac, atomic.take(atomic.new(atomic.take(atomic.new(1i64)))), seq_cst); atomic.store(ref ac, 2i64, release); return atomic.take(move ac); }\n",
"module oom\nfn main() -> i64 effects [] { return atomic.take(1i64); }\n",
"module oom\nfn main() -> i64 effects [] { let ac = atomic.new(0i64); return atomic.take(ac); }\n",
"module oom\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); return atomic.swap(ref ac, unknown, invalid); }\n",
};
for (programs, 0..) |program, 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 (program_index == 0) try std.testing.expect(baseline == .ok) else {
try std.testing.expect(baseline == .err);
try std.testing.expectEqualStrings(switch (program_index) {
1 => "E7005",
2 => "E7003",
else => "E7006",
}, 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;
}
}
}
}
}
+74
View File
@@ -799,6 +799,80 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
error['code'], str(formatted), text[:at].count('\n') + 1, at - text.rfind('\n', 0, at)), formatted_error
print(f'consuming builtin rejection depth: {operation}', flush=True)
# Atomic operand continuations preserve scalar construction/extraction,
# cell/order-before-value priority and temporary shared-loan lifetimes.
for kind in ('atomic-pair', 'atomic-mixed', 'atomic-swap'):
for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536):
if depth == 32768 and kind != 'atomic-mixed':
continue
path = root / f'{kind}-{depth}.aji'
if kind == 'atomic-pair':
expression = 'atomic.take(atomic.new(' * depth + '42i64' + '))' * depth
program = 'module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\n'
instructions, fuel, value = 2 * depth + 2, 2 * depth + 2, 42
elif kind == 'atomic-mixed':
expression = 'atomic.take(atomic.new(id(- ' * depth + 'id(42i64)' + ')))' * depth
program = 'module depth\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> i64 effects [] { return ' + expression + '; }\n'
instructions, fuel, value = 5 * depth + 4, 6 * depth + 4, 42 if depth % 2 == 0 else -42
else:
expression = 'atomic.swap(ref ac, ' * depth + '42i64' + ', seq_cst)' * depth
program = 'module depth\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); let result = ' + expression + '; return atomic.take(move ac); }\n'
instructions, fuel, value = 3 * depth + 5, 3 * depth + 5, 42 if depth % 2 else 0
path.write_text(program)
limited = kind == 'atomic-mixed' and depth == 65536
checked = cli('check', path, code=1 if limited else 0)
if limited:
error = json.loads(checked)
assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, 327683), error
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == checked
else:
assert checked == b''
lowered = cli('lower', path)
actual = sum(b' = ' in line or line.strip().startswith((b'ret ', b'borrow.end ')) for line in lowered.splitlines())
assert actual == instructions, (kind, depth, actual, instructions)
if depth <= 1024:
result = cli('run', path, '--fuel', fuel)
assert json.loads(result) == {'status': 'returned', 'value': value}
assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', fuel) == result
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
formatted_check = cli('check', formatted, code=1 if limited else 0)
if limited:
assert json.loads(formatted_check)['code'] == 'E5101'
else:
assert formatted_check == b''
assert cli('lower', formatted) == lowered
print(f'atomic operand accepted depth: {kind}', flush=True)
for leaf, code, offset, extra in (
('unknown', 'E7002', 0, {}),
('atomic.new()', 'E7005', 0, {}),
('atomic.new(1u128)', 'E7005', len('atomic.new('), {'found': 'u128'}),
('atomic.take(true)', 'E7005', len('atomic.take('), {'found': 'bool'}),
('atomic.store(ref ac, unknown, invalid)', 'E7006', len('atomic.store(ref ac, unknown, '), {}),
('atomic.store(ref ac, true, seq_cst)', 'E7005', len('atomic.store(ref ac, '), {'expected': 'i64', 'found': 'bool'}),
):
for depth in (16, 1024, 65536):
prefix = 'module depth\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); return '
expression = 'atomic.take(atomic.new(' * depth + leaf + '))' * depth
path = root / f'atomic-operand-reject-{code}-{offset}-{depth}-{len(leaf)}.aji'
path.write_text(prefix + expression + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
col = len(prefix.split('\n')[-1]) + len('atomic.take(atomic.new(') * depth + offset + 1
assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 2, col), error
for key, wanted in extra.items():
assert error[key] == wanted, error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'atomic operand error priority: {leaf}', flush=True)
# Block/control callbacks remain native. Their existing shallow/deeper
# syntax must retain its capacity while expression dispatch is moved out
# of the native stack, including explicit-return callback re-entry.