cli: lower mutex value operands iteratively

This commit is contained in:
dev committed 2026-10-11 18:41:13 +03:00
1 parent c5d0d09a81
commit 7ccded2b59
5 files changed
+348 -21

No files matched your search

+185 -14
View File
@@ -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<T>`", &.{.{ .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<T>`", &.{.{ .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<T>`", &.{.{ .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<T>`", &.{.{ .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<i64>) -> 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;
}
}
}
}
}