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

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

No files matched your search

+3 -3
View File
@@ -154,7 +154,7 @@ region.reset(r);
## 7. Concurrency
Tasks and channels work (layer 7). `select`, `lock`/`mutex`, `shield`, `task.check_cancel` and `task.join_cancel` are layer 8, not implemented yet: `aji check` reports them as not implemented (exit code 3).
Tasks, channels, `select`, `lock`/mutex, `shield` and the cancellation operations all work.
```aji
mut d = data; // data: [u64; 8]
@@ -203,13 +203,13 @@ scope s { // every task spawned in s must
```aji
select {
recv(rx_a) { ok(x) => { … } closed => { … } }
recv(rx_a) { ok(x, job) => { … } closed(job) => { … } }
send(tx_b, move job) { ok => { … } closed(job) => { … } }
cancelled(job) => { … }
}
```
Among ready arms, the scheduler's seeded choice decides. Arms where `job` was not sent bind it back.
Among ready arms, the scheduler's seeded choice decides. Every edge where `job` was not sent binds it back, after the edge's own value: `ok(x, job)`.
- **Mutex:**
```aji
+1 -1
View File
@@ -23,7 +23,7 @@ You write `.aji`; you never need to write AIR. Diagnostics point at your source
## Concurrency status
The source frontend implements layers 1–7 of spec 15: task scopes, `task.spawn`/`join`/`cancel`/`cancelled` and channels work. Layer 8 (`lock`/`mutex.*`, `select`, `shield`, `task.check_cancel`, `task.join_cancel`) is not implemented yet: a program that uses it is reported as not implemented (exit code 3). The rules below describe the language as specified.
The source frontend implements every layer of spec 15, concurrency included: task scopes, spawn and join, channels, `select`, `lock` and mutexes, `shield`, `task.check_cancel` and `task.join_cancel`.
## The AIR reference
+1 -1
View File
@@ -89,7 +89,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| 5 | explicit `move` for linear values (`E7003` with the `move x` hint), `own`/`own_array`, regions with an explicit region borrow, outcome matches (match kind decided by the parser), `or trap`, built-in error enums, `cap<mem.alloc>` and `cap.narrow.budget`; linear aggregates stay rejected (`E0006`); `aji lower --stats` reports `mechanical_air_eliminated` | done |
| 6 | intrinsics as plain calls (outcome match / `or trap`), resources by name with a per-operation borrow, explicit closes and data borrows, `cap.narrow.prefix`, byte-string paths, unsafe operations under `effects [unsafe]`, `trusted` rejected, preserved parameter names; source/AIR run-record equivalence (`equivalent:`) for hello, file copy, TCP echo, prefix narrowing, random | done |
| 7 | `scope` blocks, `task.spawn`/`join`/`cancel`/`cancelled`, `task<T>`/`sender<T>`/`receiver<T>`, channels (`make`, `dup`, `send`, `recv`, `close_sender`, `close_receiver`), endpoint operands by name, rebinding of variables on outcome edges, joins carry live variables only; source/AIR equivalence with the Phase 3 task and channel programs | done |
| 8 | `lock`, `select`, cancellation, shields | todo |
| 8 | `lock` blocks over `mutex<T>` (guard never a source value; unlock at every exit), `mutex.make`/`take`, `select` (one borrow per endpoint, unsent values bound back on every edge), `shield`, `task.check_cancel`, `task.join_cancel`; linear values never in frame storage; source/AIR equivalence with the Phase 3 mutex, select and cancellation programs; every Quick Reference example passes | done |
## Tasks (full Phase 6)
+4 -4
View File
@@ -279,17 +279,17 @@ select {
}
```
Arms bind the send values not sent on their edge, in the order of first appearance (spec 04 §39).
Every edge binds its own value (the received `T` of a `recv` arm's `ok`) and then the send values not sent on it, distinct values in the order of first appearance (spec 04 §39). With `send(tx_b, move job)` in the `select`, the `recv` arm's edges are `ok(x, job)` and `closed(job)`, the send arm's are `ok` and `closed(job)`, and the `select`'s own is `cancelled(job)`. A wrong number of names is `E7005`, a missing outcome `E7004`. Each endpoint is borrowed `mut` once for the `select`, even when several arms name it, and the borrow ends on every edge.
**Mutex:**
- `mutex.make(v)`;
- `mutex.make(v)`; to share a mutex with tasks, bind `ref mr = m;` and pass `mr` (a `ref<mutex<T>>`);
- `mutex.take(move m)`, which needs no live borrow of `m`;
- `lock ref m as x { … } cancelled { … }`.
**The `lock` block** lowers to:
1. `mutex.lock` on the borrow `ref m`;
1. `mutex.lock` on the borrow `ref m`: `m` is a `mutex<T>` (borrowed for the lock, the borrow ending after the unlock and on the `cancelled` edge) or a `ref<mutex<T>>` binding (used as it is);
2. on the `ok` edge: `mutex.borrow` of the guard, bound as `x: mut<T>`;
3. the block;
4. `borrow.end x` and `mutex.unlock` of the guard.
@@ -348,7 +348,7 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
## 9. Frame storage, borrow scopes and features
- **Frame storage.** Addressability is a property of lowering, not of source types. A variable whose name is borrowed, indexed, or written through a field or element anywhere in the function lowers to `local<T>` storage, allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The decision is by name, so the same source always gives the same placement. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
- **Frame storage.** Addressability is a property of lowering, not of source types. Linear values (owners, regions, resources, endpoints, tasks, mutexes) never get frame storage: they are borrowed in place. A variable whose name is borrowed, indexed, or written through a field or element anywhere in the function lowers to `local<T>` storage, allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The decision is by name, so the same source always gives the same placement. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
- **Borrow scopes.** A borrow bound by `ref`/`mut` ends at the end of the block that contains the binding. Because a borrow's name is not visible after its scope, a use after the borrow ended (`E2106`) cannot be written in source. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
- **Features.** The frontend emits the `features [...]` header as the dependency closure of the constructs used, always including `effects`.
- **Effects.** They are declared by the programmer. `E3101` names the missing effect and suggests the complete effect list (`suggested_effects`).
+283 -35
View File
@@ -20,7 +20,8 @@
//! outcome matches and `or trap`;
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels.
//! 7. task scopes, spawn and join, channels;
//! 8. `lock` and mutexes, `select`, cancellation points, shields.
const std = @import("std");
const ast = @import("ast.zig");
@@ -59,13 +60,18 @@ pub const Ty = union(enum) {
receiver: *const Ty,
/// A task scope (bound by `scope s { … }`, never written as a type).
scope,
/// `mutex<T>`; `guard<T>` is never a source value (the `lock` block).
mutex: *const Ty,
guard: *const Ty,
/// A shield (`shield { … }`, never a source value).
shield,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope => true,
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield => true,
else => false,
};
}
@@ -76,7 +82,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
@@ -86,7 +92,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -278,9 +284,11 @@ const Lowerer = struct {
rest: std.ArrayList(Rest) = .empty,
/// Set by a loop just before lowering its body: the body's `Rest` frame.
pending_loop: ?LoopAst = null,
/// Set by `scope s { … }` just before lowering its body: a binding and an
/// end that belong to the body's own lexical scope.
pending_entry: ?struct { binding: Binding, end: BorrowEnd } = null,
/// Set by `scope`, `shield` and `lock` just before lowering a body:
/// bindings and ends that belong to the body's own lexical scope (ends
/// in creation order; they run innermost first at every normal exit).
pending_bindings: std.ArrayList(Binding) = .empty,
pending_ends: std.ArrayList(BorrowEnd) = .empty,
/// Borrows to end at the end of each open lexical scope (innermost last).
scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty,
/// `local.alloc` instructions; they go first in the entry block.
@@ -311,8 +319,9 @@ const Lowerer = struct {
.never => "never",
.named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| blk: {
@@ -427,7 +436,9 @@ const Lowerer = struct {
.{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
.{ "tasks", &.{ "task.", "task<", ": scope" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<", "select [" } },
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
@@ -498,7 +509,7 @@ const Lowerer = struct {
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try l.typeOf(w.inner.*);
return switch (which) {
@@ -511,6 +522,7 @@ const Lowerer = struct {
.task => l.wrap(.task, in),
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
.mutex => l.wrap(.mutex, in),
};
},
.cap => |k| {
@@ -768,10 +780,11 @@ const Lowerer = struct {
const saved_start = l.scope_binding_start;
l.scope_binding_start = depth;
defer l.scope_binding_start = saved_start;
if (l.pending_entry) |pe| {
l.pending_entry = null;
try l.bindings.append(l.arena, pe.binding);
try l.scopes.items[l.scopes.items.len - 1].append(l.arena, pe.end);
if (l.pending_bindings.items.len != 0 or l.pending_ends.items.len != 0) {
try l.bindings.appendSlice(l.arena, l.pending_bindings.items);
try l.scopes.items[l.scopes.items.len - 1].appendSlice(l.arena, l.pending_ends.items);
l.pending_bindings = .empty;
l.pending_ends = .empty;
}
for (b.stmts, 0..) |s, i| {
if (l.cur == null) return l.fail("E7006", s.span, "unreachable statement", &.{});
@@ -850,7 +863,9 @@ const Lowerer = struct {
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
if (v.ty == .void or v.ty == .never) return l.fail("E7005", x.e.span, "this expression has no value", &.{});
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
if (l.addressable.contains(x.names[0])) {
// Linear values (owners, regions, resources, endpoints, tasks,
// mutexes) are borrowed in place, never moved to frame storage.
if (l.addressable.contains(x.names[0]) and !v.ty.isLinear()) {
const st = try l.storageFor(x.names[0], v.ty, s.span);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage });
@@ -859,7 +874,7 @@ const Lowerer = struct {
.@"var" => |x| {
const ty = try l.typeOf(x.ty);
if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
if (l.addressable.contains(x.name)) {
if (l.addressable.contains(x.name) and !ty.isLinear()) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.consuming(e, ty);
@@ -943,12 +958,19 @@ const Lowerer = struct {
// `scope s { … }`: task.scope.begin, and task.scope.end at every
// normal exit of the block (spec 15 §7).
const sv = try l.def(x.name, .scope, "task.scope.begin", s.span);
l.pending_entry = .{ .binding = .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope }, .end = .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" } };
try l.pending_bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope });
try l.pending_ends.append(l.arena, .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" });
_ = try l.blockBody(x.body);
},
.shield => return l.notYet(s.span, "`shield` (layer 8)"),
.lock => return l.notYet(s.span, "`lock` (layer 8)"),
.select => return l.notYet(s.span, "`select` (layer 8)"),
.shield => |b| {
// `shield { … }`: task.shield.begin, and task.shield.end at every
// normal exit; shields nest by construction (spec 15 §7).
const sh = try l.def("sh", .shield, "task.shield.begin", s.span);
try l.pending_ends.append(l.arena, .{ .name = sh.name, .span = b.span, .op = "task.shield.end" });
_ = try l.blockBody(b);
},
.lock => |x| try l.lockStmt(s, x.place, x.name, x.body, x.cancelled),
.select => |x| try l.selectStmt(s, x),
}
}
@@ -1826,7 +1848,7 @@ const Lowerer = struct {
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.resource, .mutex, .sender, .receiver, .task => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
@@ -2080,7 +2102,7 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver" };
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2169,6 +2191,17 @@ const Lowerer = struct {
try l.endNow(temps.items, e.span);
return v;
}
if (eq(p, "mutex.make")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
const v = try l.consuming(args[0], null);
return try l.def("m", try l.wrap(.mutex, v.ty), try l.fmt("mutex.make %{s}", .{v.name}), e.span);
}
if (eq(p, "mutex.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{});
const m = try l.consuming(args[0], null);
if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex<T>`", &.{.{ .name = "found", .value = l.tyText(m.ty) }});
return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span);
}
if (eq(p, "channel.close_sender")) {
if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{});
const tx = try l.consuming(args[0], null);
@@ -2179,6 +2212,189 @@ const Lowerer = struct {
return null;
}
/// `lock ref m as x { body } cancelled { cb }` (spec 15 §7): `mutex.lock`
/// on a shared borrow of the mutex; on `ok`, `mutex.borrow` of the guard
/// bound as `x: mut<T>`, and at every normal exit of the body
/// `borrow.end x` then `mutex.unlock`. The guard is never a source value.
fn lockStmt(l: *Lowerer, s: ast.Stmt, place: ast.Expr, name: []const u8, body: ast.Block, cancelled: ast.Block) Error!void {
// The mutex: a `ref<mutex<T>>` binding, or a mutex borrowed for the lock.
var temps: std.ArrayList([]const u8) = .empty;
if (place.kind != .name) return l.fail("E7005", place.span, "`lock ref m`: the mutex or a `ref<mutex<T>>` binding, by name", &.{});
const b = l.lookup(place.kind.name) orelse return l.unknown(place.span, place.kind.name);
const mr: Value = switch (b.ty) {
.mutex => blk: {
const v = try l.def(place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), place.span);
try temps.append(l.arena, v.name);
break :blk v;
},
.ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}),
else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}),
};
const elem = mr.ty.ref.mutex.*;
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const before = try l.snapshot();
const locked = try l.newBlock("locked");
const guard = try l.freshName("guard");
try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) });
const canc = try l.newBlock("lock_cancelled");
try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
l.cur = locked;
const x = try l.def(name, try l.wrap(.mut, elem), try l.fmt("mutex.borrow %{s}", .{guard}), s.span);
for (temps.items) |t| try l.pending_ends.append(l.arena, .{ .name = t, .span = body.span });
try l.pending_ends.append(l.arena, .{ .name = guard, .span = body.span, .op = "mutex.unlock" });
try l.pending_ends.append(l.arena, .{ .name = x.name, .span = body.span });
try l.pending_bindings.append(l.arena, .{ .name = name, .mutable = false, .value = x.name, .ty = x.ty, .kind = .borrow });
const bv = try l.blockBody(body);
try ends.append(l.arena, .{ .block = l.cur, .value = bv, .values = try l.snapshot(), .span = body.span });
l.restore(before);
l.cur = canc;
try l.endNow(temps.items, cancelled.span);
const cv = try l.blockBody(cancelled);
try ends.append(l.arena, .{ .block = l.cur, .value = cv, .values = try l.snapshot(), .span = cancelled.span });
_ = try l.mergeArms(s.span, "lock", ends.items, vars, before, "endlock");
}
/// `select { recv(rx) { … } send(tx, v) { … } cancelled(…) => … }`
/// (spec 15 §7, spec 04 §39). Each endpoint is borrowed once for the
/// operation. `V` is the distinct send values in order of first
/// appearance; every edge binds its own value (a received `T`) and then
/// the values of `V` not sent on it.
fn selectStmt(l: *Lowerer, s: ast.Stmt, sel: ast.Select) Error!void {
if (sel.arms.len == 0) return l.fail("E7006", s.span, "a `select` has at least one `recv` or `send` arm", &.{});
const Sent = struct { key: ?[]const u8, v: Value };
var values: std.ArrayList(Sent) = .empty;
const arm_value = try l.arena.alloc(?usize, sel.arms.len);
// Values first (as for an assignment), then the endpoint borrows.
for (sel.arms, arm_value) |a, *av| {
av.* = null;
const ve = a.value orelse continue;
const key: ?[]const u8 = switch (ve.kind) {
.move, .name => |n| n,
else => null,
};
if (key) |k| for (values.items, 0..) |x, i| if (x.key != null and std.mem.eql(u8, x.key.?, k)) {
av.* = i;
break;
};
if (av.* == null) {
const v = try l.consuming(ve, null);
try values.append(l.arena, .{ .key = key, .v = v });
av.* = values.items.len - 1;
}
}
var temps: std.ArrayList([]const u8) = .empty;
const Ep = struct { name: []const u8, v: Value };
var eps: std.ArrayList(Ep) = .empty;
const arm_ep = try l.arena.alloc(Value, sel.arms.len);
for (sel.arms, arm_ep, 0..) |a, *ae, ai| {
const found = for (eps.items) |x| {
if (std.mem.eql(u8, x.name, a.endpoint)) break x.v;
} else null;
ae.* = found orelse blk: {
const ex: ast.Expr = .{ .span = a.span, .kind = .{ .name = a.endpoint } };
const v = try l.endpointOperand(ex, if (a.send) .sender else .receiver, true, &temps);
try eps.append(l.arena, .{ .name = a.endpoint, .v = v });
break :blk v;
};
if (a.send) {
const et = ae.ty.inner().?.sender.*;
try l.checkTy(a.value.?.span, values.items[arm_value[ai].?].v.ty, et);
}
}
// Edges: per arm `ok` and `closed`, then `cancelled`.
const Edge = struct { arm: ?usize, role: []const u8, params: []const Ty, values: []const usize, block: usize = 0 };
var edges: std.ArrayList(Edge) = .empty;
const notSent = struct {
fn f(lw: *Lowerer, n: usize, sent: ?usize) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (0..n) |i| if (sent == null or sent.? != i) try out.append(lw.arena, i);
return out.items;
}
}.f;
for (sel.arms, 0..) |a, i| {
if (a.send) {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = &.{}, .values = try notSent(l, values.items.len, arm_value[i]) });
} else {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = try l.arena.dupe(Ty, &.{arm_ep[i].ty.inner().?.receiver.*}), .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = i, .role = "closed", .params = &.{}, .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = null, .role = "cancelled", .params = &.{}, .values = try notSent(l, values.items.len, null) });
// Every outcome of every arm is matched exactly once.
for (sel.arms) |a| {
for (a.arms, 0..) |arm, k| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.fail("E7006", arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
const c = arm.pattern.kind.ctor;
if (!std.mem.eql(u8, c.name, "ok") and !std.mem.eql(u8, c.name, "closed")) return l.fail("E7002", arm.pattern.span, "a `select` arm has the outcomes `ok` and `closed`; `cancelled` is the `select`'s own arm", &.{.{ .name = "outcome", .value = c.name }});
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
}
for ([_][]const u8{ "ok", "closed" }) |role| {
const covered = for (a.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, role)) break true;
} else false;
if (!covered) return l.fail("E7004", a.span, "the arm does not handle every outcome", &.{.{ .name = "missing", .value = role }});
}
}
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const before = try l.snapshot();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
for (edges.items) |*ed| {
ed.block = try l.newBlock(ed.role);
for (ed.params) |pt| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = pt });
for (ed.values) |vi| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = values.items[vi].v.ty });
}
for (sel.arms, 0..) |a, i| {
const okb = edges.items[2 * i].block;
const clb = edges.items[2 * i + 1].block;
if (a.send) {
try text.appendSlice(l.arena, try l.fmt("[send %{s}, %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, values.items[arm_value[i].?].v.name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
} else {
try text.appendSlice(l.arena, try l.fmt("[recv %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
}
}
try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name}));
try l.term(text.items, s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (edges.items) |ed| {
const binds: []const []const u8, const body: ast.Expr, const pspan: Span = if (ed.arm) |ai| blk: {
const a = sel.arms[ai];
const arm = for (a.arms) |x| {
if (std.mem.eql(u8, x.pattern.kind.ctor.name, ed.role)) break x;
} else unreachable;
break :blk .{ arm.pattern.kind.ctor.binds, arm.body, arm.pattern.span };
} else .{ sel.cancelled_binds, sel.cancelled, sel.span };
const params = l.blocks.items[ed.block].params.items;
if (binds.len != params.len) return l.fail("E7005", pspan, "the edge binds its own value, then the values not sent on it, in order of first appearance", &.{ .{ .name = "outcome", .value = ed.role }, .{ .name = "expected", .value = try l.fmt("{d}", .{params.len}) } });
l.restore(before);
l.cur = ed.block;
try l.endNow(temps.items, pspan);
try l.scopes.append(l.arena, .empty);
for (binds, params) |bn, prm| {
if (std.mem.eql(u8, bn, "_")) continue;
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
old.value = prm.name;
continue;
};
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
}
const v = try l.armBody(body, null);
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, body.span);
_ = l.scopes.pop();
l.bindings.shrinkRetainingCapacity(before.len);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = body.span });
}
_ = try l.mergeArms(s.span, "select", ends.items, vars, before, "endselect");
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
@@ -2262,7 +2478,6 @@ const Lowerer = struct {
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
if (e.kind != .call) return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
if (laterLayer(e.kind.call.callee.*)) return l.notYet(e.span, "this operation (layer 8)");
const path = pathOf(e.kind.call.callee.*) orelse return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
const args = e.kind.call.args;
const want = struct {
@@ -2319,6 +2534,18 @@ const Lowerer = struct {
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "task.check_cancel")) {
try want(l, e.span, args, 0, path);
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
}
if (std.mem.eql(u8, path, "task.join_cancel")) {
try want(l, e.span, args, 1, path);
const t = try l.consuming(args[0], null);
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task<T>`", &.{.{ .name = "found", .value = l.tyText(t.ty) }});
const rt = t.ty.task.*;
const ok: []const Ty = if (rt == .void) &.{} else &.{rt};
return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) };
}
if (std.mem.eql(u8, path, "channel.make")) {
try want(l, e.span, args, 2, path);
const ta = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "`channel.make` names its element type: `channel.make<T>(n, mem)`", &.{});
@@ -2535,14 +2762,6 @@ fn elemOf(t: Ty) ?Ty {
};
}
/// `task.check_cancel`, `task.join_cancel`, `mutex.*`: operations of layer 8.
fn laterLayer(e: ast.Expr) bool {
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return false;
for ([_][]const u8{ "task.check_cancel", "task.join_cancel", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true;
return false;
}
/// The built-in operation named by a callee such as `own.new` or
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
@@ -2551,7 +2770,8 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
"task.join_cancel",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
@@ -2635,8 +2855,7 @@ fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool {
.loop, .shield => |b| blockReads(b, name, skip),
.scope => |x| blockReads(x.body, name, skip),
.lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip),
// Layer 8; until then, assume it reads everything.
.select => true,
.select => |x| selectReads(x, name, skip),
.@"break", .@"continue", .trap => false,
};
}
@@ -2673,6 +2892,15 @@ fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
};
}
fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool {
for (x.arms) |a| {
if (std.mem.eql(u8, a.endpoint, name)) return true;
if (a.value) |v| if (exprReads(v, name, skip)) return true;
for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true;
}
return exprReads(x.cancelled, name, skip);
}
fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool {
if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true;
if (x.@"else") |els| return switch (els) {
@@ -2732,6 +2960,26 @@ const After = struct {
};
}
fn select(w: *After, x: ast.Select) bool {
for (x.arms) |a| {
if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true;
if (a.value) |v| if (w.expr(v)) return true;
}
var bodies: std.ArrayList(ast.Expr) = .empty;
defer bodies.deinit(std.heap.page_allocator);
for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true;
bodies.append(std.heap.page_allocator, x.cancelled) catch return true;
if (w.seen) {
for (bodies.items) |b| if (w.expr(b)) return true;
return false;
}
for (bodies.items) |b| {
const r = w.expr(b);
if (w.seen) return r;
}
return false;
}
fn ifExpr(w: *After, x: ast.If) bool {
if (w.expr(x.cond)) return true;
if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false);
@@ -2782,7 +3030,7 @@ const After = struct {
.shield => |b| w.block(b),
.scope => |x| w.block(x.body),
.lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled),
.select => w.seen,
.select => |x| w.select(x),
.@"break", .@"continue", .trap => false,
};
}
@@ -0,0 +1,50 @@
// A cancelled parent forwards cancellation to its child explicitly: join_cancel
// hands the child back on `cancelled`; the parent cancels and joins it.
// expect: run
// schedules: 20
// result: 13
// equivalent: phase3/run/cancel_join_forward.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.canceljoinforward
fn child() -> u64
effects []
{
loop {
match task.check_cancel() {
ok => {}
cancelled => { break; }
}
}
3
}
fn parent() -> u64
effects [task.spawn, task.wait]
{
var r: u64 = 0;
scope sc {
let c = task.spawn(sc, child);
match task.join_cancel(move c) {
ok(v) => { r = v; }
cancelled(c) => {
task.cancel(c);
r = task.join(move c) + 10;
}
}
}
r
}
fn main() -> u64
effects [task.spawn, task.wait]
{
var r: u64 = 0;
scope sc {
let p = task.spawn(sc, parent);
task.cancel(p);
r = task.join(move p);
}
r
}
@@ -0,0 +1,47 @@
// A shielded receive is not cancelled; after the shield the task observes the
// pending cancellation at task.check_cancel.
// expect: run
// grant: heap=mem.alloc:64
// schedules: 20
// result: 105
// equivalent: phase3/run/cancel_shield.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.cancelshield
fn waiter(rx: receiver<u64>) -> u64
effects [task.wait]
{
var v: u64 = 0;
shield {
v = channel.recv(rx) or trap;
}
channel.close_receiver(move rx) or trap;
match task.check_cancel() {
ok => v,
cancelled => v + 100,
}
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
var r: u64 = 0;
scope sc {
let t = task.spawn(sc, waiter, move rx);
task.cancel(t);
match channel.send(tx, 5u64) {
ok => {}
closed(w) => {}
cancelled(w) => {}
}
r = task.join(move t);
}
channel.close_sender(move tx);
r
}
err(e) => { trap; }
}
}
@@ -0,0 +1,47 @@
// 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
// equivalent: phase3/run/cancel_wait_recv.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.cancelwaitrecv
fn waiter(rx: receiver<u64>) -> u8
effects [task.wait]
{
match channel.recv(rx) {
ok(v) => {
channel.close_receiver(move rx) or trap;
0
}
closed => {
channel.close_receiver(move rx) or trap;
0
}
cancelled => {
channel.close_receiver(move rx) or trap;
7
}
}
}
fn main(heap: cap<mem.alloc>) -> u8
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
var r: u8 = 0;
scope sc {
let t = task.spawn(sc, waiter, move rx);
task.cancel(t);
r = task.join(move t);
}
channel.close_sender(move tx);
r
}
err(e) => { trap; }
}
}
@@ -0,0 +1,41 @@
// Two tasks increment a shared counter under a mutex; the lock block unlocks at
// every exit; mutex.take dismantles the mutex once no borrow is live.
// expect: run
// schedules: 30
// quantum: 1
// result: 10
// equivalent: phase3/run/sync_mutex_counter.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.mutexcounter
fn bump(mr: ref<mutex<u64>>) -> u8
effects [task.wait]
{
var i: u64 = 0;
while i != 5 {
lock ref mr as count {
*count = *count + 1;
} cancelled {
return 0;
}
i = i + 1;
}
0
}
fn main() -> u64
effects [task.spawn, task.wait]
{
let m = mutex.make(0u64);
{
ref mr = m;
scope sc {
let a = task.spawn(sc, bump, mr);
let b = task.spawn(sc, bump, mr);
let x = task.join(move a);
let y = task.join(move b);
}
}
mutex.take(move m)
}
@@ -0,0 +1,51 @@
module demo.mutexcounter
air 0
lang 0.1
features [cancellation, effects, ownership, sync, tasks]
fn @bump(%mr: ref<mutex<u64>>) -> u8
effects [task.wait]
entry:
%c_1 = const.u64 0
br @while_2(%c_1)
while_2(%i_4: u64):
%c_5 = const.u64 5
%cmp_6 = ne.u64 %i_4, %c_5
cbr %cmp_6, @body_7(), @after_3()
after_3:
%c_20 = const.u8 0
ret %c_20
body_7:
mutex.lock %mr, ok -> @locked_8, cancelled -> @lock_cancelled_10
locked_8(%guard_9: guard<u64>):
%count_11 = mutex.borrow %guard_9
%v_12 = load %count_11
%c_13 = const.u64 1
%t_14 = add.checked.u64 %v_12, %c_13
store %count_11, %t_14
borrow.end %count_11
mutex.unlock %guard_9
br @endlock_16(%i_4)
lock_cancelled_10:
%c_15 = const.u8 0
ret %c_15
endlock_16(%i_17: u64):
%c_18 = const.u64 1
%t_19 = add.checked.u64 %i_17, %c_18
br @while_2(%t_19)
fn @main() -> u64
effects [task.spawn, task.wait]
entry:
%c_1 = const.u64 0
%m_2 = mutex.make %c_1
%m_3 = borrow.ref %m_2
%sc_4 = task.scope.begin
%t_5 = task.spawn %sc_4, @bump(%m_3)
%t_6 = task.spawn %sc_4, @bump(%m_3)
%r_7 = task.join %t_5
%r_8 = task.join %t_6
task.scope.end %sc_4
borrow.end %m_3
%v_9 = mutex.take %m_2
ret %v_9
@@ -0,0 +1,21 @@
// Calling a function whose effects include task.wait inside a `lock` block is E4304.
// expect: reject E4304
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.call_waiting_function
fn pause() -> void
effects [task.wait]
{
}
fn main() -> u64
effects [task.wait]
{
let m = mutex.make(0u64);
lock ref m as c {
pause();
*c = 1;
} cancelled {}
mutex.take(move m)
}
@@ -0,0 +1,33 @@
// On the `cancelled` edge of task.join_cancel the task is not joined: its loans stay, so touching the lent data is E4101.
// expect: reject E4101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.cancelled_keeps_loans
fn bump(s: slice_mut<u64>) -> u64
effects []
{
s[0] = s[0] + 1;
s[0]
}
fn main() -> u64
effects [task.spawn, task.wait]
{
var buf: [u64; 2] = zero;
var r: u64 = 0;
{
mut s = buf;
scope sc {
let t = task.spawn(sc, bump, s);
match task.join_cancel(move t) {
ok(v) => { r = v; }
cancelled(t) => {
s[0] = 9;
r = task.join(move t);
}
}
}
}
r
}
@@ -0,0 +1,25 @@
// task.join_cancel waits, and so does the join on its cancelled edge: both require task.wait (E3101 at each).
// expect: reject E3101 E3101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.join_cancel_needs_wait
fn work() -> u64
effects []
{
1
}
fn main() -> u64
effects [task.spawn]
{
var r: u64 = 0;
scope sc {
let t = task.spawn(sc, work);
match task.join_cancel(move t) {
ok(v) => { r = v; }
cancelled(t) => { r = task.join(move t); }
}
}
r
}
@@ -0,0 +1,15 @@
// `lock` needs a mutex.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.lock_not_mutex
fn main() -> u64
effects [task.wait]
{
var x: u64 = 1;
lock ref x as c {
*c = 2;
} cancelled {}
x
}
@@ -0,0 +1,18 @@
// A second lock while one is held waits while locked (E4304): lock-order deadlocks cannot be written.
// expect: reject E4304
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.lock_twice
fn main() -> u64
effects [task.wait]
{
let a = mutex.make(0u64);
let b = mutex.make(0u64);
lock ref a as x {
lock ref b as y {
*y = *x;
} cancelled {}
} cancelled {}
mutex.take(move a) + mutex.take(move b)
}
@@ -0,0 +1,24 @@
// Every `select` edge binds its own value and then the values not sent on it: `ok(x)` misses `job`.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.select_bind_count
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<own<u64>>(1, heap) {
ok(tx, rx) => {
let job = own.new(1u64, heap) or trap;
select {
recv(rx) { ok(x) => { own.free(move x); } closed(job) => { own.free(move job); } }
send(tx, move job) { ok => {} closed(job) => { own.free(move job); } }
cancelled(job) => { own.free(move job); }
}
channel.close_sender(move tx);
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,22 @@
// A `select` arm handles both of its outcomes.
// expect: reject E7004
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.select_missing_outcome
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
channel.close_sender(move tx);
select {
recv(rx) { ok(x) => {} }
cancelled => {}
}
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,13 @@
// mutex.take while a borrow of the mutex is live is E2101.
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.take_while_borrowed
fn main() -> u64
effects []
{
let m = mutex.make(1u64);
ref mr = m;
mutex.take(move m)
}
@@ -0,0 +1,16 @@
// A mutex locked after mutex.take: the verifier reports use after consume (E3001).
// expect: reject E3001
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.use_after_take
fn main() -> u64
effects [task.wait]
{
let m = mutex.make(1u64);
let v = mutex.take(move m);
lock ref m as c {
*c = 2;
} cancelled {}
v
}
@@ -0,0 +1,22 @@
// A waiting operation inside a `lock` block breaks the critical-section rule (E4304).
// expect: reject E4304
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.wait_while_locked
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
let m = mutex.make(0u64);
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
lock ref m as c {
*c = channel.recv(rx) or trap;
} cancelled {}
channel.close_sender(move tx);
channel.close_receiver(move rx) or trap;
}
err(e) => { trap; }
}
mutex.take(move m)
}
@@ -0,0 +1,38 @@
// Two ready receive arms: the scheduler's seeded draw picks one; the other value is
// received afterwards; the sum does not depend on the draw.
// expect: run
// grant: heap=mem.alloc:64
// schedules: 20
// result: 3
// equivalent: phase3/run/select_ready_draw.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.selectdraw
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<u64>(1, heap) {
ok(ta, ra) => {
match channel.make<u64>(1, heap) {
ok(tb, rb) => {
channel.send(ta, 1u64) or trap;
channel.send(tb, 2u64) or trap;
channel.close_sender(move ta);
channel.close_sender(move tb);
var sum: u64 = 0;
select {
recv(ra) { ok(x) => { sum = x + (channel.recv(rb) or trap); } closed => { trap; } }
recv(rb) { ok(y) => { sum = y + (channel.recv(ra) or trap); } closed => { trap; } }
cancelled => { trap; }
}
channel.close_receiver(move ra) or trap;
channel.close_receiver(move rb) or trap;
sum
}
err(e) => { trap; }
}
}
err(e) => { trap; }
}
}
@@ -0,0 +1,42 @@
// The same owned value in two send arms: it is consumed only on the edge of the arm
// that runs; every other edge hands it back.
// expect: run
// grant: heap=mem.alloc:64
// schedules: 20
// result: 42
// equivalent: phase3/run/select_same_value.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.selectsamevalue
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<own<u64>>(1, heap) {
ok(ta, ra) => {
match channel.make<own<u64>>(1, heap) {
ok(tb, rb) => {
let x = own.new(42u64, heap) or trap;
select {
send(ta, move x) { ok => {} closed(x) => { trap; } }
send(tb, move x) { ok => {} closed(x) => { trap; } }
cancelled(x) => { trap; }
}
var r: u64 = 0;
select {
recv(ra) { ok(o) => { r = own.take(move o); } closed => { trap; } }
recv(rb) { ok(o) => { r = own.take(move o); } closed => { trap; } }
cancelled => { trap; }
}
channel.close_sender(move ta);
channel.close_sender(move tb);
channel.close_receiver(move ra) or trap;
channel.close_receiver(move rb) or trap;
r
}
err(e) => { trap; }
}
}
err(e) => { trap; }
}
}
@@ -0,0 +1,89 @@
module demo.selectsamevalue
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:
%c_1 = const.usize 1
channel.make own<u64>, %c_1, %heap, ok -> @ok_2, err -> @err_5
ok_2(%ok_3: sender<own<u64>>, %ok_4: receiver<own<u64>>):
%c_7 = const.usize 1
channel.make own<u64>, %c_7, %heap, ok -> @ok_8, err -> @err_11
err_5(%err_6: alloc_error):
trap
ok_8(%ok_9: sender<own<u64>>, %ok_10: receiver<own<u64>>):
%c_13 = const.u64 42
own.new %c_13, %heap, ok -> @ok_14, err -> @err_16
err_11(%err_12: alloc_error):
trap
ok_14(%ok_15: own<u64>):
%ta_18 = borrow.mut %ok_3
%tb_19 = borrow.mut %ok_9
select [send %ta_18, %ok_15, ok -> @ok_20, closed -> @closed_21], [send %tb_19, %ok_15, ok -> @ok_23, closed -> @closed_24], cancelled -> @cancelled_26
err_16(%err_17: alloc_error):
trap
ok_20:
borrow.end %tb_19
borrow.end %ta_18
br @endselect_28()
closed_21(%closed_22: own<u64>):
borrow.end %tb_19
borrow.end %ta_18
trap
ok_23:
borrow.end %tb_19
borrow.end %ta_18
br @endselect_28()
closed_24(%closed_25: own<u64>):
borrow.end %tb_19
borrow.end %ta_18
trap
cancelled_26(%cancelled_27: own<u64>):
borrow.end %tb_19
borrow.end %ta_18
trap
endselect_28:
%c_29 = const.u64 0
%ra_30 = borrow.mut %ok_4
%rb_31 = borrow.mut %ok_10
select [recv %ra_30, ok -> @ok_32, closed -> @closed_34], [recv %rb_31, ok -> @ok_35, closed -> @closed_37], cancelled -> @cancelled_38
ok_32(%ok_33: own<u64>):
borrow.end %rb_31
borrow.end %ra_30
%v_39 = own.take %ok_33
br @endselect_41(%v_39)
closed_34:
borrow.end %rb_31
borrow.end %ra_30
trap
ok_35(%ok_36: own<u64>):
borrow.end %rb_31
borrow.end %ra_30
%v_40 = own.take %ok_36
br @endselect_41(%v_40)
closed_37:
borrow.end %rb_31
borrow.end %ra_30
trap
cancelled_38:
borrow.end %rb_31
borrow.end %ra_30
trap
endselect_41(%r_42: u64):
channel.close_sender %ok_3
channel.close_sender %ok_9
channel.close_receiver %ok_4, ok -> @ok_43, pending -> @pending_44
ok_43:
channel.close_receiver %ok_10, ok -> @ok_46, pending -> @pending_47
pending_44(%pending_45: receiver<own<u64>>):
trap
ok_46:
br @endmatch_49(%r_42)
pending_47(%pending_48: receiver<own<u64>>):
trap
endmatch_49(%match_50: u64):
br @endmatch_51(%match_50)
endmatch_51(%match_52: u64):
ret %match_52
+6 -6
View File
@@ -9,21 +9,21 @@ module demo.qrselect
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
let job = 9u64;
var which: u64 = 0;
match channel.make<u64>(1, heap) {
ok(tx_a, rx_a) => {
match channel.make<u64>(1, heap) {
match channel.make<own<u64>>(1, heap) {
ok(tx_b, rx_b) => {
let job = own.new(9u64, heap) or trap;
channel.close_sender(move tx_a);
select {
recv(rx_a) { ok(x) => { which = 2; } closed => { which = 1; } }
send(tx_b, move job) { ok => { which = 1; } closed(job) => { which = 3; } }
cancelled(job) => { trap; }
recv(rx_a) { ok(x, job) => { own.free(move job); which = 2; } closed(job) => { own.free(move job); which = 1; } }
send(tx_b, move job) { ok => { which = 1; } closed(job) => { own.free(move job); which = 3; } }
cancelled(job) => { own.free(move job); trap; }
}
channel.close_sender(move tx_b);
match channel.close_receiver(move rx_a) { ok => {} pending(rx_a) => { trap; } }
match channel.recv(rx_b) { ok(v) => {} closed => {} cancelled => { trap; } }
match channel.recv(rx_b) { ok(v) => { own.free(move v); } closed => {} cancelled => { trap; } }
match channel.close_receiver(move rx_b) { ok => {} pending(rx_b) => { trap; } }
}
err(e) => { trap; }