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

+2
View File
@@ -28,6 +28,8 @@ pub const CastMode = module.CastMode;
pub const forEachUse = module.forEachUse;
pub const successors = module.successors;
pub const allocTargets = module.allocTargets;
pub const waitTargets = module.waitTargets;
pub const WaitTarget = module.WaitTarget;
pub const parse = @import("air/parse.zig");
pub const print = @import("air/print.zig");
+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);
+398 -6
View File
@@ -46,6 +46,16 @@ pub const Value = union(enum) {
task: u32,
/// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 },
/// `shield` (the depth lives in the task).
shield,
/// `sender<T>` / `receiver<T>`: index into the machine's channel table.
sender: u32,
receiver: u32,
/// `mutex<T>` and the `guard<T>` that holds it.
mutex: *MutexCell,
guard: *MutexCell,
pub const MutexCell = struct { locked: bool, cell: Cell };
pub const Aggregate = struct {
decl: u32,
@@ -238,8 +248,42 @@ pub const Wait = union(enum) {
join: u32,
accept: u32,
recv: u32,
/// A waiting operation of spec 04 §37.1: the current instruction is
/// re-evaluated when it becomes ready or cancellation becomes observable.
op,
};
/// A rendezvous offer: a task waiting to send or receive on a capacity-0
/// channel, in arm `arm` of its instruction (0 outside `select`).
const Offer = struct { task: u32, arm: u32, value: Value = .void };
/// A channel (spec 04 §38.3).
const Channel = struct {
capacity: u64,
buf: std.ArrayList(Value) = .empty,
head: usize = 0,
senders: u64 = 1,
receiver: enum { open, closing, closed } = .open,
authority: u32,
bytes: u64,
released: bool = false,
/// Waiting rendezvous senders, in the order they began to wait.
send_offers: std.ArrayList(Offer) = .empty,
/// The receiver, while it waits on this rendezvous channel.
recv_offer: ?Offer = null,
fn buffered(c: *const Channel) usize {
return c.buf.items.len - c.head;
}
/// No future value can arrive (`DRAINED` once the buffer is empty).
fn noMore(c: *const Channel) bool {
return c.senders == 0 or c.receiver != .open;
}
};
const Readiness = enum { none, ok, closed };
const Frame = struct { func: u32, vals: []Value, block: u32, inst: u32 };
const Task = struct {
@@ -250,6 +294,10 @@ const Task = struct {
wait: Wait = .{ .join = 0 },
wait_at: Location = .{ .function = "", .block = "", .inst = 0 },
fuel_paid: bool = false,
/// Shield depth (spec 04 §37.3).
shield: u32 = 0,
/// Set by a peer that completed a rendezvous against this waiting task.
delivered: ?struct { arm: u32, value: Value } = null,
};
const Machine = struct {
@@ -273,6 +321,9 @@ const Machine = struct {
host: ?host_mod.Host = null,
owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty,
regions: std.ArrayList(Region) = .empty,
channels: std.ArrayList(Channel) = .empty,
/// A `select` drew among ready arms (spec 04 §36.4).
drew: bool = false,
/// Instructions executed so far.
steps: u64 = 0,
@@ -308,6 +359,12 @@ const Machine = struct {
frame.block = target;
frame.inst = 0;
},
.jump_yield => |target| {
frame.block = target;
frame.inst = 0;
if (try m.schedule()) |o| return o;
continue;
},
.call => |c| {
if (t.frames.items.len >= call_depth_limit) return .{ .trapped = .{ .code = TrapKind.call_depth.code(), .function = here.function, .block = here.block, .inst = here.inst } };
try m.pushFrame(m.current, c.callee, c.args);
@@ -356,9 +413,11 @@ const Machine = struct {
}
/// Whether a waiting task's condition holds now.
fn ready(m: *Machine, w: Wait) bool {
return switch (w) {
.join => |id| m.tasks.items[id].state == .done,
fn ready(m: *Machine, id: u32) bool {
const t = &m.tasks.items[id];
return switch (t.wait) {
.op => t.delivered != null or m.opReady(id) or cancelObservable(t),
.join => |child| m.tasks.items[child].state == .done,
.accept => |hd| m.world.handles.items[hd].listener.pending.items.len != 0,
.recv => |hd| blk: {
const st = m.world.handles.items[hd].stream;
@@ -371,7 +430,7 @@ const Machine = struct {
/// next runnable task. Returns an outcome only at global quiescence.
fn schedule(m: *Machine) !?Outcome {
m.quantum_used = 0;
for (m.tasks.items) |*t| if (t.state == .waiting and m.ready(t.wait)) {
for (m.tasks.items, 0..) |*t, i| if (t.state == .waiting and m.ready(@intCast(i))) {
t.state = .runnable;
};
var runnable: std.ArrayList(u32) = .empty;
@@ -406,6 +465,8 @@ const Machine = struct {
yield,
/// `task.spawn` would exceed the deterministic task limit.
task_limit,
/// Continue at a block; the completed instruction is a scheduling point.
jump_yield: u32,
};
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -514,6 +575,9 @@ const Machine = struct {
vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel };
return .yield;
},
.task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst),
.channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst),
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
@@ -522,6 +586,334 @@ const Machine = struct {
}
}
// ------------------------------------------------------------ waiting, channels, mutex (spec 04 §37–§41)
fn cancelObservable(t: *const Task) bool {
return t.cancel and t.shield == 0;
}
/// The instruction a task is executing.
fn currentOf(m: *Machine, id: u32) struct { air.Function, []Value, air.Inst } {
const fr = m.tasks.items[id].frames.items[m.tasks.items[id].frames.items.len - 1];
const f = m.module.functions[fr.func];
return .{ f, fr.vals, f.blocks[fr.block].insts[fr.inst] };
}
/// Whether the waiting operation of task `id` is ready (spec 04 §38.3).
fn opReady(m: *Machine, id: u32) bool {
_, const vals, const inst = m.currentOf(id);
return switch (inst.op) {
.task_join_cancel => |x| m.tasks.items[vals[x.task].task].state == .done,
.channel_send => |x| m.sendState(endpointOf(vals[x.sender])) != .none,
.channel_recv => |x| m.recvState(endpointOf(vals[x.receiver])) != .none,
.select => |x| for (x.arms) |arm| {
const ch = endpointOf(vals[arm.endpoint]);
if ((if (arm.value == null) m.recvState(ch) else m.sendState(ch)) != .none) break true;
} else false,
.mutex_lock => |x| !vals[x.mutex].mutex.locked,
else => unreachable,
};
}
fn endpointOf(v: Value) u32 {
return switch (v) {
.sender, .receiver => |c| c,
.place => |p| endpointOf(p.cell.value),
else => unreachable,
};
}
fn sendState(m: *Machine, id: u32) Readiness {
const c = &m.channels.items[id];
if (c.receiver != .open) return .closed;
if (c.capacity > 0) return if (c.buffered() < c.capacity) .ok else .none;
return if (c.recv_offer != null) .ok else .none;
}
fn recvState(m: *Machine, id: u32) Readiness {
const c = &m.channels.items[id];
if (c.buffered() > 0) return .ok;
if (c.capacity == 0 and c.receiver == .open and c.send_offers.items.len > 0) return .ok;
return if (c.noMore()) .closed else .none;
}
/// Withdraws every rendezvous offer of task `id`.
fn removeOffers(m: *Machine, id: u32) void {
for (m.channels.items) |*c| {
if (c.recv_offer) |o| if (o.task == id) {
c.recv_offer = null;
};
var i: usize = 0;
while (i < c.send_offers.items.len) {
if (c.send_offers.items[i].task == id) {
_ = c.send_offers.orderedRemove(i);
} else i += 1;
}
}
}
/// Completes the peer of a rendezvous: it resumes on arm `arm`.
fn deliver(m: *Machine, o: Offer, value: Value) void {
m.removeOffers(o.task);
const t = &m.tasks.items[o.task];
t.delivered = .{ .arm = o.arm, .value = value };
if (t.state == .waiting) t.state = .runnable;
}
/// Performs an `ok`-ready send.
fn doSend(m: *Machine, id: u32, v: Value) !void {
const c = &m.channels.items[id];
if (c.capacity > 0) return c.buf.append(m.arena, try m.deepCopy(v));
const o = c.recv_offer.?;
m.deliver(o, try m.deepCopy(v));
}
/// Performs an `ok`-ready receive.
fn doRecv(m: *Machine, id: u32) Value {
const c = &m.channels.items[id];
if (c.buffered() > 0) {
c.head += 1;
return c.buf.items[c.head - 1];
}
const o = c.send_offers.orderedRemove(0);
m.deliver(o, .void);
return o.value;
}
/// Returns the channel's bytes once it is `CLOSED` with no sender.
fn maybeRelease(m: *Machine, id: u32) void {
const c = &m.channels.items[id];
if (c.released or c.receiver != .closed or c.senders != 0) return;
c.released = true;
m.uncharge(c.authority, c.bytes);
}
fn setParams(f: air.Function, vals: []Value, block: u32, values: []const Value) void {
for (f.blocks[block].params, values) |p, v| vals[p.value] = v;
}
fn execCancellation(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
const t = &m.tasks.items[m.current];
switch (inst.op) {
.task_check_cancel => |x| return .{ .jump_yield = if (cancelObservable(t)) x.cancelled else x.ok },
.task_join_cancel => |x| {
const child = vals[x.task].task;
if (m.tasks.items[child].state == .done) {
m.live_tasks -= 1;
setParams(f, vals, x.ok, &.{m.tasks.items[child].result});
return .{ .jump_yield = x.ok };
}
if (cancelObservable(t)) {
setParams(f, vals, x.cancelled, &.{vals[x.task]});
return .{ .jump_yield = x.cancelled };
}
return .{ .wait = .op };
},
.task_shield_begin => {
t.shield += 1;
return bind(vals, inst.result, .shield);
},
.task_shield_end => {
t.shield -= 1;
return .next;
},
else => unreachable,
}
}
fn execChannel(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
const self = m.current;
switch (inst.op) {
.channel_make => |x| {
const n = usize_(vals[x.cap]);
const each = budget.accountedSize(m.module, x.elem, 0);
const bytes: ?u64 = if (each) |e| std.math.mul(u64, n, e) catch null else null;
const a = vals[x.mem].cap;
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
try m.channels.append(m.arena, .{ .capacity = n, .authority = a, .bytes = bytes.? });
const id: u32 = @intCast(m.channels.items.len - 1);
setParams(f, vals, x.ok, &.{ .{ .sender = id }, .{ .receiver = id } });
return .{ .jump = x.ok };
},
.channel_dup => |v| {
const id = endpointOf(vals[v]);
m.channels.items[id].senders += 1;
return bind(vals, inst.result, .{ .sender = id });
},
.channel_close_sender => |v| {
const id = vals[v].sender;
m.channels.items[id].senders -= 1;
m.maybeRelease(id);
return .yield;
},
.channel_close_receiver => |x| {
const id = vals[x.receiver].receiver;
const c = &m.channels.items[id];
if (c.buffered() == 0) {
c.receiver = .closed;
m.maybeRelease(id);
return .{ .jump_yield = x.ok };
}
c.receiver = .closing;
setParams(f, vals, x.pending, &.{vals[x.receiver]});
return .{ .jump_yield = x.pending };
},
.channel_send => |x| {
const t = &m.tasks.items[self];
const v = vals[x.value];
if (t.delivered) |_| {
t.delivered = null;
return .{ .jump_yield = x.ok };
}
m.removeOffers(self);
const id = endpointOf(vals[x.sender]);
switch (m.sendState(id)) {
.ok => {
try m.doSend(id, v);
return .{ .jump_yield = x.ok };
},
.closed => {
setParams(f, vals, x.closed, &.{v});
return .{ .jump_yield = x.closed };
},
.none => {
if (cancelObservable(t)) {
setParams(f, vals, x.cancelled, &.{v});
return .{ .jump_yield = x.cancelled };
}
const c = &m.channels.items[id];
if (c.capacity == 0) try c.send_offers.append(m.arena, .{ .task = self, .arm = 0, .value = v });
return .{ .wait = .op };
},
}
},
.channel_recv => |x| {
const t = &m.tasks.items[self];
if (t.delivered) |d| {
t.delivered = null;
setParams(f, vals, x.ok, &.{d.value});
return .{ .jump_yield = x.ok };
}
m.removeOffers(self);
const id = endpointOf(vals[x.receiver]);
switch (m.recvState(id)) {
.ok => {
setParams(f, vals, x.ok, &.{m.doRecv(id)});
return .{ .jump_yield = x.ok };
},
.closed => return .{ .jump_yield = x.closed },
.none => {
if (cancelObservable(t)) return .{ .jump_yield = x.cancelled };
const c = &m.channels.items[id];
if (c.capacity == 0) c.recv_offer = .{ .task = self, .arm = 0 };
return .{ .wait = .op };
},
}
},
.select => |x| return m.execSelect(f, vals, x),
else => unreachable,
}
}
/// `select` (spec 04 §39).
fn execSelect(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select")) !Step {
const self = m.current;
const t = &m.tasks.items[self];
const ids = try m.arena.alloc(air.ValueId, x.arms.len);
const vs = air.Op.selectValues(x.arms, ids);
const v_vals = try m.arena.alloc(Value, vs.len);
for (vs, v_vals) |v, *o| o.* = vals[v];
if (t.delivered) |d| {
t.delivered = null;
return m.selectOk(f, vals, x, d.arm, d.value, vs, v_vals);
}
m.removeOffers(self);
var ready_arms: std.ArrayList(struct { u32, Readiness }) = .empty;
for (x.arms, 0..) |arm, i| {
const ch = endpointOf(vals[arm.endpoint]);
const st = if (arm.value == null) m.recvState(ch) else m.sendState(ch);
if (st != .none) try ready_arms.append(m.arena, .{ @intCast(i), st });
}
if (ready_arms.items.len == 0) {
if (cancelObservable(t)) {
setParams(f, vals, x.cancelled, v_vals);
return .{ .jump_yield = x.cancelled };
}
for (x.arms, 0..) |arm, i| {
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
if (c.capacity != 0) continue;
if (arm.value) |v| {
try c.send_offers.append(m.arena, .{ .task = self, .arm = @intCast(i), .value = vals[v] });
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
}
return .{ .wait = .op };
}
var pick: usize = 0;
if (ready_arms.items.len > 1) {
pick = m.sched.next() % ready_arms.items.len;
m.choices += 1;
m.drew = true;
}
const arm_i, const st = ready_arms.items[pick];
const arm = x.arms[arm_i];
const ch = endpointOf(vals[arm.endpoint]);
if (st == .closed) {
setParams(f, vals, arm.closed, v_vals);
return .{ .jump_yield = arm.closed };
}
if (arm.value) |v| {
try m.doSend(ch, vals[v]);
return m.selectOk(f, vals, x, arm_i, .void, vs, v_vals);
}
return m.selectOk(f, vals, x, arm_i, m.doRecv(ch), vs, v_vals);
}
/// Continues at the `ok` target of arm `i`: the received value (for a
/// receive arm), then the send values not sent on this edge.
fn selectOk(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select"), i: u32, received: Value, vs: []const air.ValueId, v_vals: []const Value) !Step {
const arm = x.arms[i];
var params: std.ArrayList(Value) = .empty;
if (arm.value == null) try params.append(m.arena, received);
for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.arena, val);
setParams(f, vals, arm.ok, params.items);
return .{ .jump_yield = arm.ok };
}
fn execMutex(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
switch (inst.op) {
.mutex_make => |v| {
const mc = try m.arena.create(Value.MutexCell);
mc.* = .{ .locked = false, .cell = .{ .value = try m.deepCopy(vals[v]), .ty = .void } };
return bind(vals, inst.result, .{ .mutex = mc });
},
.mutex_take => |v| return bind(vals, inst.result, vals[v].mutex.cell.value),
.mutex_lock => |x| {
const mc = mutexOf(vals[x.mutex]);
if (!mc.locked) {
mc.locked = true;
setParams(f, vals, x.ok, &.{.{ .guard = mc }});
return .{ .jump_yield = x.ok };
}
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
return .{ .wait = .op };
},
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = &vals[g].guard.cell, .path = &.{} } }),
.mutex_unlock => |g| {
vals[g].guard.locked = false;
return .yield;
},
else => unreachable,
}
}
fn mutexOf(v: Value) *Value.MutexCell {
return switch (v) {
.mutex => |mc| mc,
.place => |p| mutexOf(p.cell.value),
else => unreachable,
};
}
fn bind(vals: []Value, result: ?air.ValueId, v: Value) Step {
vals[result.?] = v;
return .next;
@@ -604,7 +996,7 @@ const Machine = struct {
.stdout = m.world.stdout.items,
.stderr = m.world.stderr.items,
.files = files,
.schedule = if (m.spawned) .{ .seed = m.schedule_seed, .quantum = m.quantum, .choices = m.choices } else null,
.schedule = if (m.spawned or m.drew) .{ .seed = m.schedule_seed, .quantum = m.quantum, .choices = m.choices } else null,
};
}
@@ -1135,7 +1527,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
.resource, .own, .region, .scope, .task => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
+7 -1
View File
@@ -61,10 +61,16 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
_ = try addOnce(arena, &info.intrinsics, reg.name);
if (reg.effect) |e| _ = try addOnce(arena, &info.direct, e);
},
.own_new, .own_array, .region_new, .region_array, .region_create => {
.own_new, .own_array, .region_new, .region_array, .region_create, .channel_make => {
info.allocations += 1;
_ = try addOnce(arena, &info.direct, "mem.alloc");
},
.task_spawn => _ = try addOnce(arena, &info.direct, "task.spawn"),
// spec 04 §37.4: `task.join` waits in modules declaring `cancellation`.
.task_join => if (m.declares("cancellation")) {
_ = try addOnce(arena, &info.direct, "task.wait");
},
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => _ = try addOnce(arena, &info.direct, "task.wait"),
.arith => |x| if (x.mode == .checked) switch (x.op) {
.add, .sub, .mul => info.checks.overflow += 1,
.div, .rem => {
+120 -1
View File
@@ -72,6 +72,10 @@ const Walker = struct {
loans: std.ArrayList(Loan) = .empty,
/// Scope of each task handle value.
task_scope: []?ValueId,
/// Number of shields live when each shield began (spec 04 §37.3).
shield_depth: []u32,
/// The `ref<mutex<T>>` each guard was locked through (spec 04 §40).
guard_parent: []?ValueId,
block: u32 = 0,
index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 },
@@ -265,7 +269,9 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void
try out.append(arena, .{ .target = t.ok, .args = &.{} });
try out.append(arena, .{ .target = t.err, .args = &.{} });
},
else => {},
// Values these terminators consume are consumed on every edge, by
// `step`, before propagation; results arrive as block parameters.
else => for (try air.waitTargets(op, arena)) |t| try out.append(arena, .{ .target = t.block, .args = &.{} }),
}
}
@@ -278,8 +284,12 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
.live = try c.arena.alloc(bool, f.values.len),
.dead = try c.arena.alloc(Dead, f.values.len),
.task_scope = try c.arena.alloc(?ValueId, f.values.len),
.shield_depth = try c.arena.alloc(u32, f.values.len),
.guard_parent = try c.arena.alloc(?ValueId, f.values.len),
};
@memset(w.task_scope, null);
@memset(w.shield_depth, 0);
@memset(w.guard_parent, null);
@memset(w.info, null);
@memset(w.live, false);
@memset(w.dead, .none);
@@ -397,6 +407,9 @@ fn step(w: *Walker, inst: air.Inst) !void {
for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) {
return w.report("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task });
};
for (w.live, 0..) |is_live, g| if (is_live and w.guard_parent[g] != null and w.isAncestor(v, w.guard_parent[g].?)) {
return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", @intCast(g) });
};
for (w.live, 0..) |is_live, cv| {
if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) {
return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) });
@@ -406,6 +419,10 @@ fn step(w: *Walker, inst: air.Inst) !void {
.call => |x| {
try lendArgs(w, x.args);
const callee = w.c.module.functions[x.callee];
for (callee.effects) |e| if (std.mem.eql(u8, e, "task.wait") or std.mem.eql(u8, e, "task.spawn")) {
try noWaitUnderLock(w, "call of a function that may wait or spawn");
break;
};
for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved);
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
@@ -419,6 +436,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
.own_free, .own_take => |v| try w.consume(v, .closed),
.task_scope_begin => w.live[inst.result.?] = true,
.task_spawn => |x| {
try noWaitUnderLock(w, "task.spawn");
const t = inst.result.?;
w.task_scope[t] = x.scope;
for (x.args) |a| {
@@ -433,6 +451,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
w.live[t] = true;
},
.task_join => |t| {
try noWaitUnderLock(w, "task.join");
// Joining ends the task's loans (they are active only while `t` lives).
try w.consume(t, .closed);
if (inst.result) |r| if (w.isResource(r)) {
@@ -480,6 +499,92 @@ fn step(w: *Walker, inst: air.Inst) !void {
for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed);
},
.ret => |v| try retStep(w, v),
.task_join_cancel => |x| {
try noWaitUnderLock(w, "task.join.cancel");
const t = x.task;
const back = w.f.blocks[x.cancelled].params[0].value;
// On `cancelled` the same task comes back: its scope and loans
// move to the new handle value (spec 04 §37.3).
w.task_scope[back] = w.task_scope[t];
const n = w.loans.items.len;
for (0..n) |i| {
const l = w.loans.items[i];
if (l.task == t) try w.loans.append(w.c.arena, .{ .task = back, .borrow = l.borrow, .root = l.root, .path = l.path, .mode = l.mode });
}
try w.consume(t, .closed);
},
.task_shield_begin => {
const r = inst.result.?;
var depth: u32 = 0;
for (w.live, 0..) |is_live, v| depth += @intFromBool(is_live and w.types[v] == .shield);
w.shield_depth[r] = depth;
w.live[r] = true;
},
.task_shield_end => |sh| {
if (w.live[sh]) for (w.live, 0..) |is_live, v| if (is_live and w.types[v] == .shield and w.shield_depth[v] > w.shield_depth[sh]) {
try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", @intCast(v) });
break;
};
try w.consume(sh, .closed);
},
.channel_dup => |v| {
try lendArgs(w, &.{v});
w.live[inst.result.?] = true;
},
.channel_send => |x| {
try noWaitUnderLock(w, "channel.send");
try lendArgs(w, &.{x.sender});
if (w.isResource(x.value)) try w.consume(x.value, .moved);
},
.channel_recv => |x| {
try noWaitUnderLock(w, "channel.recv");
try lendArgs(w, &.{x.receiver});
},
.channel_close_sender => |v| try w.consume(v, .closed),
.channel_close_receiver => |x| try w.consume(x.receiver, .closed),
.select => |x| {
try noWaitUnderLock(w, "select");
// Only one arm runs, so arms may name the same endpoint borrow.
for (x.arms, 0..) |arm, i| {
const seen = for (x.arms[0..i]) |prev| {
if (prev.endpoint == arm.endpoint) break true;
} else false;
if (!seen) try lendArgs(w, &.{arm.endpoint});
}
const buf = try w.c.arena.alloc(ValueId, x.arms.len);
for (air.Op.selectValues(x.arms, buf)) |v| if (w.isResource(v)) try w.consume(v, .moved);
},
.mutex_make => |v| {
if (w.isResource(v)) try w.consume(v, .moved);
w.live[inst.result.?] = true;
},
.mutex_take => |m| {
try w.consume(m, .closed);
if (w.isResource(inst.result.?)) w.live[inst.result.?] = true;
},
.mutex_lock => |x| {
try noWaitUnderLock(w, "mutex.lock");
try lendArgs(w, &.{x.mutex});
w.guard_parent[w.f.blocks[x.ok].params[0].value] = x.mutex;
},
.mutex_borrow => |g| {
const r = inst.result.?;
if (!try w.resourceUsable(g)) {
w.info[r] = .{ .owned = true, .mode = .exclusive, .root = g, .path = &.{}, .parent = null };
w.live[r] = true;
return;
}
try w.create(r, null, g, &.{});
},
.mutex_unlock => |g| {
if (!w.live[g]) return w.report("E2002", "linear value consumed twice", g, null);
for (w.live, 0..) |is_live, b| if (is_live and w.info[b] != null and w.info[b].?.root == g) {
try w.report("E2102", "guard unlocked while a borrow from it is live", g, .{ "borrow", @intCast(b) });
break;
};
w.live[g] = false;
w.dead[g] = .closed;
},
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
else => {},
@@ -487,6 +592,20 @@ fn step(w: *Walker, inst: air.Inst) !void {
_ = f;
}
/// The critical-section rule (spec 04 §41): no operation that may wait or
/// spawn while a lock guard is live.
fn noWaitUnderLock(w: *Walker, op: []const u8) !void {
for (w.live, 0..) |is_live, g| if (is_live and w.types[g] == .guard) {
return w.c.report("E4304", w.span, "operation that may wait or spawn while a lock guard is live", &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "guard", .value = .{ .str = try w.name(@intCast(g)) } },
.{ .name = "op", .value = .{ .str = op } },
});
};
}
/// Borrow arguments of a call or intrinsic are lent for its duration and
/// must not alias each other when one is exclusive (§11.2).
fn lendArgs(w: *Walker, args: []const ValueId) !void {
+2 -1
View File
@@ -28,7 +28,8 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task => 8,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard => 8,
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
.own_array => 16,
.slice, .slice_mut => 16,
.builtin => |b| tagSize(b.variants().len),
+43
View File
@@ -91,6 +91,49 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
try paramCount(c, f, inst.span, x.err.?, 1, "intrinsic `err` target takes exactly one parameter");
},
.ret, .trap => {},
.task_check_cancel => |x| {
try paramCount(c, f, inst.span, x.ok, 0, "task.check_cancel targets take no parameters");
try paramCount(c, f, inst.span, x.cancelled, 0, "task.check_cancel targets take no parameters");
},
.task_join_cancel => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "task.join.cancel `ok` target takes the task result");
try paramCount(c, f, inst.span, x.cancelled, 1, "task.join.cancel `cancelled` target takes the task handle");
},
.channel_make => |x| {
try paramCount(c, f, inst.span, x.ok, 2, "channel.make `ok` target takes the sender and the receiver");
try paramCount(c, f, inst.span, x.err, 1, "channel.make `err` target takes exactly one parameter");
},
.channel_send => |x| {
try paramCount(c, f, inst.span, x.ok, 0, "channel.send `ok` target takes no parameters");
try paramCount(c, f, inst.span, x.closed, 1, "channel.send `closed` target takes the value back");
try paramCount(c, f, inst.span, x.cancelled, 1, "channel.send `cancelled` target takes the value back");
},
.channel_recv => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "channel.recv `ok` target takes the received value");
try paramCount(c, f, inst.span, x.closed, 0, "channel.recv `closed` target takes no parameters");
try paramCount(c, f, inst.span, x.cancelled, 0, "channel.recv `cancelled` target takes no parameters");
},
.channel_close_receiver => |x| {
try paramCount(c, f, inst.span, x.ok, 0, "channel.close_receiver `ok` target takes no parameters");
try paramCount(c, f, inst.span, x.pending, 1, "channel.close_receiver `pending` target takes the receiver back");
},
.mutex_lock => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "mutex.lock `ok` target takes the guard");
try paramCount(c, f, inst.span, x.cancelled, 0, "mutex.lock `cancelled` target takes no parameters");
},
// Each target receives its own parameters, then the send values not
// sent on that edge (spec 04 §39).
.select => |x| {
const buf = try c.arena.alloc(air.ValueId, x.arms.len);
const n = air.Op.selectValues(x.arms, buf).len;
for (x.arms) |arm| {
if (arm.value) |_| {
try paramCount(c, f, arm.span, arm.ok, n - 1, "select send arm `ok` target takes the send values not sent by this arm");
} else try paramCount(c, f, arm.span, arm.ok, n + 1, "select recv arm `ok` target takes the received value and the send values");
try paramCount(c, f, arm.span, arm.closed, n, "select `closed` target takes the send values");
}
try paramCount(c, f, inst.span, x.cancelled, n, "select `cancelled` target takes the send values");
},
else => unreachable,
}
}
+14 -1
View File
@@ -42,6 +42,11 @@ pub fn check(c: *Context) !void {
});
};
},
// In a module declaring `cancellation`, every operation that may
// suspend requires `task.wait`, `task.join` included (spec 04 §37.4).
.task_join => if (m.declares("cancellation")) try need(c, f, inst, "task.wait"),
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => try need(c, f, inst, "task.wait"),
.channel_make => try need(c, f, inst, "mem.alloc"),
.own_new, .own_array, .region_create, .region_new, .region_array => if (!contains(f.effects, "mem.alloc")) {
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
.{ .name = "function", .value = .{ .str = f.name } },
@@ -60,7 +65,15 @@ pub fn check(c: *Context) !void {
}
}
fn contains(list: []const []const u8, name: []const u8) bool {
fn need(c: *Context, f: air.Function, inst: air.Inst, effect: []const u8) !void {
if (contains(f.effects, effect)) return;
try c.report("E3101", inst.span, "instruction requires an effect the function does not declare", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "effect", .value = .{ .str = effect } },
});
}
pub fn contains(list: []const []const u8, name: []const u8) bool {
for (list) |x| if (std.mem.eql(u8, x, name)) return true;
return false;
}
+146 -8
View File
@@ -85,7 +85,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
.resource, .own, .own_array, .region, .scope, .task => pos != .member,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
@@ -95,7 +95,12 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
});
// The pointee of ref/mut may be a linear value (`mut<file<read>>`), and
// a task may return one; every other compound holds value types only.
if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut or t == .task) .borrowed else .member, owner);
// Channel elements and mutex contents may be linear (spec 04 §38.1);
// their remaining rules are the element rules of `checkElement`.
if (t.inner()) |inner| try wellFormed(c, span, inner, switch (t) {
.ref, .mut, .task, .sender, .receiver, .mutex, .guard => .borrowed,
else => .member,
}, owner);
}
/// `local.alloc` results are checked separately: their own type is storage.
@@ -191,6 +196,14 @@ const FnCtx = struct {
for (args, params) |a, p| try fc.expectValue(span, a, p);
}
/// The parameters of `block` have exactly the types `want` (counts were
/// checked by the CFG stage).
fn expectParams(fc: *FnCtx, span: air.Span, block: u32, want: []const Type) !void {
for (fc.f.blocks[block].params, want) |p, t| {
if (!p.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(fc.f, p.value), t, p.ty);
}
}
fn expectTarget(fc: *FnCtx, span: air.Span, t: air.Target) !void {
const params = fc.f.blocks[t.block].params;
for (t.args, params) |a, p| try fc.expectValue(span, a, p.ty);
@@ -212,6 +225,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.slice_len => .{ .int = .usize },
.task_scope_begin => .scope,
.task_cancelled => .bool,
.task_shield_begin => .shield,
.intrinsic => |x| blk: {
const reg = air.authority.intrinsics[x.index];
if (reg.fallible or reg.results.len == 0) break :blk .void;
@@ -312,13 +326,13 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
/// `Send` (spec 04 §35): may move to another task.
pub fn isSend(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .resource, .region => true,
.own, .own_array => |inner| isSend(m, inner.*),
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
.ref, .slice => |inner| isShare(m, inner.*),
.mut, .slice_mut => |inner| isSend(m, inner.*),
.array => |a| isSend(m, a.elem),
.named => |i| aggregateAll(m, i, isSend),
.scope, .task, .local, .void, .never => false,
.scope, .task, .shield, .guard, .local, .void, .never => false,
};
}
@@ -326,8 +340,10 @@ pub fn isSend(m: air.Module, t: Type) bool {
pub fn isShare(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap => true,
.resource, .region, .mut, .slice_mut, .scope, .task, .local, .void, .never => false,
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
.own, .own_array, .ref, .slice => |inner| isShare(m, inner.*),
// The lock synchronizes access (spec 04 §35, §40).
.mutex => |inner| isSend(m, inner.*),
.array => |a| isShare(m, a.elem),
.named => |i| aggregateAll(m, i, isShare),
};
@@ -383,6 +399,78 @@ fn checkSpawn(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "task_spawn")) !
}
}
/// Element rules of channels and mutexes (spec 04 §38.1).
fn checkElement(fc: *FnCtx, span: air.Span, t: Type) !void {
const m = fc.c.module;
if (contains(m, t, .endpoint)) return fc.c.report("E0006", span, "construct belongs to a feature the module does not declare", &.{
.{ .name = "reason", .value = .{ .str = "feature_not_declared" } },
.{ .name = "feature", .value = .{ .str = "channel_transfer" } },
.{ .name = "construct", .value = .{ .str = "channel endpoint inside a channel element or mutex" } },
});
if (contains(m, t, .forbidden)) return fc.c.report("E1001", span, "a channel element or mutex content contains no borrow, scope, task, shield or guard", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "type", .value = .{ .str = try fc.c.typeName(t) } },
});
if (!isSend(m, t)) try fc.c.report("E4001", span, "a channel element or mutex content must be Send", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "type", .value = .{ .str = try fc.c.typeName(t) } },
});
}
/// Whether `t` transitively contains an endpoint, or a borrow or
/// function-bound value.
fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden }) bool {
const here = switch (what) {
.endpoint => t.isEndpoint(),
.forbidden => t.isBorrow() or t.isTaskBound() or t == .guard,
};
if (here) return true;
if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) return contains(m, inner, what);
return switch (t) {
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (contains(m, f.ty, what)) break true;
} else false,
.@"enum" => |vs| for (vs) |v| {
for (v.payload) |p| if (contains(m, p, what)) return true;
} else false,
},
else => false,
};
}
/// `select` (spec 04 §39): each arm is a channel operation; each target
/// takes its own parameters, then the send values not sent on its edge.
fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !void {
const f = fc.f;
const a = fc.c.arena;
const buf = try a.alloc(air.ValueId, x.arms.len);
const vs = air.Op.selectValues(x.arms, buf);
const v_types = try a.alloc(Type, vs.len);
for (vs, v_types) |v, *t| t.* = fc.typeOf(v);
for (x.arms) |arm| {
const t = fc.typeOf(arm.endpoint);
const want: std.meta.Tag(Type) = if (arm.value == null) .receiver else .sender;
if (t != .mut or std.meta.activeTag(t.mut.*) != want) {
try fc.kindError(arm.span, arm.endpoint, if (arm.value == null) "mut<receiver<T>>" else "mut<sender<T>>");
continue;
}
const e = t.mut.inner().?;
var ok_types: std.ArrayList(Type) = .empty;
if (arm.value) |v| {
try fc.expectValue(arm.span, v, e);
for (vs, v_types) |w, wt| if (w != v) try ok_types.append(a, wt);
} else {
try ok_types.append(a, e);
try ok_types.appendSlice(a, v_types);
}
try fc.expectParams(arm.span, arm.ok, ok_types.items);
try fc.expectParams(arm.span, arm.closed, v_types);
}
try fc.expectParams(inst.span, x.cancelled, v_types);
_ = f;
}
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type);
b.* = t;
@@ -406,6 +494,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.own_take => |v| fc.ty[v] orelse return null,
.task_join => |v| fc.ty[v] orelse return null,
.task_spawn => |x| return .{ .task = try boxed(a, m.functions[x.callee].ret) },
.channel_dup, .mutex_take, .mutex_borrow => |v| fc.ty[v] orelse return null,
.mutex_make => |v| return .{ .mutex = try boxed(a, fc.ty[v] orelse return null) },
.slice_split => |x| fc.ty[x.slice] orelse return null,
else => return null,
};
@@ -414,7 +504,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope => .{ .ref = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver, .mutex => .{ .ref = try boxed(a, t) },
.own => |inner| .{ .ref = inner },
.own_array => |inner| .{ .slice = inner },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
@@ -422,7 +512,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope => .{ .mut = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver => .{ .mut = try boxed(a, t) },
.own => |inner| .{ .mut = inner },
.own_array => |inner| .{ .slice_mut = inner },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
@@ -455,6 +545,9 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.slice_sub, .slice_split => if (t.isSlice()) t else invalid,
.own_take => if (t == .own) t.own.* else invalid,
.task_join => if (t == .task) t.task.* else invalid,
.channel_dup => if (t == .ref and t.ref.* == .sender) t.ref.* else invalid,
.mutex_take => if (t == .mutex) t.mutex.* else invalid,
.mutex_borrow => if (t == .guard) Type{ .mut = t.guard } else invalid,
else => unreachable,
};
}
@@ -679,6 +772,51 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
if (inst.result == null and r != .void and r != .never) try fc.c.report("E1001", span, "the result of task.join must be bound", &.{.{ .name = "function", .value = .{ .str = f.name } }});
},
.task_spawn => |x| try checkSpawn(fc, inst, x),
.task_check_cancel, .task_shield_begin => {},
.task_shield_end => |v| if (fc.typeOf(v) != .shield) try fc.kindError(span, v, "shield"),
.task_join_cancel => |x| {
const t = fc.typeOf(x.task);
if (t != .task) return fc.kindError(span, x.task, "task<T>");
try fc.expectParams(span, x.ok, &.{t.task.*});
try fc.expectParams(span, x.cancelled, &.{t});
},
.channel_make => |x| {
try fc.expectValue(span, x.cap, .{ .int = .usize });
try fc.expectAllocCap(span, x.mem);
try checkElement(fc, span, x.elem);
const e = try boxed(fc.c.arena, x.elem);
try fc.expectParams(span, x.ok, &.{ .{ .sender = e }, .{ .receiver = e } });
try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }});
},
.channel_dup => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<sender<T>>"),
.channel_send => |x| {
const t = fc.typeOf(x.sender);
if (t != .mut or t.mut.* != .sender) return fc.kindError(span, x.sender, "mut<sender<T>>");
const e = t.mut.sender.*;
try fc.expectValue(span, x.value, e);
try fc.expectParams(span, x.closed, &.{e});
try fc.expectParams(span, x.cancelled, &.{e});
},
.channel_recv => |x| {
const t = fc.typeOf(x.receiver);
if (t != .mut or t.mut.* != .receiver) return fc.kindError(span, x.receiver, "mut<receiver<T>>");
try fc.expectParams(span, x.ok, &.{t.mut.receiver.*});
},
.channel_close_sender => |v| if (fc.typeOf(v) != .sender) try fc.kindError(span, v, "sender<T>"),
.channel_close_receiver => |x| {
const t = fc.typeOf(x.receiver);
if (t != .receiver) return fc.kindError(span, x.receiver, "receiver<T>");
try fc.expectParams(span, x.pending, &.{t});
},
.select => |x| try checkSelect(fc, inst, x),
.mutex_make => |v| try checkElement(fc, span, fc.typeOf(v)),
.mutex_take => |v| if (fc.typeOf(v) != .mutex) try fc.kindError(span, v, "mutex<T>"),
.mutex_lock => |x| {
const t = fc.typeOf(x.mutex);
if (t != .ref or t.ref.* != .mutex) return fc.kindError(span, x.mutex, "ref<mutex<T>>");
try fc.expectParams(span, x.ok, &.{.{ .guard = t.ref.mutex }});
},
.mutex_borrow, .mutex_unlock => |v| if (fc.typeOf(v) != .guard) try fc.kindError(span, v, "guard<T>"),
.cap_narrow => |x| {
const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");