From 7ccded2b59212751b620c45952dd0821bfe691b4 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 11 Oct 2026 18:41:13 +0300 Subject: [PATCH] cli: lower mutex value operands iteratively --- docs/design/open-questions.md | 5 +- docs/design/source-expression-depth-audit.md | 67 ++++++- docs/plan/phase-6-source-language.md | 17 +- src/frontend/lower.zig | 199 +++++++++++++++++-- tests/hosted/source_expression_depth.py | 81 ++++++++ 5 files changed, 348 insertions(+), 21 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 3edf949..ef05020 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -563,4 +563,7 @@ The [atomic operand increment](source-expression-depth-audit.md#atomic-operand-c The [task.join increment](source-expression-depth-audit.md#task-join-operand-continuations) preserves consuming/type/result/void rules, spans, loans and host OOM through the shared driver. Build/units/format, exact ordinary conformance coverage, public check/lower parity, lifetime/related/CFG checks and 522 focused CLI checks pass, with valid call operands and exact rejections through 65,536 and runtime/fuel through 1,024. Read-only Claude core/follow-up reviews found no production or fixture defect. At that checkpoint a valid 16-level alternating join/spawn probe still aborted at 256 before/after, confirming the next spawn-argument callback. Other callbacks/walks, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change. -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. Nested mutex.make/take still aborts at 256/1,024 before/after and is 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 [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. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index ae37f8a..21d0d2f 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -939,10 +939,67 @@ or fixture defect, relying on the core review plus the final diff, driver and generic-worker code; it did not re-audit every consumer or run tests. Its exit, formatted-check bound and schedule-seed wording suggestions are integrated. -The next finite probe, nested `mutex.take(mutex.make(...))`, accepts at 16 -but aborts at 256/1,024 with no JSON before and after this spawn repair. +At this spawn checkpoint, nested `mutex.take(mutex.make(...))` accepts at 16 +but aborts at 256/1,024 with no JSON before and after the spawn repair. `task-spawn-next-probes.json` and matching raw stdout/stderr retain the evidence. -Mutex operands are the next confirmed callback repair; other walks remain open. +Mutex operands were the next confirmed callback repair; other walks remained open. + +## Mutex make/take operand continuations + +Mutex.make/take now use the shared consuming driver (spec 15 §7; spec 04 +§40), preserving arity, explicit-move, no-hint operand descent, void/never +content rejection, element constraints and input-span type errors, followed +by unchanged wrapping/result names/emission. No-live-borrow rules remain +verifier-owned (E2101; E4101 for a live task loan); make is unlocked with no +allocation and take has no unlock/destructor. No semantic/effect/feature/ +AIR/bundle/limit/runtime/scheduler change. Work states keep arena lifetime. + +The copied former `ReferenceMutex` uses recursive oracle consuming descent, +sharing leaf/place/type/emission helpers. Shallow comparisons cover 36 expressions × 11 wrappers (396 forms), +each under three hints, including borrowed/owning/aggregate/nonvalue operands, moves, +CFG and error priority. New-driver tests cover 32,768 make/take pairs with +exact operation spans and a deep unknown leaf emitting nothing. Six public +accepted/rejected recovering/persistent OOM sweeps preserve host errors, +absence of partial AIR and actual backing cleanup on arena destruction. + +Build/units/format pass. All 310 focused CLI checks complete: scalar check +through 65,536; mixed id/negation check through 32,768 then existing E5101 at +65,536 (327683 main instructions, 327684 whole-module). Lower/fmt exact AIR +parity reaches 65,536; formatted accepted checks repeat only through 1,024. +Quantum-one/seed-7 source/AIR runtime and exact fuel boundaries reach 1,024, +without scheduler records because these operations are not scheduling points. +Eight rejected families preserve code/fields/positions and identical +check/lower/run/report/explore JSON, plus formatted positions, through 65,536. +Existing valid `source/linear/mutex.aji` and rejected +`source/inferred_content/mutex_void.aji` retain their contracts. Lifetime, +related-position and CFG suites pass (188/409/146), and all 1,793 ordinary +conformance files have exact successful coverage. This includes existing +`source/layer8/reject/take_while_borrowed.aji`, its E2101 rejection twin and +multi-task mutex examples; this increment adds no new mutex stress experiment. +Frozen public check/lower parity passes (1,423/506, byte-exact) over +`tests/conformance/**/*.aji`; `task-mutex-public-parity.json/.log` record it. +Read-only Claude core review found no +production or fixture defect; final read-only follow-up agrees after reading +the final diff, current code and listed evidence. Neither review ran tests, +proved every remaining path or independently counted every gate. Final +follow-up documentation suggestions are integrated. Its filename +collision observation is corrected with distinct leaf-based names; the +48-check two-family subset passes after that filename-only change. + +The shallow oracle compares value/error, problem/unimplemented, blocks, +allocations/constants/bindings, counter/current block, feature-use set, linear and +constant flags and borrow-parent mappings; other Lowerer state is unverified. +It covers return-expression fixtures, not every statement context. Deep unit +spans/errors test only the new scalar driver; id/negation alternation is CLI +coverage. OOM sweeps compare failure-free result tags, with baseline codes +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 +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` syntax and was corrected before this failure claim. ## Remaining work @@ -958,7 +1015,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 callbacks independently abort at 256/1,024 before and after the spawn 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, 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 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 @@ -967,5 +1024,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 and task.spawn +The struct/value-field, array, enum-payload, task.join, task.spawn and mutex increments have the scoped reviews recorded above. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 1407e2d..bdcf9ed 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -778,7 +778,22 @@ E5101 at 65,536. Runtime/source-AIR/fuel checks reach 1,024; rejected family positions reach 65,536; formatted accepted checks are repeated only through 1,024. Runtime uses quantum one/seed 7, with extra seeds 0/1 through 16. Read-only Claude core/final follow-up reviews found no production or fixture -defect within their recorded scope. Nested mutex.make/take still aborts at +defect within their recorded scope. At this spawn checkpoint nested mutex.make/take aborts at 256/1,024 before/after and is next. Remaining graph/place/control/liveness and multi-result callbacks keep Q-061 open; no semantic/depth-limit change. Q-060 full GC and Phase 6 exit gates remain open. + +### Mutex make/take operand depth increment + +The [mutex increment](../design/source-expression-depth-audit.md#mutex-maketake-operand-continuations) +preserves consuming/content/type priority, explicit moves, spans, loans, +emission and host OOM with the existing driver. Build/units/format and 310 +focused CLI checks pass; scalar check and original/formatted lower reach +65,536, mixed check reaches 32,768 then existing E5101. Runtime/source-AIR/ +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 +at 1,024 before/after; other callbacks/walks, Q-060 and Phase 6 remain open. +No semantic or depth-limit change. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 17d651f..a2de921 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2448,10 +2448,19 @@ const Lowerer = struct { temps: std.ArrayList([]const u8) = .empty, }; const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool }; - const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy, join } }; + const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy, join, mutex_make, mutex_take } }; const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand, spawn: *SpawnCall }; fn finishConsumingBuiltin(l: *Lowerer, c: *ConsumingBuiltin, o: Value) Error!Value { + if (c.operation == .mutex_make) { + if (o.ty == .void or o.ty == .never) return l.contentPositionError(c.input.span, o.ty); + try l.elementRule(o.ty, c.input.span, "a mutex's content"); + return l.def("m", try l.wrap(.mutex, o.ty), try l.fmt("mutex.make %{s}", .{o.name}), c.span); + } + if (c.operation == .mutex_take) { + if (o.ty != .mutex) return l.fail("E7005", c.input.span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); + return l.def("v", o.ty.mutex.*, try l.fmt("mutex.take %{s}", .{o.name}), c.span); + } if (c.operation == .join) { if (o.ty != .task) return l.fail("E7005", c.input.span, "`task.join` takes a `task`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); const rt = o.ty.task.*; @@ -2543,6 +2552,13 @@ const Lowerer = struct { state.* = .{ .span = e.span, .input = args[0], .operation = .join }; return .{ .consuming_builtin = state }; } + const mutex_make = std.mem.eql(u8, p, "mutex.make"); + if (mutex_make or std.mem.eql(u8, p, "mutex.take")) { + if (args.len != 1) return l.fail("E7005", e.span, if (mutex_make) "`mutex.make` takes the initial value" else "`mutex.take` takes one mutex", &.{}); + const state = try l.arena.create(ConsumingBuiltin); + state.* = .{ .span = e.span, .input = args[0], .operation = if (mutex_make) .mutex_make else .mutex_take }; + return .{ .consuming_builtin = state }; + } if (try l.concurrencyCall(e, p, args)) |v| return .{ .done = v }; if (std.mem.startsWith(u8, p, "atomic.")) return switch (try l.prepareAtomic(e, p, args)) { .done => |v| .{ .done = v }, @@ -3684,7 +3700,7 @@ const Lowerer = struct { } /// Immediate task/channel/graph dispatch; null for other paths. - /// Spawn/join operands use the shared expression driver instead. + /// Spawn/join and mutex make/take operands use the shared expression driver instead. fn concurrencyCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!?Value { const eq = struct { fn f(a: []const u8, b: []const u8) bool { @@ -3746,18 +3762,6 @@ const Lowerer = struct { } if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at")) return l.invalid(.invalid_borrow, e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{}); - if (eq(p, "mutex.make")) { - if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{}); - const v = try l.contentValue(args[0]); - try l.elementRule(v.ty, args[0].span, "a mutex's content"); - return try l.def("m", try l.wrap(.mutex, v.ty), try l.fmt("mutex.make %{s}", .{v.name}), e.span); - } - if (eq(p, "mutex.take")) { - if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{}); - const m = try l.consuming(args[0], null); - if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = try l.diagnosticTyText(m.ty) }}); - return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span); - } if (eq(p, "channel.close_sender")) { if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{}); const tx = try l.consuming(args[0], null); @@ -5477,6 +5481,7 @@ const ReferenceCalls = struct { } if (std.mem.eql(u8, p, "task.spawn")) return ReferenceTaskSpawn.call(l, e, args); if (std.mem.eql(u8, p, "task.join")) return ReferenceTaskJoin.call(l, e, args); + if (std.mem.eql(u8, p, "mutex.make") or std.mem.eql(u8, p, "mutex.take")) return ReferenceMutex.call(l, e, p, args); if (try l.concurrencyCall(e, p, args)) |v| return v; if (std.mem.startsWith(u8, p, "atomic.")) return ReferenceAtomics.call(l, e, p, args); if (authority.intrinsicIndex(p)) |ix| { @@ -9276,3 +9281,169 @@ test "public spawn continuations propagate OOM without partial AIR and free back } } } + +// Copied former mutex descent; leaf/place/type/emission helpers remain shared. +const ReferenceMutex = struct { + fn call(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value { + if (std.mem.eql(u8, p, "mutex.make")) { + if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{}); + const v = try ReferenceCalls.consuming(l, args[0], null); + if (v.ty == .void or v.ty == .never) return l.contentPositionError(args[0].span, v.ty); + try l.elementRule(v.ty, args[0].span, "a mutex's content"); + return try l.def("m", try l.wrap(.mutex, v.ty), try l.fmt("mutex.make %{s}", .{v.name}), e.span); + } + if (std.mem.eql(u8, p, "mutex.take")) { + if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{}); + const m = try ReferenceCalls.consuming(l, args[0], null); + if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = try l.diagnosticTyText(m.ty) }}); + return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span); + } + unreachable; + } +}; + +fn mutexTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer { + var l = try consumingTestLowerer(a, m, span); + const integer: Ty = .{ .int = "i64" }; + try l.bindings.appendSlice(a, &.{ + .{ .name = "mx", .value = "mutex_input", .mutable = false, .ty = try l.wrap(.mutex, integer) }, + .{ .name = "mo", .value = "mutex_owner", .mutable = false, .ty = try l.wrap(.mutex, try l.wrap(.own, integer)) }, + .{ .name = "mb", .value = "mutex_bool", .mutable = false, .ty = try l.wrap(.mutex, .bool) }, + }); + return l; +} +fn expectMutexMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void { + var old = try mutexTestLowerer(a, m, e.span); + var current = try mutexTestLowerer(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 "mutex continuations match former consumption content and diagnostic priority" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "mutex.make(1i64)", "mutex.make(n)", "mutex.make(true and bool_id(false))", "mutex.make(id(n))", + "mutex.make(move o)", "mutex.make(o)", "mutex.make(move ob)", "mutex.make(p)", + "mutex.make(ref n)", "mutex.make(b\"xy\")", "mutex.make(Box { n: 1i64 })", "mutex.make([1i64, 2i64])", + "mutex.make(void_call(b\"xy\"))", "mutex.make(stop(b\"xy\"))", "mutex.make(unknown)", "mutex.make()", + "mutex.make(unknown, ref n)", "mutex.take()", "mutex.take(unknown, true)", "mutex.take(unknown)", + "mutex.take(mx)", "mutex.take(move mx)", "mutex.take(move mo)", "mutex.take(move mb)", + "mutex.take(1i64)", "mutex.take(p)", "mutex.take(ref n)", "mutex.take(void_call(b\"xy\"))", + "mutex.take(stop(b\"xy\"))", "mutex.take(mutex.make(1i64))", "mutex.make(mutex.take(move mx))", "mutex.take(mutex.make({ let n: i64 = 3i64; id(n) }))", + "mutex.make(if true { 1i64 } else { 2i64 })", "mutex.make(move r)", "mutex.make(move sc)", "mutex.make(move t)", + }; + const forms = [_][]const u8{ "{s}", "mutex.take({s})", "mutex.make({s})", "id({s})", "own.free({s})", "not ({s})", "- ({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 expectMutexMatches(a, parsed.ok, e, want); + }; +} + +test "deep mutex make take preserves result instruction spans and error prefixes" { + 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 make = try consumingTestCallee(a, "mutex.make"); + const take = try consumingTestCallee(a, "mutex.take"); + const count = 32_768; + for ([_]bool{ false, true }) |unknown| { + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = if (unknown) .{ .name = "unknown" } else .{ .int = .{ .text = "42i64" } } }; + for (0..count) |i| { + const made: ast.Expr = .{ .span = unaryTestSpan(@intCast(2 * i + 1)), .kind = .{ .call = .{ .callee = make, .type_arg = null, .args = try a.dupe(ast.Expr, &.{e}) } } }; + const args = try a.dupe(ast.Expr, &.{made}); + e = .{ .span = unaryTestSpan(@intCast(2 * i + 2)), .kind = .{ .call = .{ .callee = take, .type_arg = null, .args = args } } }; + } + var l = try mutexTestLowerer(a, m, e.span); + const counter = l.counter; + if (unknown) { + try std.testing.expectError(error.Lower, l.expr(e, null)); + try std.testing.expectEqualStrings("E7002", l.problem.?.code); + try std.testing.expectEqualDeep(unaryTestSpan(90_000), l.problem.?.span); + try std.testing.expectEqual(@as(usize, 0), l.blocks.items[0].insts.items.len); + try std.testing.expectEqual(counter, l.counter); + } else { + 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(counter + insts.len, l.counter); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(90_000)), insts[0].span); + for (0..count) |i| { + try std.testing.expect(std.mem.indexOf(u8, insts[2 * i + 1].text, " = mutex.make %") != null); + try std.testing.expect(std.mem.indexOf(u8, insts[2 * i + 2].text, " = mutex.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); + } + } + } +} + +test "public mutex continuations propagate host OOM and free arena backing" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module oom\nfn main() -> i64 effects [] { return mutex.take(mutex.make(mutex.take(mutex.make(42i64)))); }\n", + "module oom\nfn main() -> i64 effects [] { let m = mutex.make(42i64); { ref r = m; } return mutex.take(move m); }\n", + "module oom\nfn main() -> i64 effects [] { return mutex.take(mutex.make(unknown)); }\n", + "module oom\nfn main() -> i64 effects [] { let m = mutex.make(42i64); return mutex.take(m); }\n", + "module oom\nfn empty() -> void effects [] {}\nfn main() -> i64 effects [] { return mutex.take(mutex.make(empty())); }\n", + "module oom\nfn bad(p: ref) -> void effects [] { let m = mutex.make(p); trap; }\nfn main() -> i64 effects [] { return 0i64; }\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", + 3 => "E7003", + 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; + } + } + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index af477ee..008b02e 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -1095,4 +1095,85 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert (trapped['status'], trapped['code'], trapped['kind'], trapped['inst']) == ( 'trapped', 'T0003', 'trap.overflow', 2), trapped + # Mutex operands share consuming continuations; element/loan rules stay unchanged. + for mixed in (False, True): + for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536): + if depth == 32768 and not mixed: + continue + opening = 'mutex.take(mutex.make(id(- ' if mixed else 'mutex.take(mutex.make(' + expression = opening * depth + ('id(42i64)' if mixed else '42i64') + (')))' if mixed else '))') * depth + worker = 'fn id(x: i64) -> i64 effects [] { x }\n' if mixed else '' + path = root / f'mutex-operand-{mixed}-{depth}.aji' + path.write_text('module depth\n' + worker + 'fn main() -> i64 effects [] { return ' + expression + '; }\n') + instructions, fuel = (5 * depth + 4, 6 * depth + 4) if mixed else (2 * depth + 2, 2 * depth + 2) + limited = 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((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith(b'ret') for line in lowered.splitlines()) + assert actual == instructions, (mixed, depth, actual, instructions) + if depth <= 1024: + record = {'status': 'returned', 'value': 42 if depth % 2 == 0 or not mixed else -42} + options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) + result = cli('run', path, *options) + assert json.loads(result) == record, result + 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, *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 + if depth <= 1024: + assert cli('check', formatted) == b'' + print(f'mutex operand accepted depth: mixed={mixed}', flush=True) + + for leaf, code, extra in ( + ('unknown', 'E7002', {}), + ('p', 'E7005', {'found': 'ref'}), + ('m', 'E7003', {'suggestion': 'move m'}), + ('empty()', 'E7005', {'position': 'member', 'type_constructor': 'void'}), + ('stop()', 'E7005', {'position': 'member', 'type_constructor': 'never'}), + ('mutex.take(true)', 'E7005', {'found': 'bool'}), + ('mutex.take(unknown, ref n)', 'E7005', {}), + ('mutex.make(unknown, ref n)', 'E7005', {}), + ): + for depth in (16, 1024, 65536): + prefix = 'module depth\nfn empty() -> void effects [] {}\nfn stop() -> never effects [] { trap; }\nfn main() -> i64 effects [] { var n: i64 = 1i64; let m = mutex.make(1i64); ref p = n; return ' + opening = 'mutex.take(mutex.make(' + leaf_name = re.sub(r'[^A-Za-z0-9]+', '-', leaf).strip('-') + path = root / f'mutex-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) + offset = len('mutex.take(') if leaf == 'mutex.take(true)' else 0 + assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 4, 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() + if leaf in ('m', 'p'): + pos = list(re.finditer(r'(?