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:
1 parent
b82bc35c5f
commit
aaf32b6853
45 files changed
+2077
-43
No files matched your search
@@ -23,16 +23,16 @@ Non-normative. Part of the [implementation plan](README.md).
|
||||
| ID | Status | Task | Depends | Output | Done when |
|
||||
|---|---|---|---|---|---|
|
||||
| P3-1 | done | Resolve Q-013, Q-014 (RFC 0011, RFC 0012) | — | spec 04, 11 | questions resolved |
|
||||
| P3-2 | doing | Contract tables: `task.*` (RFC 0011, done), `channel.*`, `mutex.*`, `rwlock.*`, select (RFC 0012); `thread.*` deferred to native backends | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects |
|
||||
| P3-2a | doing | Publish features `tasks` (done), `cancellation`, `channels`, `sync` (specified by RFC 0012) | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
|
||||
| P3-2 | done | Contract tables: `task.*` (RFC 0011), `channel.*`, `mutex.*`, select, cancellation (RFC 0012, spec 04 §37–§41); `rwlock.*` deferred (reserved `rwlock`); `thread.*` deferred to native backends | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects |
|
||||
| P3-2a | done | Publish features `tasks`, `cancellation`, `channels`, `sync` | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
|
||||
| P3-3 | done | Deterministic scheduler: seeds, choice points, choice log; global fuel across tasks and a separate `quantum` (spec 11 §7.2) | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run; fuel is the sum over all tasks |
|
||||
| P3-4 | done | Send/Share/Local derivation | P3-1 | `src/verifier/send_share.zig` | E4001, E4002 accept/reject |
|
||||
| P3-5 | done | Task-scope verifier and scoped borrows | P3-2 | `src/verifier/tasks.zig` | E4301, E4302 accept/reject |
|
||||
| P3-6 | done | Concurrent alias / data-race rejection | P3-5 | `src/verifier/borrow.zig` | E4101 accept/reject; disjoint `split_mut` halves accepted in two tasks |
|
||||
| P3-7 | doing | Interpreter tasks: spawn, join, cancel, cancellation points, shields, task failure | P3-3 | `src/interp/` | cancellation observed only at defined points; shield defers it |
|
||||
| P3-8 | todo | Bounded and rendezvous channels with ownership transfer | P3-7 | interpreter + verifier | sender cannot use moved message (E2001); capacity 0 rendezvous test |
|
||||
| P3-9 | todo | Mutex and RwLock with linear guards | P3-7 | interpreter + verifier | guard not `Send`; unlock consumes guard; E3002 on leaked guard |
|
||||
| P3-10 | todo | Async I/O buffer claims | P3-7 | verifier + runtime | E4303 accept/reject |
|
||||
| P3-7 | done | Interpreter tasks: spawn, join, cancel, cancellation points, shields, task failure | P3-3 | `src/interp/` | cancellation observed only at defined points; shield defers it |
|
||||
| P3-8 | done | Bounded and rendezvous channels with ownership transfer | P3-7 | interpreter + verifier | sender cannot use moved message (E2001); capacity 0 rendezvous test |
|
||||
| P3-9 | done | Mutex with linear guards and the critical-section rule (E4304); RwLock deferred | P3-7 | interpreter + verifier | guard not `Send`; unlock consumes guard; E3002 on leaked guard |
|
||||
| P3-10 | todo | Async I/O buffer claims (depends on task-aware I/O, spec 04 §36.1; deferral proposed to the owner) | P3-7 | verifier + runtime | E4303 accept/reject |
|
||||
| P3-11 | todo | Blocking effect and blocking pool policy | P3-7 | spec 04 §18, runtime | `thread.block` from ordinary task handled per spec |
|
||||
| P3-12 | doing | Runner: `seed:`/`schedules:`/`quantum:` headers (schedule budget kept separate from fuel); stress modes (1/2/N workers, random, forced yield, slow consumer, cancellation during waits, I/O reordering) | P3-3 | `tools/conformance.zig` | stress modes selectable; failing seed printed for replay |
|
||||
| P3-13 | todo | Reference programs: parallel-map, channel transfer, tcp-echo with tasks | P3-8, P3-9 | `tests/programs/` | pass under all stress modes |
|
||||
|
||||
@@ -650,10 +650,10 @@ Decision record: RFC 0012. Depends on `cancellation`. `RwLock` is deferred (rese
|
||||
|
||||
| Type | Meaning | Class |
|
||||
|---|---|---|
|
||||
| `mutex<T>` | mutual exclusion around a `T` (element rules of §38.1) | move-only; linear if `T` is |
|
||||
| `mutex<T>` | mutual exclusion around a `T` (element rules of §38.1) | linear: consumed by `mutex.take` |
|
||||
| `guard<T>` | the current task holds the lock | linear, function-bound, `Local` |
|
||||
|
||||
`mutex<T>` is opaque: no `borrow.field`, `load` or `store` reaches its contents; it is the verifier-known interior-mutability abstraction of §8. Tasks share it through a `ref<mutex<T>>` loan (§34). `guard<T>` as a parameter, return type or aggregate member is the reserved feature `guard_transfer` (`E0006`).
|
||||
`mutex<T>` is opaque: no `borrow.field`, `load` or `store` reaches its contents; it is the verifier-known interior-mutability abstraction of §8. It is a linear SSA value like a resource (format 0 has no droppable move-only class): `borrow.ref %m` gives the `ref<mutex<T>>` that tasks share through a loan (§34), and `mutex.take` consumes it once no borrow is live. `guard<T>` as a parameter, return type or aggregate member is the reserved feature `guard_transfer` (`E0006`).
|
||||
|
||||
| Instruction | Operands → result | Effect | Verifier | Runtime |
|
||||
|---|---|---|---|---|
|
||||
|
||||
+1
-1
@@ -268,7 +268,7 @@ A function header may carry, after its `effects` line, a line `trusted "<obligat
|
||||
|
||||
### 8.11 Types and syntax of the features `cancellation`, `channels` and `sync`
|
||||
|
||||
Types: `shield` (`cancellation`), `sender<T>` and `receiver<T>` (`channels`), `mutex<T>` and `guard<T>` (`sync`). `shield` and `guard<T>` are linear and function-bound; `sender<T>`, `receiver<T>` are linear; `mutex<T>` is move-only, linear if `T` is. Rules: spec 04 §37–§41.
|
||||
Types: `shield` (`cancellation`), `sender<T>` and `receiver<T>` (`channels`), `mutex<T>` and `guard<T>` (`sync`). `shield` and `guard<T>` are linear and function-bound; `sender<T>`, `receiver<T>` and `mutex<T>` are linear. Rules: spec 04 §37–§41.
|
||||
|
||||
`select` is a terminator written on one line: one or more bracketed arms `[recv %b, ok -> @x, closed -> @y]` or `[send %b, %v, ok -> @x, closed -> @y]`, separated by commas, followed by `, cancelled -> @c`. `channel.make` takes a type operand first, like `local.alloc`.
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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>");
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
; Properly nested shields: the inner one ends first.
|
||||
; expect: accept
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_shields_nested
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @f() -> void
|
||||
effects []
|
||||
entry:
|
||||
%a = task.shield.begin
|
||||
%b = task.shield.begin
|
||||
task.shield.end %b
|
||||
task.shield.end %a
|
||||
ret
|
||||
@@ -0,0 +1,30 @@
|
||||
; A critical section may call functions that neither wait nor spawn, passing them the guarded mut<T>.
|
||||
; expect: accept
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_call_in_critical_section
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%g: guard<u64>):
|
||||
%p = mutex.borrow %g
|
||||
call @inc(%p)
|
||||
borrow.end %p
|
||||
mutex.unlock %g
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
|
||||
fn @inc(%p: mut<u64>) -> void
|
||||
effects []
|
||||
entry:
|
||||
%v = load %p
|
||||
%one = const.u64 1
|
||||
%w = add.wrap.u64 %v, %one
|
||||
store %p, %w
|
||||
ret
|
||||
@@ -0,0 +1,21 @@
|
||||
; Unlocking first, then waiting, is accepted.
|
||||
; expect: accept
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_unlock_then_wait
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>, %b: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%ga: guard<u64>):
|
||||
mutex.unlock %ga
|
||||
mutex.lock %b, ok -> @lb, cancelled -> @out
|
||||
lb(%gb: guard<u64>):
|
||||
mutex.unlock %gb
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,23 @@
|
||||
; A module that does not declare cancellation keeps the RFC 0011 effect rules: task.join needs no task.wait.
|
||||
; expect: accept
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.tasks_join_without_wait_effect
|
||||
air 0
|
||||
lang 0.1
|
||||
features [effects, ownership, tasks]
|
||||
|
||||
fn @main() -> u8
|
||||
effects [task.spawn]
|
||||
entry:
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @w()
|
||||
%r = task.join %t
|
||||
task.scope.end %sc
|
||||
ret %r
|
||||
|
||||
fn @w() -> u8
|
||||
effects []
|
||||
entry:
|
||||
%z = const.u8 0
|
||||
ret %z
|
||||
@@ -0,0 +1,33 @@
|
||||
; On the cancelled edge of task.join.cancel the task is not joined: its loans stay, so ending the lent borrow is rejected.
|
||||
; expect: reject E4302
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_join_keeps_loans
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @main() -> u8
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%x = local.alloc u8
|
||||
local.zero %x
|
||||
%r = borrow.ref %x
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @w(%r)
|
||||
task.join.cancel %t, ok -> @joined, cancelled -> @cancelled
|
||||
joined(%v: u8):
|
||||
task.scope.end %sc
|
||||
borrow.end %r
|
||||
ret %v
|
||||
cancelled(%t2: task<u8>):
|
||||
borrow.end %r
|
||||
%v2 = task.join %t2
|
||||
task.scope.end %sc
|
||||
ret %v2
|
||||
|
||||
fn @w(%p: ref<u8>) -> u8
|
||||
effects []
|
||||
entry:
|
||||
%v = load %p
|
||||
ret %v
|
||||
@@ -0,0 +1,23 @@
|
||||
; In a module declaring cancellation, task.join requires the effect task.wait.
|
||||
; expect: reject E3101
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_join_needs_wait
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @main() -> u8
|
||||
effects [task.spawn]
|
||||
entry:
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @w()
|
||||
%r = task.join %t
|
||||
task.scope.end %sc
|
||||
ret %r
|
||||
|
||||
fn @w() -> u8
|
||||
effects []
|
||||
entry:
|
||||
%z = const.u8 0
|
||||
ret %z
|
||||
@@ -0,0 +1,17 @@
|
||||
; Shields end innermost first (spec 04 §37.3).
|
||||
; expect: reject E4305
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_shield_order
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @f() -> void
|
||||
effects []
|
||||
entry:
|
||||
%a = task.shield.begin
|
||||
%b = task.shield.begin
|
||||
task.shield.end %a
|
||||
task.shield.end %b
|
||||
ret
|
||||
@@ -0,0 +1,18 @@
|
||||
; A channel element contains no borrow (reported for each endpoint parameter).
|
||||
; expect: reject E1001 E1001
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_borrow_element
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%heap: cap<mem.alloc>) -> void
|
||||
effects [mem.alloc]
|
||||
entry:
|
||||
%n = const.usize 1
|
||||
channel.make ref<u64>, %n, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<ref<u64>>, %rx: receiver<ref<u64>>):
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,18 @@
|
||||
; Endpoints inside channel elements belong to the reserved feature channel_transfer.
|
||||
; expect: reject E0006
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_endpoint_element
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%heap: cap<mem.alloc>) -> void
|
||||
effects [mem.alloc]
|
||||
entry:
|
||||
%n = const.usize 1
|
||||
channel.make sender<u64>, %n, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<sender<u64>>, %rx: receiver<sender<u64>>):
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,19 @@
|
||||
; Endpoints are linear: a receiver that is never closed leaks.
|
||||
; expect: reject E3002
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_receiver_leak
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%heap: cap<mem.alloc>) -> void
|
||||
effects [mem.alloc]
|
||||
entry:
|
||||
%n = const.usize 1
|
||||
channel.make u64, %n, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
channel.close_sender %tx
|
||||
ret
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,17 @@
|
||||
; channel.recv may suspend: it requires the effect task.wait.
|
||||
; expect: reject E3101
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_recv_without_effect
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%rxb: mut<receiver<u64>>) -> u64
|
||||
effects []
|
||||
entry:
|
||||
channel.recv %rxb, ok -> @got, closed -> @end, cancelled -> @end
|
||||
got(%v: u64):
|
||||
ret %v
|
||||
end:
|
||||
trap
|
||||
@@ -0,0 +1,21 @@
|
||||
; channel.send consumes the value on every edge; on closed/cancelled it comes back as a block parameter, so the old value is dead.
|
||||
; expect: reject E2001
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_use_after_send
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%txb: mut<sender<own<u64>>>, %o: own<u64>) -> u64
|
||||
effects [task.wait]
|
||||
entry:
|
||||
channel.send %txb, %o, ok -> @sent, closed -> @back, cancelled -> @back
|
||||
sent:
|
||||
%z = const.u64 0
|
||||
ret %z
|
||||
back(%r: own<u64>):
|
||||
%b = borrow.ref %o
|
||||
borrow.end %b
|
||||
%v = own.take %r
|
||||
ret %v
|
||||
@@ -0,0 +1,19 @@
|
||||
; A select closed target takes the send values (here one).
|
||||
; expect: reject E5002
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.select_target_arity
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @f(%txb: mut<sender<u64>>, %x: u64) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
select [send %txb, %x, ok -> @sent, closed -> @gone], cancelled -> @back
|
||||
sent:
|
||||
ret
|
||||
gone:
|
||||
ret
|
||||
back(%v: u64):
|
||||
ret
|
||||
@@ -0,0 +1,29 @@
|
||||
; A call of a function declaring task.wait inside a critical section is rejected.
|
||||
; expect: reject E4304
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_call_waiting_function
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>, %b: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%ga: guard<u64>):
|
||||
call @g(%b)
|
||||
mutex.unlock %ga
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
|
||||
fn @g(%b: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %b, ok -> @lb, cancelled -> @out
|
||||
lb(%gb: guard<u64>):
|
||||
mutex.unlock %gb
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,17 @@
|
||||
; A guard is never unlocked implicitly: leaving it live is a leak.
|
||||
; expect: reject E3002
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_guard_leak
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%g: guard<u64>):
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,14 @@
|
||||
; guard<T> is function-bound; as a parameter it belongs to the reserved feature guard_transfer.
|
||||
; expect: reject E0006
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_guard_parameter
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%g: guard<u64>) -> void
|
||||
effects []
|
||||
entry:
|
||||
mutex.unlock %g
|
||||
ret
|
||||
@@ -0,0 +1,24 @@
|
||||
; mutex.lock may wait, so a second lock while holding a guard is rejected: lock-order deadlock is not expressible.
|
||||
; expect: reject E4304
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_lock_twice
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>, %b: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%ga: guard<u64>):
|
||||
mutex.lock %b, ok -> @lb, cancelled -> @ub
|
||||
lb(%gb: guard<u64>):
|
||||
mutex.unlock %gb
|
||||
mutex.unlock %ga
|
||||
ret
|
||||
ub:
|
||||
mutex.unlock %ga
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,20 @@
|
||||
; The mut<T> from mutex.borrow must end before mutex.unlock.
|
||||
; expect: reject E2102
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_unlock_live_borrow
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @f(%a: ref<mutex<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %a, ok -> @la, cancelled -> @out
|
||||
la(%g: guard<u64>):
|
||||
%p = mutex.borrow %g
|
||||
mutex.unlock %g
|
||||
borrow.end %p
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,23 @@
|
||||
; A task may not wait while it holds a lock guard (spec 04 §41).
|
||||
; expect: reject E4304
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_wait_while_locked
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, sync, tasks]
|
||||
|
||||
fn @f(%mr: ref<mutex<u64>>, %rxb: mut<receiver<u64>>) -> void
|
||||
effects [task.wait]
|
||||
entry:
|
||||
mutex.lock %mr, ok -> @locked, cancelled -> @out
|
||||
locked(%g: guard<u64>):
|
||||
channel.recv %rxb, ok -> @got, closed -> @end, cancelled -> @end
|
||||
got(%v: u64):
|
||||
mutex.unlock %g
|
||||
ret
|
||||
end:
|
||||
mutex.unlock %g
|
||||
ret
|
||||
out:
|
||||
ret
|
||||
@@ -0,0 +1,48 @@
|
||||
; task.join.cancel: a cancelled parent gets its child's handle back (not joined,
|
||||
; loans kept), forwards the request and joins normally.
|
||||
; expect: run
|
||||
; schedules: 20
|
||||
; result: 13
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_join_forward
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%sc = task.scope.begin
|
||||
%p = task.spawn %sc, @parent()
|
||||
task.cancel %p
|
||||
%r = task.join %p
|
||||
task.scope.end %sc
|
||||
ret %r
|
||||
|
||||
fn @parent() -> u64
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%sc = task.scope.begin
|
||||
%c = task.spawn %sc, @child()
|
||||
task.join.cancel %c, ok -> @joined, cancelled -> @cancelled
|
||||
joined(%v: u64):
|
||||
task.scope.end %sc
|
||||
ret %v
|
||||
cancelled(%c2: task<u64>):
|
||||
task.cancel %c2
|
||||
%v2 = task.join %c2
|
||||
task.scope.end %sc
|
||||
%ten = const.u64 10
|
||||
%r = add.checked.u64 %v2, %ten
|
||||
ret %r
|
||||
|
||||
fn @child() -> u64
|
||||
effects []
|
||||
entry:
|
||||
br @spin()
|
||||
spin:
|
||||
task.check_cancel, ok -> @spin, cancelled -> @stop
|
||||
stop:
|
||||
%three = const.u64 3
|
||||
ret %three
|
||||
@@ -0,0 +1,58 @@
|
||||
; Inside a shield cancellation is not observed: the shielded receive waits for
|
||||
; the value; after the shield ends, task.check_cancel sees the pending request.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; result: 105
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_shield
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.spawn, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make u64, %one, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @waiter(%rx)
|
||||
task.cancel %t
|
||||
%txb = borrow.mut %tx
|
||||
%five = const.u64 5
|
||||
channel.send %txb, %five, ok -> @sent, closed -> @back, cancelled -> @back
|
||||
back(%w: u64):
|
||||
br @sent()
|
||||
sent:
|
||||
borrow.end %txb
|
||||
%r = task.join %t
|
||||
task.scope.end %sc
|
||||
channel.close_sender %tx
|
||||
ret %r
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
|
||||
fn @waiter(%rx: receiver<u64>) -> u64
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%sh = task.shield.begin
|
||||
%rb = borrow.mut %rx
|
||||
channel.recv %rb, ok -> @got, closed -> @bad, cancelled -> @bad
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
task.shield.end %sh
|
||||
channel.close_receiver %rx, ok -> @check, pending -> @pending
|
||||
check:
|
||||
task.check_cancel, ok -> @plain, cancelled -> @seen
|
||||
plain:
|
||||
ret %v
|
||||
seen:
|
||||
%hundred = const.u64 100
|
||||
%r = add.checked.u64 %v, %hundred
|
||||
ret %r
|
||||
bad:
|
||||
trap
|
||||
pending(%r2: receiver<u64>):
|
||||
trap
|
||||
@@ -0,0 +1,53 @@
|
||||
; A task waiting in channel.recv observes cancellation on its cancelled edge;
|
||||
; cancellation is a request, so the parent still joins it.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; result: 7
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cancel_wait_recv
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u8
|
||||
effects [mem.alloc, task.spawn, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make u64, %one, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @waiter(%rx)
|
||||
task.cancel %t
|
||||
%r = task.join %t
|
||||
task.scope.end %sc
|
||||
channel.close_sender %tx
|
||||
ret %r
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
|
||||
fn @waiter(%rx: receiver<u64>) -> u8
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%rb = borrow.mut %rx
|
||||
channel.recv %rb, ok -> @got, closed -> @other, cancelled -> @cancelled
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
br @close(%rx)
|
||||
other:
|
||||
borrow.end %rb
|
||||
br @close(%rx)
|
||||
close(%r: receiver<u64>):
|
||||
channel.close_receiver %r, ok -> @wrong, pending -> @pending
|
||||
pending(%r2: receiver<u64>):
|
||||
trap
|
||||
wrong:
|
||||
%z = const.u8 0
|
||||
ret %z
|
||||
cancelled:
|
||||
borrow.end %rb
|
||||
channel.close_receiver %rx, ok -> @done, pending -> @pending
|
||||
done:
|
||||
%seven = const.u8 7
|
||||
ret %seven
|
||||
@@ -0,0 +1,32 @@
|
||||
; The only task waits on a channel whose sender it still holds: no future
|
||||
; event can wake it, so the run ends blocked (not an error, not a trap).
|
||||
; expect: run
|
||||
; blocked: no_future_event
|
||||
; grant: heap=mem.alloc:64
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_blocked
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make u64, %one, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%rb = borrow.mut %rx
|
||||
channel.recv %rb, ok -> @got, closed -> @end, cancelled -> @end
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
channel.close_sender %tx
|
||||
channel.close_receiver %rx, ok -> @fin, pending -> @stuck
|
||||
end:
|
||||
trap
|
||||
fin:
|
||||
ret %v
|
||||
stuck(%p: receiver<u64>):
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,71 @@
|
||||
; Closing a receiver with buffered owned values hands it back on pending; a
|
||||
; send after that ends closed and returns the value; the receiver drains
|
||||
; everything before the close succeeds. No owned value is dropped.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; result: 13
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_drain_linear
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.wait]
|
||||
entry:
|
||||
%four = const.usize 4
|
||||
channel.make own<u64>, %four, %heap, ok -> @made, err -> @oom0
|
||||
made(%tx: sender<own<u64>>, %rx: receiver<own<u64>>):
|
||||
%txb = borrow.mut %tx
|
||||
%one = const.u64 1
|
||||
own.new %one, %heap, ok -> @o1, err -> @oom
|
||||
o1(%a: own<u64>):
|
||||
channel.send %txb, %a, ok -> @s1, closed -> @lost, cancelled -> @lost
|
||||
s1:
|
||||
%two = const.u64 2
|
||||
own.new %two, %heap, ok -> @o2, err -> @oom
|
||||
o2(%b: own<u64>):
|
||||
channel.send %txb, %b, ok -> @s2, closed -> @lost, cancelled -> @lost
|
||||
s2:
|
||||
channel.close_receiver %rx, ok -> @unexpected, pending -> @closing
|
||||
closing(%r: receiver<own<u64>>):
|
||||
%ten = const.u64 10
|
||||
own.new %ten, %heap, ok -> @o3, err -> @oom2
|
||||
o3(%c: own<u64>):
|
||||
channel.send %txb, %c, ok -> @unexpected2, closed -> @back, cancelled -> @back
|
||||
back(%returned: own<u64>):
|
||||
%v0 = own.take %returned
|
||||
br @drain(%r, %v0)
|
||||
drain(%rr: receiver<own<u64>>, %acc: u64):
|
||||
%rb = borrow.mut %rr
|
||||
channel.recv %rb, ok -> @got, closed -> @empty, cancelled -> @retry
|
||||
got(%o: own<u64>):
|
||||
borrow.end %rb
|
||||
%v = own.take %o
|
||||
%acc2 = add.checked.u64 %acc, %v
|
||||
br @drain(%rr, %acc2)
|
||||
retry:
|
||||
borrow.end %rb
|
||||
br @drain(%rr, %acc)
|
||||
empty:
|
||||
borrow.end %rb
|
||||
channel.close_receiver %rr, ok -> @done, pending -> @again
|
||||
again(%r4: receiver<own<u64>>):
|
||||
br @drain(%r4, %acc)
|
||||
done:
|
||||
borrow.end %txb
|
||||
channel.close_sender %tx
|
||||
ret %acc
|
||||
lost(%x: own<u64>):
|
||||
trap
|
||||
unexpected:
|
||||
trap
|
||||
unexpected2:
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
oom2(%e2: alloc_error):
|
||||
trap
|
||||
oom0(%e0: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,72 @@
|
||||
; Two producers share one channel through channel.sender.dup; the receiver
|
||||
; sees closed only after both senders are closed.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; quantum: 2
|
||||
; result: 20
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_mpsc_dup
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.spawn, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make u64, %one, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%txr = borrow.ref %tx
|
||||
%tx2 = channel.sender.dup %txr
|
||||
borrow.end %txr
|
||||
%sc = task.scope.begin
|
||||
%a = task.spawn %sc, @produce(%tx)
|
||||
%b = task.spawn %sc, @produce(%tx2)
|
||||
%z = const.u64 0
|
||||
br @recv_loop(%rx, %z)
|
||||
recv_loop(%r: receiver<u64>, %acc: u64):
|
||||
%rb = borrow.mut %r
|
||||
channel.recv %rb, ok -> @got, closed -> @drained, cancelled -> @drained
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
%acc2 = add.checked.u64 %acc, %v
|
||||
br @recv_loop(%r, %acc2)
|
||||
drained:
|
||||
borrow.end %rb
|
||||
channel.close_receiver %r, ok -> @closed, pending -> @pending
|
||||
pending(%r2: receiver<u64>):
|
||||
br @recv_loop(%r2, %acc)
|
||||
closed:
|
||||
%x = task.join %a
|
||||
%y = task.join %b
|
||||
task.scope.end %sc
|
||||
ret %acc
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
|
||||
; sends 1, 2, 3, 4
|
||||
fn @produce(%tx: sender<u64>) -> u8
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%txb = borrow.mut %tx
|
||||
%one = const.u64 1
|
||||
br @loop(%one)
|
||||
loop(%i: u64):
|
||||
%five = const.u64 5
|
||||
%done = eq.u64 %i, %five
|
||||
cbr %done, @finish(), @send(%i)
|
||||
send(%j: u64):
|
||||
channel.send %txb, %j, ok -> @sent, closed -> @gone, cancelled -> @gone
|
||||
sent:
|
||||
%step = const.u64 1
|
||||
%k = add.checked.u64 %j, %step
|
||||
br @loop(%k)
|
||||
gone(%w: u64):
|
||||
br @finish()
|
||||
finish:
|
||||
borrow.end %txb
|
||||
channel.close_sender %tx
|
||||
%r = const.u8 0
|
||||
ret %r
|
||||
@@ -0,0 +1,66 @@
|
||||
; A producer task sends 0..4 on a bounded channel and closes its sender; the
|
||||
; consumer receives until closed (buffered values first), then closes the receiver.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:1024
|
||||
; schedules: 20
|
||||
; quantum: 3
|
||||
; result: 10
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_producer_consumer
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.spawn, task.wait]
|
||||
entry:
|
||||
%two = const.usize 2
|
||||
channel.make u64, %two, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%sc = task.scope.begin
|
||||
%five = const.u64 5
|
||||
%t = task.spawn %sc, @produce(%tx, %five)
|
||||
%z = const.u64 0
|
||||
br @recv_loop(%rx, %z)
|
||||
recv_loop(%r: receiver<u64>, %acc: u64):
|
||||
%rb = borrow.mut %r
|
||||
channel.recv %rb, ok -> @got, closed -> @drained, cancelled -> @drained
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
%acc2 = add.checked.u64 %acc, %v
|
||||
br @recv_loop(%r, %acc2)
|
||||
drained:
|
||||
borrow.end %rb
|
||||
channel.close_receiver %r, ok -> @closed, pending -> @pending
|
||||
pending(%r2: receiver<u64>):
|
||||
br @recv_loop(%r2, %acc)
|
||||
closed:
|
||||
%x = task.join %t
|
||||
task.scope.end %sc
|
||||
ret %acc
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
|
||||
fn @produce(%tx: sender<u64>, %n: u64) -> u8
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%txb = borrow.mut %tx
|
||||
%zero = const.u64 0
|
||||
br @loop(%zero)
|
||||
loop(%i: u64):
|
||||
%done = eq.u64 %i, %n
|
||||
cbr %done, @finish(), @send(%i)
|
||||
send(%j: u64):
|
||||
channel.send %txb, %j, ok -> @sent, closed -> @gone, cancelled -> @gone
|
||||
sent:
|
||||
%one = const.u64 1
|
||||
%k = add.checked.u64 %j, %one
|
||||
br @loop(%k)
|
||||
gone(%w: u64):
|
||||
br @finish()
|
||||
finish:
|
||||
borrow.end %txb
|
||||
channel.close_sender %tx
|
||||
%r = const.u8 0
|
||||
ret %r
|
||||
@@ -0,0 +1,61 @@
|
||||
; Capacity 0: every send completes only when the receiver takes the value.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; quantum: 2
|
||||
; result: 6
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.channels_rendezvous
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.spawn, task.wait]
|
||||
entry:
|
||||
%zero = const.usize 0
|
||||
channel.make u64, %zero, %heap, ok -> @made, err -> @oom
|
||||
made(%tx: sender<u64>, %rx: receiver<u64>):
|
||||
%sc = task.scope.begin
|
||||
%t = task.spawn %sc, @produce(%tx)
|
||||
%z = const.u64 0
|
||||
br @recv_loop(%rx, %z)
|
||||
recv_loop(%r: receiver<u64>, %acc: u64):
|
||||
%rb = borrow.mut %r
|
||||
channel.recv %rb, ok -> @got, closed -> @drained, cancelled -> @drained
|
||||
got(%v: u64):
|
||||
borrow.end %rb
|
||||
%acc2 = add.checked.u64 %acc, %v
|
||||
br @recv_loop(%r, %acc2)
|
||||
drained:
|
||||
borrow.end %rb
|
||||
channel.close_receiver %r, ok -> @closed, pending -> @pending
|
||||
pending(%r2: receiver<u64>):
|
||||
br @recv_loop(%r2, %acc)
|
||||
closed:
|
||||
%x = task.join %t
|
||||
task.scope.end %sc
|
||||
ret %acc
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
|
||||
fn @produce(%tx: sender<u64>) -> u8
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%txb = borrow.mut %tx
|
||||
%one = const.u64 1
|
||||
channel.send %txb, %one, ok -> @s2, closed -> @gone, cancelled -> @gone
|
||||
s2:
|
||||
%two = const.u64 2
|
||||
channel.send %txb, %two, ok -> @s3, closed -> @gone, cancelled -> @gone
|
||||
s3:
|
||||
%three = const.u64 3
|
||||
channel.send %txb, %three, ok -> @finish, closed -> @gone, cancelled -> @gone
|
||||
gone(%w: u64):
|
||||
br @finish()
|
||||
finish:
|
||||
borrow.end %txb
|
||||
channel.close_sender %tx
|
||||
%r = const.u8 0
|
||||
ret %r
|
||||
@@ -0,0 +1,68 @@
|
||||
; Both arms are ready: the schedule generator picks one (a recorded choice even
|
||||
; in a single task); the other value is received afterwards.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; result: 3
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.select_ready_draw
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make u64, %one, %heap, ok -> @a_made, err -> @oom
|
||||
a_made(%ta: sender<u64>, %ra: receiver<u64>):
|
||||
channel.make u64, %one, %heap, ok -> @b_made, err -> @oom2
|
||||
b_made(%tb: sender<u64>, %rb: receiver<u64>):
|
||||
%tab = borrow.mut %ta
|
||||
%v1 = const.u64 1
|
||||
channel.send %tab, %v1, ok -> @s1, closed -> @lost, cancelled -> @lost
|
||||
s1:
|
||||
%tbb = borrow.mut %tb
|
||||
%v2 = const.u64 2
|
||||
channel.send %tbb, %v2, ok -> @s2, closed -> @lost2, cancelled -> @lost2
|
||||
s2:
|
||||
borrow.end %tab
|
||||
borrow.end %tbb
|
||||
channel.close_sender %ta
|
||||
channel.close_sender %tb
|
||||
%rab = borrow.mut %ra
|
||||
%rbb = borrow.mut %rb
|
||||
select [recv %rab, ok -> @from_a, closed -> @gone], [recv %rbb, ok -> @from_b, closed -> @gone], cancelled -> @gone
|
||||
from_a(%x: u64):
|
||||
channel.recv %rbb, ok -> @second, closed -> @gone, cancelled -> @gone
|
||||
from_b(%y: u64):
|
||||
channel.recv %rab, ok -> @second_b, closed -> @gone, cancelled -> @gone
|
||||
second(%z: u64):
|
||||
%s = add.checked.u64 %x, %z
|
||||
br @finish(%s)
|
||||
second_b(%w: u64):
|
||||
%s2 = add.checked.u64 %y, %w
|
||||
br @finish(%s2)
|
||||
finish(%sum: u64):
|
||||
borrow.end %rab
|
||||
borrow.end %rbb
|
||||
channel.close_receiver %ra, ok -> @ca, pending -> @stuck
|
||||
ca:
|
||||
channel.close_receiver %rb, ok -> @cb, pending -> @stuck2
|
||||
cb:
|
||||
ret %sum
|
||||
gone:
|
||||
trap
|
||||
stuck(%p: receiver<u64>):
|
||||
trap
|
||||
stuck2(%p2: receiver<u64>):
|
||||
trap
|
||||
lost(%l: u64):
|
||||
trap
|
||||
lost2(%l2: u64):
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
oom2(%e2: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,60 @@
|
||||
; The same owned value appears in two send arms: it is consumed only on the
|
||||
; edge of the arm that runs; every other edge hands it back as a parameter.
|
||||
; expect: run
|
||||
; grant: heap=mem.alloc:64
|
||||
; schedules: 20
|
||||
; result: 42
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.select_same_value
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc, task.wait]
|
||||
entry:
|
||||
%one = const.usize 1
|
||||
channel.make own<u64>, %one, %heap, ok -> @a_made, err -> @oom
|
||||
a_made(%ta: sender<own<u64>>, %ra: receiver<own<u64>>):
|
||||
channel.make own<u64>, %one, %heap, ok -> @b_made, err -> @oom2
|
||||
b_made(%tb: sender<own<u64>>, %rb: receiver<own<u64>>):
|
||||
%v = const.u64 42
|
||||
own.new %v, %heap, ok -> @owned, err -> @oom3
|
||||
owned(%x: own<u64>):
|
||||
%tab = borrow.mut %ta
|
||||
%tbb = borrow.mut %tb
|
||||
select [send %tab, %x, ok -> @sent, closed -> @back], [send %tbb, %x, ok -> @sent, closed -> @back], cancelled -> @back
|
||||
back(%returned: own<u64>):
|
||||
trap
|
||||
sent:
|
||||
borrow.end %tab
|
||||
borrow.end %tbb
|
||||
%rab = borrow.mut %ra
|
||||
%rbb = borrow.mut %rb
|
||||
select [recv %rab, ok -> @got, closed -> @none], [recv %rbb, ok -> @got, closed -> @none], cancelled -> @none
|
||||
got(%o: own<u64>):
|
||||
borrow.end %rab
|
||||
borrow.end %rbb
|
||||
%r = own.take %o
|
||||
; senders stay open until now: an empty channel whose senders are closed
|
||||
; would make its receive arm ready with `closed`
|
||||
channel.close_sender %ta
|
||||
channel.close_sender %tb
|
||||
channel.close_receiver %ra, ok -> @ca, pending -> @stuck
|
||||
ca:
|
||||
channel.close_receiver %rb, ok -> @cb, pending -> @stuck2
|
||||
cb:
|
||||
ret %r
|
||||
none:
|
||||
trap
|
||||
stuck(%p: receiver<own<u64>>):
|
||||
trap
|
||||
stuck2(%p2: receiver<own<u64>>):
|
||||
trap
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
oom2(%e2: alloc_error):
|
||||
trap
|
||||
oom3(%e3: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,53 @@
|
||||
; Two tasks increment a shared counter through a mutex lent as ref<mutex<u64>>;
|
||||
; the critical sections never interleave, whatever the schedule.
|
||||
; expect: run
|
||||
; schedules: 30
|
||||
; quantum: 1
|
||||
; result: 10
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.sync_mutex_counter
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, sync, tasks]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%m = mutex.make %z
|
||||
%mr = borrow.ref %m
|
||||
%sc = task.scope.begin
|
||||
%a = task.spawn %sc, @bump(%mr)
|
||||
%b = task.spawn %sc, @bump(%mr)
|
||||
%x = task.join %a
|
||||
%y = task.join %b
|
||||
task.scope.end %sc
|
||||
borrow.end %mr
|
||||
%v = mutex.take %m
|
||||
ret %v
|
||||
|
||||
fn @bump(%mr: ref<mutex<u64>>) -> u8
|
||||
effects [task.wait]
|
||||
entry:
|
||||
%zero = const.u64 0
|
||||
br @loop(%zero)
|
||||
loop(%i: u64):
|
||||
%n = const.u64 5
|
||||
%done = eq.u64 %i, %n
|
||||
cbr %done, @finish(), @lock(%i)
|
||||
lock(%j: u64):
|
||||
mutex.lock %mr, ok -> @locked, cancelled -> @finish
|
||||
locked(%g: guard<u64>):
|
||||
%p = mutex.borrow %g
|
||||
%x = load %p
|
||||
%one = const.u64 1
|
||||
%y = add.checked.u64 %x, %one
|
||||
store %p, %y
|
||||
borrow.end %p
|
||||
mutex.unlock %g
|
||||
%k = add.checked.u64 %j, %one
|
||||
br @loop(%k)
|
||||
finish:
|
||||
%r = const.u8 0
|
||||
ret %r
|
||||
Reference in new issue
Block a user