Phase 6A: .aji layer 8 (lock and mutexes, select, shields, cancellation)

- lock ref m as x { … } cancelled { … }: mutex.lock on a ref<mutex<T>>
  (a mutex is borrowed for the lock, a ref binding used as is); ok edge:
  mutex.borrow bound as x; at every normal exit borrow.end x then
  mutex.unlock; the guard is never a source value
- mutex.make/mutex.take; mutex<T> type; ref mr = m lends a mutex
- shield { … }: task.shield.begin/end at every exit (nesting by construction)
- task.check_cancel and task.join_cancel as outcome matches
- select: one borrow per endpoint, send values evaluated first and
  deduplicated, every edge binds its own value then the unsent values;
  bind count E7005, missing outcome E7004
- linear values never get frame storage (borrowed in place)
- liveness: select handled in the read and after walks
- Quick Reference: select edges bind `job` back (ok(x, job), closed(job));
  every Quick Reference example now passes (no PENDING)
- tests: 6 run tests with AIR equivalence (mutex counter, select draw,
  select same value, shield, join_cancel forwarding, cancelled recv), 10
  rejects (E4304 x3, E3001, E2101, E7005 x2, E7004, E3101 x2, E4101)
- spec 15 §7/§9, quick reference, bundle notes, plan
This commit is contained in:
dev committed 2026-10-05 18:02:11 +03:00
1 parent 609b6bf86e
commit 154c39865f
24 files changed
+912 -50

No files matched your search

+283 -35
View File
@@ -20,7 +20,8 @@
//! outcome matches and `or trap`;
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels.
//! 7. task scopes, spawn and join, channels;
//! 8. `lock` and mutexes, `select`, cancellation points, shields.
const std = @import("std");
const ast = @import("ast.zig");
@@ -59,13 +60,18 @@ pub const Ty = union(enum) {
receiver: *const Ty,
/// A task scope (bound by `scope s { … }`, never written as a type).
scope,
/// `mutex<T>`; `guard<T>` is never a source value (the `lock` block).
mutex: *const Ty,
guard: *const Ty,
/// A shield (`shield { … }`, never a source value).
shield,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope => true,
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield => true,
else => false,
};
}
@@ -76,7 +82,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
@@ -86,7 +92,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -278,9 +284,11 @@ const Lowerer = struct {
rest: std.ArrayList(Rest) = .empty,
/// Set by a loop just before lowering its body: the body's `Rest` frame.
pending_loop: ?LoopAst = null,
/// Set by `scope s { … }` just before lowering its body: a binding and an
/// end that belong to the body's own lexical scope.
pending_entry: ?struct { binding: Binding, end: BorrowEnd } = null,
/// Set by `scope`, `shield` and `lock` just before lowering a body:
/// bindings and ends that belong to the body's own lexical scope (ends
/// in creation order; they run innermost first at every normal exit).
pending_bindings: std.ArrayList(Binding) = .empty,
pending_ends: std.ArrayList(BorrowEnd) = .empty,
/// Borrows to end at the end of each open lexical scope (innermost last).
scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty,
/// `local.alloc` instructions; they go first in the entry block.
@@ -311,8 +319,9 @@ const Lowerer = struct {
.never => "never",
.named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| blk: {
@@ -427,7 +436,9 @@ const Lowerer = struct {
.{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
.{ "tasks", &.{ "task.", "task<", ": scope" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<", "select [" } },
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
@@ -498,7 +509,7 @@ const Lowerer = struct {
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try l.typeOf(w.inner.*);
return switch (which) {
@@ -511,6 +522,7 @@ const Lowerer = struct {
.task => l.wrap(.task, in),
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
.mutex => l.wrap(.mutex, in),
};
},
.cap => |k| {
@@ -768,10 +780,11 @@ const Lowerer = struct {
const saved_start = l.scope_binding_start;
l.scope_binding_start = depth;
defer l.scope_binding_start = saved_start;
if (l.pending_entry) |pe| {
l.pending_entry = null;
try l.bindings.append(l.arena, pe.binding);
try l.scopes.items[l.scopes.items.len - 1].append(l.arena, pe.end);
if (l.pending_bindings.items.len != 0 or l.pending_ends.items.len != 0) {
try l.bindings.appendSlice(l.arena, l.pending_bindings.items);
try l.scopes.items[l.scopes.items.len - 1].appendSlice(l.arena, l.pending_ends.items);
l.pending_bindings = .empty;
l.pending_ends = .empty;
}
for (b.stmts, 0..) |s, i| {
if (l.cur == null) return l.fail("E7006", s.span, "unreachable statement", &.{});
@@ -850,7 +863,9 @@ const Lowerer = struct {
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
if (v.ty == .void or v.ty == .never) return l.fail("E7005", x.e.span, "this expression has no value", &.{});
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
if (l.addressable.contains(x.names[0])) {
// Linear values (owners, regions, resources, endpoints, tasks,
// mutexes) are borrowed in place, never moved to frame storage.
if (l.addressable.contains(x.names[0]) and !v.ty.isLinear()) {
const st = try l.storageFor(x.names[0], v.ty, s.span);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage });
@@ -859,7 +874,7 @@ const Lowerer = struct {
.@"var" => |x| {
const ty = try l.typeOf(x.ty);
if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
if (l.addressable.contains(x.name)) {
if (l.addressable.contains(x.name) and !ty.isLinear()) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.consuming(e, ty);
@@ -943,12 +958,19 @@ const Lowerer = struct {
// `scope s { … }`: task.scope.begin, and task.scope.end at every
// normal exit of the block (spec 15 §7).
const sv = try l.def(x.name, .scope, "task.scope.begin", s.span);
l.pending_entry = .{ .binding = .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope }, .end = .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" } };
try l.pending_bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope });
try l.pending_ends.append(l.arena, .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" });
_ = try l.blockBody(x.body);
},
.shield => return l.notYet(s.span, "`shield` (layer 8)"),
.lock => return l.notYet(s.span, "`lock` (layer 8)"),
.select => return l.notYet(s.span, "`select` (layer 8)"),
.shield => |b| {
// `shield { … }`: task.shield.begin, and task.shield.end at every
// normal exit; shields nest by construction (spec 15 §7).
const sh = try l.def("sh", .shield, "task.shield.begin", s.span);
try l.pending_ends.append(l.arena, .{ .name = sh.name, .span = b.span, .op = "task.shield.end" });
_ = try l.blockBody(b);
},
.lock => |x| try l.lockStmt(s, x.place, x.name, x.body, x.cancelled),
.select => |x| try l.selectStmt(s, x),
}
}
@@ -1826,7 +1848,7 @@ const Lowerer = struct {
.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.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.resource, .mutex, .sender, .receiver, .task => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
@@ -2080,7 +2102,7 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver" };
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2169,6 +2191,17 @@ const Lowerer = struct {
try l.endNow(temps.items, e.span);
return v;
}
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.consuming(args[0], null);
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 = l.tyText(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);
@@ -2179,6 +2212,189 @@ const Lowerer = struct {
return null;
}
/// `lock ref m as x { body } cancelled { cb }` (spec 15 §7): `mutex.lock`
/// on a shared borrow of the mutex; on `ok`, `mutex.borrow` of the guard
/// bound as `x: mut<T>`, and at every normal exit of the body
/// `borrow.end x` then `mutex.unlock`. The guard is never a source value.
fn lockStmt(l: *Lowerer, s: ast.Stmt, place: ast.Expr, name: []const u8, body: ast.Block, cancelled: ast.Block) Error!void {
// The mutex: a `ref<mutex<T>>` binding, or a mutex borrowed for the lock.
var temps: std.ArrayList([]const u8) = .empty;
if (place.kind != .name) return l.fail("E7005", place.span, "`lock ref m`: the mutex or a `ref<mutex<T>>` binding, by name", &.{});
const b = l.lookup(place.kind.name) orelse return l.unknown(place.span, place.kind.name);
const mr: Value = switch (b.ty) {
.mutex => blk: {
const v = try l.def(place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), place.span);
try temps.append(l.arena, v.name);
break :blk v;
},
.ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}),
else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}),
};
const elem = mr.ty.ref.mutex.*;
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const before = try l.snapshot();
const locked = try l.newBlock("locked");
const guard = try l.freshName("guard");
try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) });
const canc = try l.newBlock("lock_cancelled");
try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
l.cur = locked;
const x = try l.def(name, try l.wrap(.mut, elem), try l.fmt("mutex.borrow %{s}", .{guard}), s.span);
for (temps.items) |t| try l.pending_ends.append(l.arena, .{ .name = t, .span = body.span });
try l.pending_ends.append(l.arena, .{ .name = guard, .span = body.span, .op = "mutex.unlock" });
try l.pending_ends.append(l.arena, .{ .name = x.name, .span = body.span });
try l.pending_bindings.append(l.arena, .{ .name = name, .mutable = false, .value = x.name, .ty = x.ty, .kind = .borrow });
const bv = try l.blockBody(body);
try ends.append(l.arena, .{ .block = l.cur, .value = bv, .values = try l.snapshot(), .span = body.span });
l.restore(before);
l.cur = canc;
try l.endNow(temps.items, cancelled.span);
const cv = try l.blockBody(cancelled);
try ends.append(l.arena, .{ .block = l.cur, .value = cv, .values = try l.snapshot(), .span = cancelled.span });
_ = try l.mergeArms(s.span, "lock", ends.items, vars, before, "endlock");
}
/// `select { recv(rx) { … } send(tx, v) { … } cancelled(…) => … }`
/// (spec 15 §7, spec 04 §39). Each endpoint is borrowed once for the
/// operation. `V` is the distinct send values in order of first
/// appearance; every edge binds its own value (a received `T`) and then
/// the values of `V` not sent on it.
fn selectStmt(l: *Lowerer, s: ast.Stmt, sel: ast.Select) Error!void {
if (sel.arms.len == 0) return l.fail("E7006", s.span, "a `select` has at least one `recv` or `send` arm", &.{});
const Sent = struct { key: ?[]const u8, v: Value };
var values: std.ArrayList(Sent) = .empty;
const arm_value = try l.arena.alloc(?usize, sel.arms.len);
// Values first (as for an assignment), then the endpoint borrows.
for (sel.arms, arm_value) |a, *av| {
av.* = null;
const ve = a.value orelse continue;
const key: ?[]const u8 = switch (ve.kind) {
.move, .name => |n| n,
else => null,
};
if (key) |k| for (values.items, 0..) |x, i| if (x.key != null and std.mem.eql(u8, x.key.?, k)) {
av.* = i;
break;
};
if (av.* == null) {
const v = try l.consuming(ve, null);
try values.append(l.arena, .{ .key = key, .v = v });
av.* = values.items.len - 1;
}
}
var temps: std.ArrayList([]const u8) = .empty;
const Ep = struct { name: []const u8, v: Value };
var eps: std.ArrayList(Ep) = .empty;
const arm_ep = try l.arena.alloc(Value, sel.arms.len);
for (sel.arms, arm_ep, 0..) |a, *ae, ai| {
const found = for (eps.items) |x| {
if (std.mem.eql(u8, x.name, a.endpoint)) break x.v;
} else null;
ae.* = found orelse blk: {
const ex: ast.Expr = .{ .span = a.span, .kind = .{ .name = a.endpoint } };
const v = try l.endpointOperand(ex, if (a.send) .sender else .receiver, true, &temps);
try eps.append(l.arena, .{ .name = a.endpoint, .v = v });
break :blk v;
};
if (a.send) {
const et = ae.ty.inner().?.sender.*;
try l.checkTy(a.value.?.span, values.items[arm_value[ai].?].v.ty, et);
}
}
// Edges: per arm `ok` and `closed`, then `cancelled`.
const Edge = struct { arm: ?usize, role: []const u8, params: []const Ty, values: []const usize, block: usize = 0 };
var edges: std.ArrayList(Edge) = .empty;
const notSent = struct {
fn f(lw: *Lowerer, n: usize, sent: ?usize) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (0..n) |i| if (sent == null or sent.? != i) try out.append(lw.arena, i);
return out.items;
}
}.f;
for (sel.arms, 0..) |a, i| {
if (a.send) {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = &.{}, .values = try notSent(l, values.items.len, arm_value[i]) });
} else {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = try l.arena.dupe(Ty, &.{arm_ep[i].ty.inner().?.receiver.*}), .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = i, .role = "closed", .params = &.{}, .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = null, .role = "cancelled", .params = &.{}, .values = try notSent(l, values.items.len, null) });
// Every outcome of every arm is matched exactly once.
for (sel.arms) |a| {
for (a.arms, 0..) |arm, k| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.fail("E7006", arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
const c = arm.pattern.kind.ctor;
if (!std.mem.eql(u8, c.name, "ok") and !std.mem.eql(u8, c.name, "closed")) return l.fail("E7002", arm.pattern.span, "a `select` arm has the outcomes `ok` and `closed`; `cancelled` is the `select`'s own arm", &.{.{ .name = "outcome", .value = c.name }});
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
}
for ([_][]const u8{ "ok", "closed" }) |role| {
const covered = for (a.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, role)) break true;
} else false;
if (!covered) return l.fail("E7004", a.span, "the arm does not handle every outcome", &.{.{ .name = "missing", .value = role }});
}
}
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const before = try l.snapshot();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
for (edges.items) |*ed| {
ed.block = try l.newBlock(ed.role);
for (ed.params) |pt| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = pt });
for (ed.values) |vi| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = values.items[vi].v.ty });
}
for (sel.arms, 0..) |a, i| {
const okb = edges.items[2 * i].block;
const clb = edges.items[2 * i + 1].block;
if (a.send) {
try text.appendSlice(l.arena, try l.fmt("[send %{s}, %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, values.items[arm_value[i].?].v.name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
} else {
try text.appendSlice(l.arena, try l.fmt("[recv %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
}
}
try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name}));
try l.term(text.items, s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (edges.items) |ed| {
const binds: []const []const u8, const body: ast.Expr, const pspan: Span = if (ed.arm) |ai| blk: {
const a = sel.arms[ai];
const arm = for (a.arms) |x| {
if (std.mem.eql(u8, x.pattern.kind.ctor.name, ed.role)) break x;
} else unreachable;
break :blk .{ arm.pattern.kind.ctor.binds, arm.body, arm.pattern.span };
} else .{ sel.cancelled_binds, sel.cancelled, sel.span };
const params = l.blocks.items[ed.block].params.items;
if (binds.len != params.len) return l.fail("E7005", pspan, "the edge binds its own value, then the values not sent on it, in order of first appearance", &.{ .{ .name = "outcome", .value = ed.role }, .{ .name = "expected", .value = try l.fmt("{d}", .{params.len}) } });
l.restore(before);
l.cur = ed.block;
try l.endNow(temps.items, pspan);
try l.scopes.append(l.arena, .empty);
for (binds, params) |bn, prm| {
if (std.mem.eql(u8, bn, "_")) continue;
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
old.value = prm.name;
continue;
};
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
}
const v = try l.armBody(body, null);
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, body.span);
_ = l.scopes.pop();
l.bindings.shrinkRetainingCapacity(before.len);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = body.span });
}
_ = try l.mergeArms(s.span, "select", ends.items, vars, before, "endselect");
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
@@ -2262,7 +2478,6 @@ const Lowerer = struct {
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
if (e.kind != .call) return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
if (laterLayer(e.kind.call.callee.*)) return l.notYet(e.span, "this operation (layer 8)");
const path = pathOf(e.kind.call.callee.*) orelse return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
const args = e.kind.call.args;
const want = struct {
@@ -2319,6 +2534,18 @@ const Lowerer = struct {
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "task.check_cancel")) {
try want(l, e.span, args, 0, path);
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
}
if (std.mem.eql(u8, path, "task.join_cancel")) {
try want(l, e.span, args, 1, path);
const t = try l.consuming(args[0], null);
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task<T>`", &.{.{ .name = "found", .value = l.tyText(t.ty) }});
const rt = t.ty.task.*;
const ok: []const Ty = if (rt == .void) &.{} else &.{rt};
return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) };
}
if (std.mem.eql(u8, path, "channel.make")) {
try want(l, e.span, args, 2, path);
const ta = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "`channel.make` names its element type: `channel.make<T>(n, mem)`", &.{});
@@ -2535,14 +2762,6 @@ fn elemOf(t: Ty) ?Ty {
};
}
/// `task.check_cancel`, `task.join_cancel`, `mutex.*`: operations of layer 8.
fn laterLayer(e: ast.Expr) bool {
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return false;
for ([_][]const u8{ "task.check_cancel", "task.join_cancel", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true;
return false;
}
/// The built-in operation named by a callee such as `own.new` or
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
@@ -2551,7 +2770,8 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
"task.join_cancel",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
@@ -2635,8 +2855,7 @@ fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool {
.loop, .shield => |b| blockReads(b, name, skip),
.scope => |x| blockReads(x.body, name, skip),
.lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip),
// Layer 8; until then, assume it reads everything.
.select => true,
.select => |x| selectReads(x, name, skip),
.@"break", .@"continue", .trap => false,
};
}
@@ -2673,6 +2892,15 @@ fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
};
}
fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool {
for (x.arms) |a| {
if (std.mem.eql(u8, a.endpoint, name)) return true;
if (a.value) |v| if (exprReads(v, name, skip)) return true;
for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true;
}
return exprReads(x.cancelled, name, skip);
}
fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool {
if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true;
if (x.@"else") |els| return switch (els) {
@@ -2732,6 +2960,26 @@ const After = struct {
};
}
fn select(w: *After, x: ast.Select) bool {
for (x.arms) |a| {
if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true;
if (a.value) |v| if (w.expr(v)) return true;
}
var bodies: std.ArrayList(ast.Expr) = .empty;
defer bodies.deinit(std.heap.page_allocator);
for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true;
bodies.append(std.heap.page_allocator, x.cancelled) catch return true;
if (w.seen) {
for (bodies.items) |b| if (w.expr(b)) return true;
return false;
}
for (bodies.items) |b| {
const r = w.expr(b);
if (w.seen) return r;
}
return false;
}
fn ifExpr(w: *After, x: ast.If) bool {
if (w.expr(x.cond)) return true;
if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false);
@@ -2782,7 +3030,7 @@ const After = struct {
.shield => |b| w.block(b),
.scope => |x| w.block(x.body),
.lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled),
.select => w.seen,
.select => |x| w.select(x),
.@"break", .@"continue", .trap => false,
};
}