Phase 3: channels, mutex, select and cancellation points (RFC 0012)

- features cancellation, channels, sync supported
- AIR model/parser/printer: shield, sender<T>, receiver<T>, mutex<T>,
  guard<T>; task.check_cancel, task.join.cancel, task.shield.*,
  channel.*, select (bracketed arms), mutex.*
- verifier: arities (E5002), element rules (E4001/E1001, E0006
  channel_transfer), guard_transfer gating, task.wait effect (gated for
  task.join by cancellation), per-edge consumption with values and
  handles returned as block parameters, loans moved to the handle on
  task.join.cancel's cancelled edge, shield order (E4305), guard
  children (E2102), critical-section rule (E4304)
- interpreter: waiting-operation rule (ready, else cancelled if
  observable, else wait), shield depth, bounded and rendezvous channels
  with FIFO offers, drain-then-close receiver, budget release at the
  last close, select with seeded draw among ready arms, mutex wakeups;
  schedule record also after a select draw
- report counts task.spawn, task.wait and channel allocations
- spec erratum: mutex<T> is linear (format 0 has no droppable
  move-only class)
- 30 new conformance tests (10 run with schedules, 4 accept, 16
  reject); 6000-run schedule stress and 4350 mutants without failure
This commit is contained in:
dev committed 2026-10-04 16:49:37 +03:00
1 parent b82bc35c5f
commit aaf32b6853
45 files changed
+2077 -43

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ pub const registry = [_]Feature{
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "tasks", "unsafe" };
pub const supported = [_][]const u8{ "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const Reason = enum {
unknown_feature,
+111 -10
View File
@@ -86,6 +86,14 @@ pub const Type = union(enum) {
// Feature `tasks` (spec 04 §33).
scope,
task: *const Type,
// Feature `cancellation` (spec 04 §37).
shield,
// Feature `channels` (spec 04 §38).
sender: *const Type,
receiver: *const Type,
// Feature `sync` (spec 04 §40).
mutex: *const Type,
guard: *const Type,
pub const Array = struct { elem: Type, len: u64 };
@@ -94,8 +102,8 @@ pub const Type = union(enum) {
return switch (a) {
.int => |x| b.int == x,
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.eql(b.inner().?),
.region, .scope => true,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(b.inner().?),
.region, .scope, .shield => true,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
.builtin => |e| b.builtin == e,
@@ -107,7 +115,7 @@ pub const Type = union(enum) {
/// Element or pointee type of storage, borrow and slice types.
pub fn inner(t: Type) ?Type {
return switch (t) {
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.*,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -124,14 +132,20 @@ pub const Type = union(enum) {
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
pub fn isLinear(t: Type) bool {
return switch (t) {
.resource, .own, .own_array, .region, .scope, .task => true,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => true,
else => false,
};
}
/// Function-bound types (spec 04 §33.1): never parameters, results or members.
/// Function-bound types (spec 04 §33.1, §37.3): never parameters, results
/// or members. `guard<T>` is function-bound too, under its own feature.
pub fn isTaskBound(t: Type) bool {
return t == .scope or t == .task;
return t == .scope or t == .task or t == .shield;
}
/// Endpoint types of the feature `channels`.
pub fn isEndpoint(t: Type) bool {
return t == .sender or t == .receiver;
}
pub fn isMutBorrow(t: Type) bool {
@@ -147,7 +161,7 @@ pub const Type = union(enum) {
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task => false,
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => false,
else => true,
};
}
@@ -281,16 +295,51 @@ pub const Op = union(enum) {
task_cancel: ValueId,
task_cancelled,
task_scope_end: ValueId,
// Feature `cancellation` (spec 04 §37).
task_check_cancel: struct { ok: u32, cancelled: u32 },
task_join_cancel: struct { task: ValueId, ok: u32, cancelled: u32 },
task_shield_begin,
task_shield_end: ValueId,
// Feature `channels` (spec 04 §38–§39).
channel_make: struct { elem: Type, cap: ValueId, mem: ValueId, ok: u32, err: u32 },
channel_dup: ValueId,
channel_send: struct { sender: ValueId, value: ValueId, ok: u32, closed: u32, cancelled: u32 },
channel_recv: struct { receiver: ValueId, ok: u32, closed: u32, cancelled: u32 },
channel_close_sender: ValueId,
channel_close_receiver: struct { receiver: ValueId, ok: u32, pending: u32 },
select: struct { arms: []const SelectArm, cancelled: u32 },
// Feature `sync` (spec 04 §40).
mutex_make: ValueId,
mutex_take: ValueId,
mutex_lock: struct { mutex: ValueId, ok: u32, cancelled: u32 },
mutex_borrow: ValueId,
mutex_unlock: ValueId,
ret: ?ValueId,
trap,
pub const Case = struct { bits: u128, target: Target, span: Span };
pub const Arm = struct { variant: u32, block: u32, span: Span };
/// A `select` arm (spec 04 §39): `value` is set for send arms.
pub const SelectArm = struct { endpoint: ValueId, value: ?ValueId, ok: u32, closed: u32, span: Span };
/// Values named by send arms, distinct, in order of first appearance
/// (the set `V` of spec 04 §39). Writes into `buf`, returns the prefix.
pub fn selectValues(arms: []const SelectArm, buf: []ValueId) []ValueId {
var n: usize = 0;
for (arms) |a| if (a.value) |v| {
if (std.mem.indexOfScalar(ValueId, buf[0..n], v) == null) {
buf[n] = v;
n += 1;
}
};
return buf[0..n];
}
pub fn isTerminator(op: Op) bool {
return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
.own_new, .own_array, .region_create, .region_new, .region_array => true,
.task_check_cancel, .task_join_cancel, .channel_make, .channel_send, .channel_recv, .channel_close_receiver, .select, .mutex_lock => true,
.intrinsic => |x| x.ok != null,
else => false,
};
@@ -430,7 +479,24 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.cap);
},
.own_take, .own_free, .region_reset, .region_destroy, .task_join, .task_cancel, .task_scope_end => |v| f(ctx, v),
.task_scope_begin, .task_cancelled => {},
.task_scope_begin, .task_cancelled, .task_check_cancel, .task_shield_begin => {},
.task_shield_end, .channel_dup, .channel_close_sender, .mutex_make, .mutex_take, .mutex_borrow, .mutex_unlock => |v| f(ctx, v),
.task_join_cancel => |x| f(ctx, x.task),
.channel_make => |x| {
f(ctx, x.cap);
f(ctx, x.mem);
},
.channel_send => |x| {
f(ctx, x.sender);
f(ctx, x.value);
},
.channel_recv => |x| f(ctx, x.receiver),
.channel_close_receiver => |x| f(ctx, x.receiver),
.select => |x| for (x.arms) |a| {
f(ctx, a.endpoint);
if (a.value) |v| f(ctx, v);
},
.mutex_lock => |x| f(ctx, x.mutex),
.task_spawn => |x| {
f(ctx, x.scope);
for (x.args) |v| f(ctx, v);
@@ -487,7 +553,7 @@ pub fn allocTargets(op: Op) ?struct { ok: u32, err: u32 } {
};
}
pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !void {
pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.mem.Allocator.Error!void {
switch (op) {
.br => |t| try buf.append(gpa, t.block),
.cbr => |x| {
@@ -514,10 +580,45 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
},
else => {},
else => for (try waitTargets(op, gpa)) |t| try buf.append(gpa, t.block),
}
}
/// A target of a terminator of the features `cancellation`, `channels` and
/// `sync`, with the role of its edge.
pub const WaitTarget = struct {
block: u32,
role: Role,
/// Index of the `select` arm, 0 otherwise.
arm: u32 = 0,
pub const Role = enum { ok, err, closed, cancelled, pending };
};
/// Targets of the waiting and channel terminators, in source order; empty
/// for every other instruction.
pub fn waitTargets(op: Op, gpa: std.mem.Allocator) ![]const WaitTarget {
return switch (op) {
.task_check_cancel => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.cancelled, .role = .cancelled } }),
.task_join_cancel => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.cancelled, .role = .cancelled } }),
.channel_make => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.err, .role = .err } }),
.channel_send => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.closed, .role = .closed }, .{ .block = x.cancelled, .role = .cancelled } }),
.channel_recv => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.closed, .role = .closed }, .{ .block = x.cancelled, .role = .cancelled } }),
.channel_close_receiver => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.pending, .role = .pending } }),
.mutex_lock => |x| gpa.dupe(WaitTarget, &.{ .{ .block = x.ok, .role = .ok }, .{ .block = x.cancelled, .role = .cancelled } }),
.select => |x| blk: {
const out = try gpa.alloc(WaitTarget, x.arms.len * 2 + 1);
for (x.arms, 0..) |arm, i| {
out[2 * i] = .{ .block = arm.ok, .role = .ok, .arm = @intCast(i) };
out[2 * i + 1] = .{ .block = arm.closed, .role = .closed, .arm = @intCast(i) };
}
out[out.len - 1] = .{ .block = x.cancelled, .role = .cancelled };
break :blk out;
},
else => &.{},
};
}
test "IntType host types" {
try std.testing.expect(IntType.Zig(.i8) == i8);
try std.testing.expect(IntType.Zig(.usize) == u64);
+128 -3
View File
@@ -503,6 +503,10 @@ const Parser = struct {
try p.requireFeature("tasks", t.span, t.text);
return .scope;
}
if (eql(t.text, "shield")) {
try p.requireFeature("cancellation", t.span, t.text);
return .shield;
}
if (eql(t.text, "region")) {
try p.requireFeature("regions", t.span, t.text);
return .region;
@@ -551,14 +555,26 @@ const Parser = struct {
boxed.* = inner;
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
}
if (eql(t.text, "task")) {
try p.requireFeature("tasks", t.span, "task");
const Wrapper = enum { task, sender, receiver, mutex, guard };
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
try p.requireFeature(switch (which) {
.task => "tasks",
.sender, .receiver => "channels",
.mutex, .guard => "sync",
}, t.span, t.text);
_ = try p.expect(.lt, "`<`");
// Element rules (spec 04 §38.1) are checked by the type stage.
const inner = try p.parseType();
_ = try p.expect(.gt, "`>`");
const boxed = try p.arena.create(air.Type);
boxed.* = inner;
return .{ .task = boxed };
return switch (which) {
.task => .{ .task = boxed },
.sender => .{ .sender = boxed },
.receiver => .{ .receiver = boxed },
.mutex => .{ .mutex = boxed },
.guard => .{ .guard = boxed },
};
}
if (eql(t.text, "cap")) {
try p.requireFeature("capabilities", t.span, "cap");
@@ -613,6 +629,7 @@ const Parser = struct {
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
if (t == .guard) return p.requireFeature("guard_transfer", span, "lock guard as a member");
if (t.isTaskBound()) return p.requireFeature("task_transfer", span, "task handle or scope as a member");
if (t.isLinear()) try p.requireFeature("linear_aggregates", span, "linear value as a member");
}
@@ -650,6 +667,7 @@ const Parser = struct {
const ty_span = p.peek().span;
const ty = try p.parseType();
if (ty.isTaskBound()) try p.requireFeature("task_transfer", ty_span, "task handle or scope as a parameter");
if (ty == .guard) try p.requireFeature("guard_transfer", ty_span, "lock guard as a parameter");
const id = try p.defineValue(v, .{ .param = @intCast(params.items.len) });
try params.append(p.arena, .{ .value = id, .ty = ty });
if (p.peek().tag != .comma) break;
@@ -660,6 +678,7 @@ const Parser = struct {
const ret_span = p.peek().span;
const ret = try p.parseType();
if (ret.isTaskBound()) try p.requireFeature("task_transfer", ret_span, "task handle or scope as a result");
if (ret == .guard) try p.requireFeature("guard_transfer", ret_span, "lock guard as a result");
var ret_from: ?u32 = null;
if (p.atWord("from")) {
const from_tok = p.next();
@@ -974,6 +993,7 @@ const Parser = struct {
}
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
if (try p.parseTaskOp(op_tok)) |top| break :op top;
if (try p.parseCoordinationOp(op_tok)) |cop| break :op cop;
if (eql(op_tok.text, "intrinsic")) {
try p.requireFeature("capabilities", op_tok.span, "intrinsic");
const name = try p.expect(.word, "intrinsic name");
@@ -1001,6 +1021,7 @@ const Parser = struct {
const produces_value = switch (op) {
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
@@ -1056,6 +1077,110 @@ const Parser = struct {
};
}
/// `, <role> -> @block` for each role in order.
fn roles(p: *Parser, comptime names: []const []const u8) Error![names.len]u32 {
var out: [names.len]u32 = undefined;
inline for (names, 0..) |n, i| {
_ = try p.expect(.comma, "`,`");
_ = try p.expectWord(n);
_ = try p.expect(.arrow, "`->`");
out[i] = try p.blockRef();
}
return out;
}
/// Instructions of the features `cancellation`, `channels` and `sync`
/// (spec 04 §37–§40).
fn parseCoordinationOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum {
@"task.check_cancel",
@"task.join.cancel",
@"task.shield.begin",
@"task.shield.end",
@"channel.make",
@"channel.sender.dup",
@"channel.send",
@"channel.recv",
@"channel.close_sender",
@"channel.close_receiver",
select,
@"mutex.make",
@"mutex.take",
@"mutex.lock",
@"mutex.borrow",
@"mutex.unlock",
};
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
try p.requireFeature(if (std.mem.startsWith(u8, op_tok.text, "task.")) "cancellation" else if (std.mem.startsWith(u8, op_tok.text, "mutex.")) "sync" else "channels", op_tok.span, op_tok.text);
switch (name) {
.@"task.check_cancel" => {
const r = try p.roles(&.{ "ok", "cancelled" });
return .{ .task_check_cancel = .{ .ok = r[0], .cancelled = r[1] } };
},
.@"task.join.cancel" => {
const t = try p.useValue();
const r = try p.roles(&.{ "ok", "cancelled" });
return .{ .task_join_cancel = .{ .task = t, .ok = r[0], .cancelled = r[1] } };
},
.@"task.shield.begin" => return .task_shield_begin,
.@"task.shield.end" => return .{ .task_shield_end = try p.useValue() },
.@"channel.make" => {
const elem = try p.parseType();
_ = try p.expect(.comma, "`,`");
const n, const mem = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .channel_make = .{ .elem = elem, .cap = n, .mem = mem, .ok = ok, .err = err } };
},
.@"channel.sender.dup" => return .{ .channel_dup = try p.useValue() },
.@"channel.send" => {
const tx, const v = try p.twoOperands();
const r = try p.roles(&.{ "ok", "closed", "cancelled" });
return .{ .channel_send = .{ .sender = tx, .value = v, .ok = r[0], .closed = r[1], .cancelled = r[2] } };
},
.@"channel.recv" => {
const rx = try p.useValue();
const r = try p.roles(&.{ "ok", "closed", "cancelled" });
return .{ .channel_recv = .{ .receiver = rx, .ok = r[0], .closed = r[1], .cancelled = r[2] } };
},
.@"channel.close_sender" => return .{ .channel_close_sender = try p.useValue() },
.@"channel.close_receiver" => {
const rx = try p.useValue();
const r = try p.roles(&.{ "ok", "pending" });
return .{ .channel_close_receiver = .{ .receiver = rx, .ok = r[0], .pending = r[1] } };
},
.select => {
var arms: std.ArrayList(air.Op.SelectArm) = .empty;
while (p.peek().tag == .l_bracket) {
const span = p.next().span;
const kind = try p.expect(.word, "`recv` or `send`");
const endpoint = try p.useValue();
var v: ?air.ValueId = null;
if (eql(kind.text, "send")) {
_ = try p.expect(.comma, "`,`");
v = try p.useValue();
} else if (!eql(kind.text, "recv")) return p.fail(kind, "`recv` or `send`");
const r = try p.roles(&.{ "ok", "closed" });
_ = try p.expect(.r_bracket, "`]`");
_ = try p.expect(.comma, "`,`");
try arms.append(p.arena, .{ .endpoint = endpoint, .value = v, .ok = r[0], .closed = r[1], .span = span });
}
if (arms.items.len == 0) return p.fail(p.peek(), "a select arm `[recv …]` or `[send …]`");
_ = try p.expectWord("cancelled");
_ = try p.expect(.arrow, "`->`");
return .{ .select = .{ .arms = arms.items, .cancelled = try p.blockRef() } };
},
.@"mutex.make" => return .{ .mutex_make = try p.useValue() },
.@"mutex.take" => return .{ .mutex_take = try p.useValue() },
.@"mutex.lock" => {
const mr = try p.useValue();
const r = try p.roles(&.{ "ok", "cancelled" });
return .{ .mutex_lock = .{ .mutex = mr, .ok = r[0], .cancelled = r[1] } };
},
.@"mutex.borrow" => return .{ .mutex_borrow = try p.useValue() },
.@"mutex.unlock" => return .{ .mutex_unlock = try p.useValue() },
}
}
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
+51 -2
View File
@@ -122,11 +122,12 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
},
.region => try w.writeAll("region"),
.scope => try w.writeAll("scope"),
.task => |inner| {
try w.writeAll("task<");
.task, .sender, .receiver, .mutex, .guard => |inner| {
try w.print("{s}<", .{@tagName(t)});
try printType(m, inner.*, w);
try w.writeByte('>');
},
.shield => try w.writeAll("shield"),
.bool, .void, .never => try w.writeAll(@tagName(t)),
}
}
@@ -348,6 +349,54 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
.task_cancelled => try w.writeAll("task.cancelled"),
.task_scope_end => |v| try one(f, w, "task.scope.end", v),
.region_destroy => |v| try one(f, w, "region.destroy", v),
.task_check_cancel => |x| try w.print("task.check_cancel, ok -> @{s}, cancelled -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.cancelled].name }),
.task_join_cancel => |x| {
try one(f, w, "task.join.cancel", x.task);
try w.print(", ok -> @{s}, cancelled -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.cancelled].name });
},
.task_shield_begin => try w.writeAll("task.shield.begin"),
.task_shield_end => |v| try one(f, w, "task.shield.end", v),
.channel_make => |x| {
try w.writeAll("channel.make ");
try printType(m, x.elem, w);
try w.writeAll(", ");
try value(f, x.cap, w);
try w.writeAll(", ");
try value(f, x.mem, w);
try okErr(f, w, x.ok, x.err);
},
.channel_dup => |v| try one(f, w, "channel.sender.dup", v),
.channel_send => |x| {
try two(f, w, "channel.send", x.sender, x.value);
try w.print(", ok -> @{s}, closed -> @{s}, cancelled -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.closed].name, f.blocks[x.cancelled].name });
},
.channel_recv => |x| {
try one(f, w, "channel.recv", x.receiver);
try w.print(", ok -> @{s}, closed -> @{s}, cancelled -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.closed].name, f.blocks[x.cancelled].name });
},
.channel_close_sender => |v| try one(f, w, "channel.close_sender", v),
.channel_close_receiver => |x| {
try one(f, w, "channel.close_receiver", x.receiver);
try w.print(", ok -> @{s}, pending -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.pending].name });
},
.select => |x| {
try w.writeAll("select ");
for (x.arms) |a| {
if (a.value) |v| {
try two(f, w, "[send", a.endpoint, v);
} else try one(f, w, "[recv", a.endpoint);
try w.print(", ok -> @{s}, closed -> @{s}], ", .{ f.blocks[a.ok].name, f.blocks[a.closed].name });
}
try w.print("cancelled -> @{s}", .{f.blocks[x.cancelled].name});
},
.mutex_make => |v| try one(f, w, "mutex.make", v),
.mutex_take => |v| try one(f, w, "mutex.take", v),
.mutex_lock => |x| {
try one(f, w, "mutex.lock", x.mutex);
try w.print(", ok -> @{s}, cancelled -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.cancelled].name });
},
.mutex_borrow => |v| try one(f, w, "mutex.borrow", v),
.mutex_unlock => |v| try one(f, w, "mutex.unlock", v),
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w);