Phase 6A: .aji layer 7 (task scopes, spawn/join, channels)

- scope s { … }: task.scope.begin, task.scope.end at every normal exit
  (scope ends generalized: borrow.end or task.scope.end, innermost first)
- task.spawn(s, f, args): call-like; named linear values moved (E7003);
  lent borrows are bound first (inline borrow E7006); scope operand E7005
- task.join/cancel/cancelled; task<T>, sender<T>, receiver<T>, scope types
- channels: make<T>, dup, send, recv, close_sender, close_receiver; send,
  recv and close_receiver are outcome matches; endpoints by name, borrowed
  for the operation and ended on every edge (written `mut tx`: E7006)
- outcome rebinding: a value coming back under the name of a variable of
  its type becomes the variable's value (pending(r))
- joins carry live variables only (pruned SSA): a linear value consumed
  before a join does not travel to it; ordered after-walk over the
  enclosing statement or tail, sibling arms not counted
- parser: a keyword after `.` is a member name (task.cancelled)
- conformance equivalence ignores schedule.choices (quantum counts AIR
  instructions)
- tests: 10 run tests with AIR equivalence (Phase 3 programs), 12 rejects
  (E4301, E4101 x2, E4002, E2001, E3101, E3002, E7006 x2, E7003, E0006,
  E7005); Quick Reference tasks/channels programs now pass
- spec 15 §4/§6/§7, grammar, quick reference, bundle notes, plan
This commit is contained in:
dev committed 2026-10-05 17:55:30 +03:00
1 parent c2c238d9b1
commit 179dee3c3a
32 files changed
+1315 -41

No files matched your search

+1 -1
View File
@@ -154,7 +154,7 @@ region.reset(r);
## 7. Concurrency ## 7. Concurrency
Not implemented in the source frontend yet (layers 7–8): `aji check` reports these constructs as not implemented (exit code 3). They are shown as specified. 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).
```aji ```aji
mut d = data; // data: [u64; 8] mut d = data; // data: [u64; 8]
+1 -1
View File
@@ -23,7 +23,7 @@ You write `.aji`; you never need to write AIR. Diagnostics point at your source
## Concurrency status ## Concurrency status
The source frontend implements layers 1–6 of spec 15. Layers 7 (tasks, channels) and 8 (`lock`, `select`, cancellation, shields) are not implemented yet: a program that uses `scope`, `task.*`, `channel.*`, `mutex.*`, `lock`, `select` or `shield` is reported as not implemented (exit code 3). The rules below describe the language as specified. 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 AIR reference ## The AIR reference
+1 -1
View File
@@ -88,7 +88,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| 3–4 | addressable values (frame storage chosen by lowering), lexical borrows (`ref r = …;`/`mut r = …;`), places and writes, arrays, slices, `split_at`, `slice.copy`, byte strings, proven indexing for the verifier's fact form; `move` comes with linear values in layer 5 | done | | 3–4 | addressable values (frame storage chosen by lowering), lexical borrows (`ref r = …;`/`mut r = …;`), places and writes, arrays, slices, `split_at`, `slice.copy`, byte strings, proven indexing for the verifier's fact form; `move` comes with linear values in layer 5 | done |
| 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 | | 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 | | 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 | tasks, channels | todo | | 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`, `select`, cancellation, shields | todo |
## Tasks (full Phase 6) ## Tasks (full Phase 6)
+3 -1
View File
@@ -83,7 +83,8 @@ unary = ( "-" | "not" | "*" ) unary
| ( "ref" | "mut" ) [ "unchecked" ] place | ( "ref" | "mut" ) [ "unchecked" ] place
| "move" ident | "move" ident
| postfix ; | postfix ;
postfix = primary { "." ident | "[" expr [ ".." expr ] "]" | call_args } ; postfix = primary { "." member | "[" expr [ ".." expr ] "]" | call_args } ;
member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *)
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ; call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ;
primary = int_lit | "true" | "false" | string primary = int_lit | "true" | "false" | string
| ident [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *) | ident [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *)
@@ -97,3 +98,4 @@ place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ; int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ;
string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *) string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *)
ident = ( letter | "_" ) { letter | digit | "_" } ; ident = ( letter | "_" ) { letter | digit | "_" } ;
keyword = ? any keyword listed under Lexical conventions ? ;
+7 -5
View File
@@ -106,6 +106,8 @@ Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`
`if` and `match` are expressions when every branch yields a value of the same type through a tail expression (an expression without `;` at the end of a block) or diverges (`return`, `break`, `continue`, `trap`). `if` and `match` are expressions when every branch yields a value of the same type through a tail expression (an expression without `;` at the end of a block) or diverges (`return`, `break`, `continue`, `trap`).
**Joins carry live variables only.** A variable is passed to a join (the block after an `if` or `match`, a loop header, a loop exit) only if it may be read after that join: on a later path, or, for a loop header, anywhere in the loop. A variable that is not read again is not passed on. This is ordinary pruned SSA construction, not tracking of moves. A linear value consumed before a join (`channel.close_receiver(move r)` before `break`) does not travel to it. A linear value that is read after it was consumed is still the verifier's `E2001`. The analysis is conservative: any read on a later path counts, and only a whole-variable assignment in straight-line code ends a variable's life.
**Type inference is deliberately small.** It works within one function, it is monomorphic, and it does no overload resolution or search among several admissible types. An expression's type comes from: **Type inference is deliberately small.** It works within one function, it is monomorphic, and it does no overload resolution or search among several admissible types. An expression's type comes from:
- its own form: a literal suffix, a name, a call's declared return type, a cast, a struct or enum constructor; - its own form: a literal suffix, a name, a call's declared return type, a cast, a struct or enum constructor;
@@ -227,7 +229,7 @@ match io.stdin_read(input, mut buf) {
- **Match kinds.** The parser decides the kind of a `match` from its arms: `Enum::Variant` arms make an enum match, integer literals and `_` an integer match, and bare outcome names (`ok`, `err`, `closed`, `cancelled`, `pending`) an outcome match. Outcome names are not enum patterns. In an outcome match the scrutinee MUST be a fallible operation (`E7006` otherwise). Each outcome is matched exactly once: a repeated one is `E7006`, an unknown one `E7002`, a wrong number of bound names `E7005`. A fallible operation outside an outcome match or `or trap` is `E7006`. - **Match kinds.** The parser decides the kind of a `match` from its arms: `Enum::Variant` arms make an enum match, integer literals and `_` an integer match, and bare outcome names (`ok`, `err`, `closed`, `cancelled`, `pending`) an outcome match. Outcome names are not enum patterns. In an outcome match the scrutinee MUST be a fallible operation (`E7006` otherwise). Each outcome is matched exactly once: a repeated one is `E7006`, an unknown one `E7002`, a wrong number of bound names `E7005`. A fallible operation outside an outcome match or `or trap` is `E7006`.
- **Outcome values.** `err(e)` binds the real error value (`alloc_error`, `cap_error`, `io_error`). These built-in enums are matched like declared ones: `alloc_error::out_of_memory`, exhaustive, no `_`. A borrow bound by an outcome (the `ok(item)` of `region.new`) ends at the end of its arm. A borrow bound by `let item = region.new(arena, v) or trap;` ends at the end of the enclosing block. - **Outcome values.** `err(e)` binds the real error value (`alloc_error`, `cap_error`, `io_error`). These built-in enums are matched like declared ones: `alloc_error::out_of_memory`, exhaustive, no `_`. A borrow bound by an outcome (the `ok(item)` of `region.new`) ends at the end of its arm. A borrow bound by `let item = region.new(arena, v) or trap;` ends at the end of the enclosing block.
- **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`. - **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`. If that name is a variable (`var`) of the value's type, the value becomes the variable's new value. A receiver kept in `var r` is closed with `match channel.close_receiver(move r) { ok => …, pending(r) => … }` and received from again.
- **`or trap`.** `op(args) or trap` is the expression of the `ok` value, or of `void`. Every other outcome traps (`T0001`). It is the only shorthand. - **`or trap`.** `op(args) or trap` is the expression of the `ok` value, or of `void`. Every other outcome traps (`T0001`). It is the only shorthand.
- **Enums.** A `match` over a value of an enum type has exactly one arm per variant, each written `Enum::Variant(names…)` (`Enum::Variant` without payload). It must be exhaustive (`E7004` lists the missing variants), and `_` is not allowed (`E7006`), so a new variant cannot slip through silently. Payload names are bound only inside their arm (they are the arm block's parameters in AIR). It lowers to `enum.switch`. - **Enums.** A `match` over a value of an enum type has exactly one arm per variant, each written `Enum::Variant(names…)` (`Enum::Variant` without payload). It must be exhaustive (`E7004` lists the missing variants), and `_` is not allowed (`E7006`), so a new variant cannot slip through silently. Payload names are bound only inside their arm (they are the arm block's parameters in AIR). It lowers to `enum.switch`.
- **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). It lowers to `switch`. - **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). It lowers to `switch`.
@@ -246,8 +248,8 @@ scope s {
**`scope s { … }`** is `task.scope.begin` and `task.scope.end`, at every normal exit of the block. Inside it: **`scope s { … }`** is `task.scope.begin` and `task.scope.end`, at every normal exit of the block. Inside it:
- `task.spawn(s, f, args)` spawns; borrow arguments are lent until the join (spec 04 §34); - `task.spawn(s, f, args)` spawns `f` (a function of the module) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`);
- `task.join(move t)` joins; - `task.join(move t)` joins; its value is the task's result (`task<T>` gives `T`);
- a task that is not joined at an exit is `E4301`. - a task that is not joined at an exit is `E4301`.
**Task operations elsewhere:** **Task operations elsewhere:**
@@ -261,9 +263,9 @@ scope s {
**Channels:** **Channels:**
- `channel.make<T>(n, mem)`: a match, §6; - `channel.make<T>(n, mem)`: a match, §6;
- `channel.dup(tx)`; - `channel.dup(tx)`: `channel.sender.dup` on a shared borrow of `tx`, made for the operation;
- `channel.send(tx, v)` (`move v` for a linear `v`); - `channel.send(tx, v)` (`move v` for a linear `v`);
- `channel.recv(rx)`; - `channel.recv(rx)`; for `send` and `recv` the endpoint is borrowed `mut` for the operation and the borrow ends on every edge;
- `channel.close_sender(move tx)`; - `channel.close_sender(move tx)`;
- `channel.close_receiver(move rx)`. - `channel.close_receiver(move rx)`.
+483 -29
View File
@@ -19,7 +19,8 @@
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`, //! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
//! outcome matches and `or trap`; //! outcome matches and `or trap`;
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability //! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations. //! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels.
const std = @import("std"); const std = @import("std");
const ast = @import("ast.zig"); const ast = @import("ast.zig");
@@ -52,12 +53,21 @@ pub const Ty = union(enum) {
builtin: authority.Builtin, builtin: authority.Builtin,
/// `file<read|write|append>`, `stream`, `listener`. /// `file<read|write|append>`, `stream`, `listener`.
resource: authority.Resource, resource: authority.Resource,
/// `task<T>`, `sender<T>`, `receiver<T>`: the element or result type.
task: *const Ty,
sender: *const Ty,
receiver: *const Ty,
/// A task scope (bound by `scope s { … }`, never written as a type).
scope,
pub const Arr = struct { elem: Ty, len: u64 }; pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5). /// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool { fn isLinear(t: Ty) bool {
return t == .own or t == .own_array or t == .region or t == .resource; return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope => true,
else => false,
};
} }
fn eql(a: Ty, b: Ty) bool { fn eql(a: Ty, b: Ty) bool {
@@ -66,7 +76,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int), .int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named, .named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem), .array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(inner(b).?), .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap), .cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin, .builtin => |e| e == b.builtin,
.resource => |r| r == b.resource, .resource => |r| r == b.resource,
@@ -76,7 +86,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty { fn inner(t: Ty) ?Ty {
return switch (t) { return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.*,
.array => |a| a.elem, .array => |a| a.elem,
else => null, else => null,
}; };
@@ -180,7 +190,9 @@ const Binding = struct {
}; };
/// A borrow to end with `borrow.end` when its scope ends (spec 15 §9). /// A borrow to end with `borrow.end` when its scope ends (spec 15 §9).
const BorrowEnd = struct { name: []const u8, span: Span }; /// Something ended at every normal exit of a lexical scope, innermost
/// first: a borrow (`borrow.end`) or a task scope (`task.scope.end`).
const BorrowEnd = struct { name: []const u8, span: Span, op: []const u8 = "borrow.end" };
/// A bounds fact the verifier can prove (spec 08 §12, "fact on the same /// A bounds fact the verifier can prove (spec 08 §12, "fact on the same
/// slice"): inside the true branch of `if i < s.len`, with `i` and `s` /// slice"): inside the true branch of `if i < s.len`, with `i` and `s`
@@ -201,6 +213,10 @@ const Loop = struct {
/// Number of borrow scopes open when the loop started: `break` and /// Number of borrow scopes open when the loop started: `break` and
/// `continue` end the borrows of every scope above it. /// `continue` end the borrows of every scope above it.
scope_depth: usize, scope_depth: usize,
/// Variables carried to the loop's header (and `continue` target) and
/// to its exit.
header_vars: []const usize = &.{},
exit_vars: []const usize = &.{},
}; };
const FnOut = struct { const FnOut = struct {
@@ -212,7 +228,19 @@ const FnOut = struct {
const Value = struct { name: []const u8, ty: Ty }; const Value = struct { name: []const u8, ty: Ty };
const Rest = struct { stmts: []const ast.Stmt, tail: ?*const ast.Expr }; /// What remains to be lowered in an enclosing block: the statements after
/// the current one, the tail, the current statement itself, and, for a loop
/// body, the loop (whose next iteration also follows).
const Rest = struct {
stmts: []const ast.Stmt,
tail: ?*const ast.Expr,
current: ?ast.Stmt = null,
/// The tail expression, while it is being lowered.
current_expr: ?*const ast.Expr = null,
loop: ?LoopAst = null,
};
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
const FnSig = struct { params: []const Ty, ret: Ty }; const FnSig = struct { params: []const Ty, ret: Ty };
@@ -248,6 +276,11 @@ const Lowerer = struct {
/// Statements still to be lowered in each enclosing block (innermost /// Statements still to be lowered in each enclosing block (innermost
/// last), for inferring the type of an untyped `let` from its uses. /// last), for inferring the type of an untyped `let` from its uses.
rest: std.ArrayList(Rest) = .empty, 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,
/// Borrows to end at the end of each open lexical scope (innermost last). /// Borrows to end at the end of each open lexical scope (innermost last).
scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty, scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty,
/// `local.alloc` instructions; they go first in the entry block. /// `local.alloc` instructions; they go first in the entry block.
@@ -278,7 +311,8 @@ const Lowerer = struct {
.never => "never", .never => "never",
.named => |i| l.typeNames[i], .named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array", .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 => |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 => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.scope => "scope",
.region => "region", .region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap", .cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| blk: { .builtin => |b| blk: {
@@ -392,6 +426,8 @@ const Lowerer = struct {
.{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } }, .{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } },
.{ "regions", &.{"region"} }, .{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } }, .{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
.{ "tasks", &.{ "task.", "task<", ": scope" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<" } },
}; };
for (rules) |r| { for (rules) |r| {
const used = for (texts.items) |t| { const used = for (texts.items) |t| {
@@ -462,7 +498,7 @@ const Lowerer = struct {
}, },
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len), .array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| { .wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array }; const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)"); 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.*); const in = try l.typeOf(w.inner.*);
return switch (which) { return switch (which) {
@@ -472,6 +508,9 @@ const Lowerer = struct {
.slice_mut => l.wrap(.slice_mut, in), .slice_mut => l.wrap(.slice_mut, in),
.own => l.wrap(.own, in), .own => l.wrap(.own, in),
.own_array => l.wrap(.own_array, in), .own_array => l.wrap(.own_array, in),
.task => l.wrap(.task, in),
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
}; };
}, },
.cap => |k| { .cap => |k| {
@@ -625,6 +664,50 @@ const Lowerer = struct {
return out.items; return out.items;
} }
/// The variables a join after the construct at `construct` carries: those
/// that may be read after it (pruned SSA, spec 15 §4). A variable that is
/// not read again is not passed on, so a linear value consumed before the
/// join does not travel to it.
fn carriedLive(l: *Lowerer, depth: usize, construct: Span) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (try l.carried(depth)) |i| if (l.liveAfter(l.bindings.items[i].name, construct)) try out.append(l.arena, i);
return out.items;
}
/// As `carriedLive`, for a loop header: also the variables the loop
/// itself reads (they flow around the back edge).
fn carriedLoop(l: *Lowerer, depth: usize, construct: Span, lp: LoopAst) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (loopReads(lp, n) or l.liveAfter(n, construct)) try out.append(l.arena, i);
}
return out.items;
}
/// Whether `name` may be read after the construct whose span is
/// `construct`. Conservative: any read on any later path counts; only a
/// whole-variable assignment in straight-line code before any read ends
/// the variable's life.
fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) bool {
var k = l.rest.items.len;
while (k > 0) {
k -= 1;
const fr = l.rest.items[k];
// The rest of the statement or tail that contains the construct.
var w: After = .{ .name = name, .construct = construct };
if (fr.current) |c| if (w.stmt(c)) return true;
if (fr.current_expr) |ce| if (w.expr(ce.*)) return true;
switch (firstUse(fr.stmts, fr.tail, name)) {
.read => return true,
.kill => return false,
.none => {},
}
if (fr.loop) |lp| if (loopReads(lp, name)) return true;
}
return false;
}
fn argsOf(l: *Lowerer, vars: []const usize, extra: ?[]const u8) Error![]const u8 { fn argsOf(l: *Lowerer, vars: []const usize, extra: ?[]const u8) Error![]const u8 {
var s: std.ArrayList(u8) = .empty; var s: std.ArrayList(u8) = .empty;
try s.append(l.arena, '('); try s.append(l.arena, '(');
@@ -677,21 +760,32 @@ const Lowerer = struct {
fn blockBodyWant(l: *Lowerer, b: ast.Block, want: ?Ty) Error!?Value { fn blockBodyWant(l: *Lowerer, b: ast.Block, want: ?Ty) Error!?Value {
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
defer l.bindings.shrinkRetainingCapacity(depth); defer l.bindings.shrinkRetainingCapacity(depth);
try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail }); try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail, .loop = l.pending_loop });
l.pending_loop = null;
defer _ = l.rest.pop(); defer _ = l.rest.pop();
try l.scopes.append(l.arena, .empty); try l.scopes.append(l.arena, .empty);
defer _ = l.scopes.pop(); defer _ = l.scopes.pop();
const saved_start = l.scope_binding_start; const saved_start = l.scope_binding_start;
l.scope_binding_start = depth; l.scope_binding_start = depth;
defer l.scope_binding_start = saved_start; 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);
}
for (b.stmts, 0..) |s, i| { for (b.stmts, 0..) |s, i| {
if (l.cur == null) return l.fail("E7006", s.span, "unreachable statement", &.{}); if (l.cur == null) return l.fail("E7006", s.span, "unreachable statement", &.{});
l.rest.items[l.rest.items.len - 1].stmts = b.stmts[i + 1 ..]; l.rest.items[l.rest.items.len - 1].stmts = b.stmts[i + 1 ..];
l.rest.items[l.rest.items.len - 1].current = s;
try l.stmt(s); try l.stmt(s);
} }
var result: ?Value = null; var result: ?Value = null;
if (b.tail) |t| { if (b.tail) |t| {
if (l.cur == null) return l.fail("E7006", t.span, "unreachable expression", &.{}); if (l.cur == null) return l.fail("E7006", t.span, "unreachable expression", &.{});
l.rest.items[l.rest.items.len - 1].stmts = &.{};
l.rest.items[l.rest.items.len - 1].current = null;
l.rest.items[l.rest.items.len - 1].tail = null;
l.rest.items[l.rest.items.len - 1].current_expr = t;
result = try l.expr(t.*, want); result = try l.expr(t.*, want);
if (result.?.ty.isBorrow()) return l.fail("E7006", t.span, "a block cannot yield a borrow", &.{}); if (result.?.ty.isBorrow()) return l.fail("E7006", t.span, "a block cannot yield a borrow", &.{});
} }
@@ -710,7 +804,7 @@ const Lowerer = struct {
var k = ends.len; var k = ends.len;
while (k > 0) { while (k > 0) {
k -= 1; k -= 1;
try l.emit(try l.fmt("borrow.end %{s}", .{ends[k].name}), if (i == l.scopes.items.len - 1 and from == i) ends[k].span else span); try l.emit(try l.fmt("{s} %{s}", .{ ends[k].op, ends[k].name }), if (i == l.scopes.items.len - 1 and from == i) ends[k].span else span);
} }
} }
} }
@@ -833,7 +927,7 @@ const Lowerer = struct {
.@"break", .@"continue" => { .@"break", .@"continue" => {
if (l.loops.items.len == 0) return l.fail("E7006", s.span, "`break` or `continue` outside a loop", &.{}); if (l.loops.items.len == 0) return l.fail("E7006", s.span, "`break` or `continue` outside a loop", &.{});
const lp = l.loops.items[l.loops.items.len - 1]; const lp = l.loops.items[l.loops.items.len - 1];
const vars = try l.carried(lp.depth); const vars = if (s.kind == .@"break") lp.exit_vars else lp.header_vars;
const target = if (s.kind == .@"break") lp.exit else lp.@"continue"; const target = if (s.kind == .@"break") lp.exit else lp.@"continue";
try l.endScopes(lp.scope_depth, s.span); try l.endScopes(lp.scope_depth, s.span);
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span); try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span);
@@ -845,7 +939,13 @@ const Lowerer = struct {
.@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null), .@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null),
.loop => |b| try l.whileLoop(s.span, null, b, null), .loop => |b| try l.whileLoop(s.span, null, b, null),
.@"for" => |x| try l.forLoop(s.span, x.name, x.lo, x.hi, x.body), .@"for" => |x| try l.forLoop(s.span, x.name, x.lo, x.hi, x.body),
.scope => return l.notYet(s.span, "`scope` (layer 7)"), .scope => |x| {
// `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.blockBody(x.body);
},
.shield => return l.notYet(s.span, "`shield` (layer 8)"), .shield => return l.notYet(s.span, "`shield` (layer 8)"),
.lock => return l.notYet(s.span, "`lock` (layer 8)"), .lock => return l.notYet(s.span, "`lock` (layer 8)"),
.select => return l.notYet(s.span, "`select` (layer 8)"), .select => return l.notYet(s.span, "`select` (layer 8)"),
@@ -865,12 +965,14 @@ const Lowerer = struct {
/// every variable visible at the loop. /// every variable visible at the loop.
fn whileLoop(l: *Lowerer, span: Span, cond: ?ast.Expr, body: ast.Block, step: ?ForStep) Error!void { fn whileLoop(l: *Lowerer, span: Span, cond: ?ast.Expr, body: ast.Block, step: ?ForStep) Error!void {
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
const vars = try l.carried(depth); const lp_ast: LoopAst = .{ .cond = cond, .body = body, .step = if (step) |st| st.name else null };
const vars = try l.carriedLoop(depth, span, lp_ast);
const exit_vars = try l.carriedLive(depth, span);
const header = try l.newBlock(if (cond == null) "loop" else "while"); const header = try l.newBlock(if (cond == null) "loop" else "while");
const exit = try l.newBlock("after"); const exit = try l.newBlock("after");
const cont = if (step != null) try l.newBlock("step") else header; const cont = if (step != null) try l.newBlock("step") else header;
try l.joinParams(header, vars); try l.joinParams(header, vars);
try l.joinParams(exit, vars); try l.joinParams(exit, exit_vars);
if (step != null) try l.joinParams(cont, vars); if (step != null) try l.joinParams(cont, vars);
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span); try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span);
@@ -880,10 +982,11 @@ const Lowerer = struct {
const cv = try l.expr(c, .bool); const cv = try l.expr(c, .bool);
try l.checkTy(c.span, cv.ty, .bool); try l.checkTy(c.span, cv.ty, .bool);
const body_b = try l.newBlock("body"); const body_b = try l.newBlock("body");
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(vars, null) }), c.span); try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(exit_vars, null) }), c.span);
l.cur = body_b; l.cur = body_b;
} }
try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth, .scope_depth = l.scopes.items.len }); try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth, .scope_depth = l.scopes.items.len, .header_vars = vars, .exit_vars = exit_vars });
l.pending_loop = lp_ast;
_ = try l.blockBody(body); _ = try l.blockBody(body);
_ = l.loops.pop(); _ = l.loops.pop();
if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span); if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span);
@@ -897,7 +1000,7 @@ const Lowerer = struct {
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span); try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span);
} }
l.cur = exit; l.cur = exit;
l.rebindToParams(exit, vars, 0); l.rebindToParams(exit, exit_vars, 0);
// A `loop` without `break` never reaches its exit. // A `loop` without `break` never reaches its exit.
if (!l.reaches(exit)) l.cur = null; if (!l.reaches(exit)) l.cur = null;
} }
@@ -959,7 +1062,7 @@ const Lowerer = struct {
.call => |x| switch (x.callee.kind) { .call => |x| switch (x.callee.kind) {
.name => |n| if (l.sigs.get(n)) |sig| sig.ret else null, .name => |n| if (l.sigs.get(n)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum"), .variant => |v| l.enumType(v.@"enum"),
else => if (pathOf(x.callee.*)) |p| (if (std.mem.eql(u8, p, "own.take") and x.args.len == 1) (if (l.peekType(x.args[0])) |t| t.inner() else null) else null) else null, else => if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
}, },
.move => |n| if (l.lookup(n)) |b| b.ty else null, .move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum"), .variant => |v| l.enumType(v.@"enum"),
@@ -1257,6 +1360,7 @@ const Lowerer = struct {
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
return .{ .name = "", .ty = .void }; return .{ .name = "", .ty = .void };
} }
if (try l.concurrencyCall(e, p, args)) |v| return v;
if (authority.intrinsicIndex(p)) |ix| { if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix]; const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty; var temps: std.ArrayList([]const u8) = .empty;
@@ -1427,7 +1531,7 @@ const Lowerer = struct {
if (st == .builtin) return l.builtinMatch(m, st.builtin, want); if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.expr(m.scrutinee, st); const sv = try l.expr(m.scrutinee, st);
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
const vars = try l.carried(depth); const vars = try l.carriedLive(depth, m.span);
const before = try l.snapshot(); const before = try l.snapshot();
var ends: std.ArrayList(ArmEnd) = .empty; var ends: std.ArrayList(ArmEnd) = .empty;
@@ -1521,7 +1625,7 @@ const Lowerer = struct {
const name = @tagName(b); const name = @tagName(b);
const sv = try l.expr(m.scrutinee, .{ .builtin = b }); const sv = try l.expr(m.scrutinee, .{ .builtin = b });
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
const vars = try l.carried(depth); const vars = try l.carriedLive(depth, m.span);
const before = try l.snapshot(); const before = try l.snapshot();
const blocks = try l.arena.alloc(usize, m.arms.len); const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty; var head: std.ArrayList(u8) = .empty;
@@ -1555,6 +1659,20 @@ const Lowerer = struct {
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch"); return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
} }
/// The result type of a built-in operation called plainly, if known
/// without lowering it.
fn peekPath(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty {
const eq = std.mem.eql;
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2 and args[1].kind == .name) {
const sig = l.sigs.get(args[1].kind.name) orelse return null;
return l.wrap(.task, sig.ret) catch null;
}
return null;
}
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value { fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
const v = try l.expr(body, want); const v = try l.expr(body, want);
if (v.ty == .void) return null; if (v.ty == .void) return null;
@@ -1962,12 +2080,105 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void { fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l; _ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix" }; 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" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {}; for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {}; if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null; return null;
} }
// ------------------------------------------------------------ tasks and channels (layer 7)
fn bindingOf(l: *Lowerer, a: ast.Expr, what: []const u8) Error!*Binding {
if (a.kind != .name) return l.fail("E7005", a.span, try l.fmt("{s} is expected here, by name", .{what}), &.{});
return l.lookup(a.kind.name) orelse l.unknown(a.span, a.kind.name);
}
/// An endpoint operand the operation borrows (`mut` or `ref`): the
/// endpoint by name, borrowed for the operation, or a borrow binding of it.
fn endpointOperand(l: *Lowerer, a: ast.Expr, tag: std.meta.Tag(Ty), mutable: bool, temps: *std.ArrayList([]const u8)) Error!Value {
const what = if (tag == .sender) "a sender" else "a receiver";
if (a.kind == .borrow) return l.fail("E7006", a.span, "an endpoint operand is written by name; the operation borrows it", &.{});
const b = try l.bindingOf(a, what);
if (std.meta.activeTag(b.ty) == tag) {
const bt = if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty);
const v = try l.def(a.kind.name, bt, try l.fmt("{s} %{s}", .{ if (mutable) "borrow.mut" else "borrow.ref", b.value }), a.span);
try temps.append(l.arena, v.name);
return v;
}
if ((b.ty == .mut or (b.ty == .ref and !mutable)) and std.meta.activeTag(b.ty.inner().?) == tag) return .{ .name = b.value, .ty = b.ty };
return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = l.tyText(b.ty) }});
}
/// The task and channel operations that are plain calls; null for any
/// other path.
fn concurrencyCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!?Value {
const eq = struct {
fn f(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
}.f;
if (eq(p, "task.spawn")) {
if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{});
const sb = try l.bindingOf(args[0], "a task scope");
if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.tyText(sb.ty) }});
const scope_name = sb.value;
if (args[1].kind != .name) return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
const fname = args[1].kind.name;
const sig = l.sigs.get(fname) orelse return l.unknown(args[1].span, fname);
const fargs = args[2..];
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = fname }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
var names: std.ArrayList(u8) = .empty;
for (fargs, sig.params, 0..) |a, pt, i| {
// A borrow is lent to the task until its join, so it is bound
// by the program, not made for the call (spec 15 §7).
if (a.kind == .borrow or a.kind == .bytes) return l.fail("E7006", a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{});
const v = try l.consuming(a, pt);
try l.checkTy(a.span, v.ty, pt);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, fname, names.items }), e.span);
}
if (eq(p, "task.join")) {
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
const t = try l.consuming(args[0], null);
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = l.tyText(t.ty) }});
const rt = t.ty.task.*;
if (rt == .void) {
try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span);
return .{ .name = "", .ty = .void };
}
return try l.def("r", rt, try l.fmt("task.join %{s}", .{t.name}), e.span);
}
if (eq(p, "task.cancel")) {
if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{});
const b = try l.bindingOf(args[0], "a task");
if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task<T>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
try l.emit(try l.fmt("task.cancel %{s}", .{b.value}), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(p, "task.cancelled")) {
if (args.len != 0) return l.fail("E7005", e.span, "`task.cancelled()` takes no operands", &.{});
return try l.def("c", .bool, "task.cancelled", e.span);
}
if (eq(p, "channel.dup")) {
if (args.len != 1) return l.fail("E7005", e.span, "`channel.dup` takes one sender", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const tx = try l.endpointOperand(args[0], .sender, false, &temps);
const st = tx.ty.inner().?;
const v = try l.def("tx", st, try l.fmt("channel.sender.dup %{s}", .{tx.name}), e.span);
try l.endNow(temps.items, e.span);
return v;
}
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);
if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender<T>`", &.{.{ .name = "found", .value = l.tyText(tx.ty) }});
try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span);
return .{ .name = "", .ty = .void };
}
return null;
}
fn resultTy(r: authority.ResultType) Ty { fn resultTy(r: authority.ResultType) Ty {
return switch (r) { return switch (r) {
.usize => .{ .int = "usize" }, .usize => .{ .int = "usize" },
@@ -2051,7 +2262,7 @@ const Lowerer = struct {
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible { 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 (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 (layers 7–8)"); 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 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 args = e.kind.call.args;
const want = struct { const want = struct {
@@ -2108,6 +2319,37 @@ const Lowerer = struct {
.temps = temps.items, .temps = temps.items,
}; };
} }
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)`", &.{});
const et = try l.memberType(ta);
const n = try l.expr(args[0], usize_ty);
try l.checkTy(args[0].span, n.ty, usize_ty);
const c = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("channel.make {s}, %{s}, %{s}", .{ l.tyText(et), n.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ try l.wrap(.sender, et), try l.wrap(.receiver, et) } }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "channel.send")) {
try want(l, e.span, args, 2, path);
var temps: std.ArrayList([]const u8) = .empty;
const tx = try l.endpointOperand(args[0], .sender, true, &temps);
const et = tx.ty.inner().?.sender.*;
const v = try l.consuming(args[1], et);
try l.checkTy(args[1].span, v.ty, et);
return .{ .text = try l.fmt("channel.send %{s}, %{s}", .{ tx.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "closed", .params = &.{et} }, .{ .role = "cancelled", .params = &.{et} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "channel.recv")) {
try want(l, e.span, args, 1, path);
var temps: std.ArrayList([]const u8) = .empty;
const rx = try l.endpointOperand(args[0], .receiver, true, &temps);
const et = rx.ty.inner().?.receiver.*;
return .{ .text = try l.fmt("channel.recv %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{et} }, .{ .role = "closed", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "channel.close_receiver")) {
try want(l, e.span, args, 1, path);
const rx = try l.consuming(args[0], null);
if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver<T>`", &.{.{ .name = "found", .value = l.tyText(rx.ty) }});
return .{ .text = try l.fmt("channel.close_receiver %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "pending", .params = &.{rx.ty} } }) };
}
if (std.mem.eql(u8, path, "cap.narrow.prefix")) { if (std.mem.eql(u8, path, "cap.narrow.prefix")) {
try want(l, e.span, args, 2, path); try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null); const c = try l.expr(args[0], null);
@@ -2179,7 +2421,7 @@ const Lowerer = struct {
if (missing.items.len != 0) return l.fail("E7004", m.span, "the match does not handle every outcome of the operation", &.{.{ .name = "missing", .value = missing.items }}); if (missing.items.len != 0) return l.fail("E7004", m.span, "the match does not handle every outcome of the operation", &.{.{ .name = "missing", .value = missing.items }});
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
const vars = try l.carried(depth); const vars = try l.carriedLive(depth, m.span);
const before = try l.snapshot(); const before = try l.snapshot();
const blocks = try l.outcomeBlocks(f, m.scrutinee.span); const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
var ends: std.ArrayList(ArmEnd) = .empty; var ends: std.ArrayList(ArmEnd) = .empty;
@@ -2195,6 +2437,13 @@ const Lowerer = struct {
for (arm.pattern.kind.ctor.binds, l.blocks.items[blk].params.items) |bn, prm| { for (arm.pattern.kind.ctor.binds, l.blocks.items[blk].params.items) |bn, prm| {
if (prm.ty.isBorrow()) try l.scopeEnds(&.{prm.name}, arm.pattern.span); if (prm.ty.isBorrow()) try l.scopeEnds(&.{prm.name}, arm.pattern.span);
if (std.mem.eql(u8, bn, "_")) continue; if (std.mem.eql(u8, bn, "_")) continue;
// Rebinding (spec 15 §6): a value that comes back on an edge
// under the name of a variable of its type is that variable's
// new value (`pending(rx)`, `closed(v)`).
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, .kind = if (prm.ty.isBorrow()) .borrow else .ssa }); try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty, .kind = if (prm.ty.isBorrow()) .borrow else .ssa });
} }
const v = try l.armBody(arm.body, want); const v = try l.armBody(arm.body, want);
@@ -2245,7 +2494,7 @@ const Lowerer = struct {
}; };
try l.checkTy(x.cond.span, cv.ty, .bool); try l.checkTy(x.cond.span, cv.ty, .bool);
const depth = l.bindings.items.len; const depth = l.bindings.items.len;
const vars = try l.carried(depth); const vars = try l.carriedLive(depth, span);
const then_b = try l.newBlock("then"); const then_b = try l.newBlock("then");
const else_b = try l.newBlock("else"); const else_b = try l.newBlock("else");
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span); try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span);
@@ -2286,11 +2535,11 @@ fn elemOf(t: Ty) ?Ty {
}; };
} }
/// `task.*`, `channel.*`, `mutex.*`: operations of layers 7–8. /// `task.check_cancel`, `task.join_cancel`, `mutex.*`: operations of layer 8.
fn laterLayer(e: ast.Expr) bool { fn laterLayer(e: ast.Expr) bool {
var buf: [64]u8 = undefined; var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return false; const text = dotted(e, &buf) orelse return false;
for ([_][]const u8{ "task.", "channel.", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true; for ([_][]const u8{ "task.check_cancel", "task.join_cancel", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true;
return false; return false;
} }
@@ -2298,9 +2547,11 @@ fn laterLayer(e: ast.Expr) bool {
/// `cap.narrow.budget`; null for anything else. /// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 { fn pathOf(e: ast.Expr) ?[]const u8 {
const known = [_][]const u8{ const known = [_][]const u8{
"slice.copy", "own.new", "own.array", "own.take", "own.free", "slice.copy", "own.new", "own.array", "own.take", "own.free",
"region.create", "region.new", "region.array", "region.reset", "region.destroy", "region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget", "cap.narrow.prefix", "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",
}; };
var buf: [64]u8 = undefined; var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null; const text = dotted(e, &buf) orelse return null;
@@ -2333,3 +2584,206 @@ fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
b.* = e; b.* = e;
return b; return b;
} }
// ---------------------------------------------------------------- liveness (pruned joins)
fn spanEq(a: Span, b: Span) bool {
return a.start.line == b.start.line and a.start.col == b.start.col and a.end.line == b.end.line and a.end.col == b.end.col;
}
const Use = enum { read, kill, none };
/// The first use of `name` in statements executed in order: a read, a
/// whole-variable assignment that does not read it (`name = e;`), or none.
fn firstUse(stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) Use {
for (stmts) |st| {
if (st.kind == .assign and st.kind.assign.place.kind == .name and std.mem.eql(u8, st.kind.assign.place.kind.name, name)) {
if (exprReads(st.kind.assign.e, name, null)) return .read;
return .kill;
}
if (stmtReads(st, name, null)) return .read;
}
if (tail) |t| if (exprReads(t.*, name, null)) return .read;
return .none;
}
fn loopReads(lp: LoopAst, name: []const u8) bool {
if (lp.step) |st| if (std.mem.eql(u8, st, name)) return true;
if (lp.cond) |c| if (exprReads(c, name, null)) return true;
return blockReads(lp.body, name, null);
}
fn blockReads(b: ast.Block, name: []const u8, skip: ?Span) bool {
for (b.stmts) |st| if (stmtReads(st, name, skip)) return true;
if (b.tail) |t| if (exprReads(t.*, name, skip)) return true;
return false;
}
/// Whether the statement mentions `name` other than as the target of a
/// whole-variable assignment. `skip`: a construct whose own reads happen
/// before the join being decided.
fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool {
return switch (st.kind) {
.let => |x| exprReads(x.e, name, skip),
.@"var" => |x| if (x.init) |e| exprReads(e, name, skip) else false,
.assign => |x| exprReads(x.e, name, skip) or (x.place.kind != .name and exprReads(x.place, name, skip)),
.borrow => |x| exprReads(x.place, name, skip),
.@"return" => |e| if (e) |x| exprReads(x, name, skip) else false,
.expr => |e| exprReads(e, name, skip),
.@"while" => |x| exprReads(x.cond, name, skip) or blockReads(x.body, name, skip),
.@"for" => |x| exprReads(x.lo, name, skip) or exprReads(x.hi, name, skip) or blockReads(x.body, name, skip),
.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,
.@"break", .@"continue", .trap => false,
};
}
fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
if (skip) |sk| if (spanEq(e.span, sk)) return false;
return switch (e.kind) {
.name => |n| std.mem.eql(u8, n, name),
.move => |n| std.mem.eql(u8, n, name),
.int, .boolean, .bytes, .variant => false,
.neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip),
.borrow => |x| exprReads(x.place.*, name, skip),
.binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip),
.cast => |x| exprReads(x.e.*, name, skip),
.call => |x| blk: {
if (exprReads(x.callee.*, name, skip)) break :blk true;
for (x.args) |a| if (exprReads(a, name, skip)) break :blk true;
break :blk false;
},
.field => |x| exprReads(x.e.*, name, skip),
.index => |x| exprReads(x.e.*, name, skip) or exprReads(x.lo.*, name, skip) or (if (x.hi) |h| exprReads(h.*, name, skip) else false),
.struct_lit => |x| blk: {
for (x.fields) |f| if (exprReads(f.e, name, skip)) break :blk true;
break :blk false;
},
.array_rep => |x| exprReads(x.e.*, name, skip),
.if_expr => |x| ifReads(x.*, name, skip),
.match_expr => |x| blk: {
if (exprReads(x.scrutinee, name, skip)) break :blk true;
for (x.arms) |a| if (exprReads(a.body, name, skip)) break :blk true;
break :blk false;
},
.block => |b| blockReads(b.*, 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) {
.block => |b| blockReads(b, name, skip),
.@"if" => |inner| ifReads(inner.*, name, skip),
};
return false;
}
/// Reads of `name` after `construct`, in evaluation order, within the
/// statement or expression that contains it. Once the construct is found in
/// one arm of an `if` or `match`, the other arms are not "after" it; once it
/// is found in a loop, the whole loop is (the back edge).
const After = struct {
name: []const u8,
construct: Span,
seen: bool = false,
fn expr(w: *After, e: ast.Expr) bool {
if (!w.seen and spanEq(e.span, w.construct)) {
w.seen = true;
return false;
}
return switch (e.kind) {
.name, .move => |n| w.seen and std.mem.eql(u8, n, w.name),
.int, .boolean, .bytes, .variant => false,
.neg, .not, .deref, .or_trap => |x| w.expr(x.*),
.borrow => |x| w.expr(x.place.*),
.binary => |x| w.expr(x.l.*) or w.expr(x.r.*),
.cast => |x| w.expr(x.e.*),
.call => |x| blk: {
if (w.expr(x.callee.*)) break :blk true;
for (x.args) |a| if (w.expr(a)) break :blk true;
break :blk false;
},
.field => |x| w.expr(x.e.*),
.index => |x| w.expr(x.e.*) or w.expr(x.lo.*) or (if (x.hi) |h| w.expr(h.*) else false),
.struct_lit => |x| blk: {
for (x.fields) |f| if (w.expr(f.e)) break :blk true;
break :blk false;
},
.array_rep => |x| w.expr(x.e.*),
.if_expr => |x| w.ifExpr(x.*),
.match_expr => |x| blk: {
if (w.expr(x.scrutinee)) break :blk true;
if (w.seen) {
for (x.arms) |a| if (w.expr(a.body)) break :blk true;
break :blk false;
}
for (x.arms) |a| {
const r = w.expr(a.body);
if (w.seen) break :blk r; // found in this arm: siblings are not after it
}
break :blk false;
},
.block => |b| w.block(b.*),
};
}
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);
const r = w.block(x.then);
if (w.seen) return r;
if (x.@"else") |els| return w.elseBranch(els);
return false;
}
fn elseBranch(w: *After, els: ast.Else) bool {
return switch (els) {
.block => |b| w.block(b),
.@"if" => |inner| w.ifExpr(inner.*),
};
}
fn block(w: *After, b: ast.Block) bool {
for (b.stmts) |st| if (w.stmt(st)) return true;
if (b.tail) |t| if (w.expr(t.*)) return true;
return false;
}
fn loopBody(w: *After, cond: ?ast.Expr, body: ast.Block, step: ?[]const u8) bool {
const was = w.seen;
if (cond) |c| if (w.expr(c)) return true;
const r = w.block(body);
if (r) return true;
// Found inside this loop: everything in it can run again.
if (!was and w.seen) return loopReads(.{ .cond = cond, .body = body, .step = step }, w.name);
return false;
}
fn stmt(w: *After, st: ast.Stmt) bool {
if (!w.seen and spanEq(st.span, w.construct)) {
w.seen = true;
return false;
}
return switch (st.kind) {
.let => |x| w.expr(x.e),
.@"var" => |x| if (x.init) |e| w.expr(e) else false,
.assign => |x| w.expr(x.e) or (x.place.kind != .name and w.expr(x.place)),
.borrow => |x| w.expr(x.place),
.@"return" => |e| if (e) |x| w.expr(x) else false,
.expr => |e| w.expr(e),
.@"while" => |x| w.loopBody(x.cond, x.body, null),
.@"for" => |x| w.expr(x.lo) or w.expr(x.hi) or w.loopBody(null, x.body, x.name),
.loop => |b| w.loopBody(null, b, null),
.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,
.@"break", .@"continue", .trap => false,
};
}
};
+4 -1
View File
@@ -620,7 +620,10 @@ const Parser = struct {
switch (p.peek().tag) { switch (p.peek().tag) {
.dot => { .dot => {
_ = p.next(); _ = p.next();
const name = try p.ident("a field, method or operation name"); // After `.` a keyword is a member name (`task.cancelled`).
const nt = p.peek();
if (nt.tag != .ident) return p.fail(nt, "a field, method or operation name");
const name = p.next().text;
const base = try p.box(ast.Expr, e); const base = try p.box(ast.Expr, e);
e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } };
// `channel.make<T>(…)`: the only explicit type argument. // `channel.make<T>(…)`: the only explicit type argument.
+1 -1
View File
@@ -31,7 +31,7 @@ Every test starts with a block of `;` lines. Keys:
| `stdout` / `stderr` | no | expected captured output (same escapes) | | `stdout` / `stderr` | no | expected captured output (same escapes) |
| `file` | no, repeatable | `<path>=<text>`: expected contents of a file written by the run | | `file` | no, repeatable | `<path>=<text>`: expected contents of a file written by the run |
| `fuel` | no | instruction limit for `run` tests (spec 11 §7.1); default 1 000 000. Running out is a `FAIL`, never a pass | | `fuel` | no | instruction limit for `run` tests (spec 11 §7.1); default 1 000 000. Running out is a `FAIL`, never a pass |
| `equivalent` | no, `.aji` `run` tests only | path, relative to `tests/conformance`, of a reference AIR program. Both are run with this test's world and grants; their run records must be byte-identical (for a trap, the trap code must match, since the record carries the AIR location). The AIR texts may differ | | `equivalent` | no, `.aji` `run` tests only | path, relative to `tests/conformance`, of a reference AIR program. Both are run with this test's world and grants; their run records must be byte-identical (for a trap, the trap code must match, since the record carries the AIR location; `schedule.choices` is not compared, since the scheduler's quantum counts AIR instructions and the lowered program may have a different instruction stream). The AIR texts may differ |
| `phase` | yes | implementation phase number | | `phase` | yes | implementation phase number |
| `spec` | yes | spec section that justifies the expectation | | `spec` | yes | spec section that justifies the expectation |
@@ -0,0 +1,22 @@
// The only task waits on a channel whose sender it still holds: no future event can
// wake it, so the run ends blocked (an environment outcome, not an error or a trap).
// expect: run
// blocked: no_future_event
// grant: heap=mem.alloc:64
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.blocked
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
let v = channel.recv(rx) or trap;
channel.close_sender(move tx);
channel.close_receiver(move rx) or trap;
v
}
err(e) => { trap; }
}
}
@@ -0,0 +1,27 @@
// task.cancel only requests: the child sees the flag, returns, and is still joined.
// expect: run
// schedules: 10
// result: 7
// equivalent: phase3/run/tasks_cancel_request.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.cancelrequest
fn worker() -> u8
effects []
{
while not task.cancelled() {}
7
}
fn main() -> u8
effects [task.spawn]
{
var r: u8 = 0;
scope sc {
let t = task.spawn(sc, worker);
task.cancel(t);
r = task.join(move t);
}
r
}
@@ -0,0 +1,51 @@
// 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
// equivalent: phase3/run/channels_drain_linear.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.drainlinear
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<own<u64>>(4, heap) {
ok(tx, rx) => {
let a = own.new(1u64, heap) or trap;
channel.send(tx, move a) or trap;
let b = own.new(2u64, heap) or trap;
channel.send(tx, move b) or trap;
var acc: u64 = 0;
match channel.close_receiver(move rx) {
ok => { trap; }
pending(r) => {
let c = own.new(10u64, heap) or trap;
match channel.send(tx, move c) {
ok => { trap; }
closed(back) => { acc = own.take(move back); }
cancelled(back) => { acc = own.take(move back); }
}
var rr: receiver<own<u64>> = move r;
loop {
match channel.recv(rr) {
ok(o) => { acc = acc + own.take(move o); }
closed => {
match channel.close_receiver(move rr) {
ok => { break; }
pending(rr) => {}
}
}
cancelled => {}
}
}
}
}
channel.close_sender(move tx);
acc
}
err(e) => { trap; }
}
}
@@ -0,0 +1,64 @@
// Two producers share one channel through channel.dup; the receiver sees closed
// only after both senders are closed.
// expect: run
// grant: heap=mem.alloc:64
// schedules: 20
// quantum: 2
// result: 20
// equivalent: phase3/run/channels_mpsc_dup.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.mpscdup
fn produce(tx: sender<u64>) -> u8
effects [task.wait]
{
var i: u64 = 1;
while i != 5 {
match channel.send(tx, i) {
ok => {}
closed(w) => { break; }
cancelled(w) => { break; }
}
i = i + 1;
}
channel.close_sender(move tx);
0
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
let tx2 = channel.dup(tx);
var acc: u64 = 0;
scope sc {
let a = task.spawn(sc, produce, move tx);
let b = task.spawn(sc, produce, move tx2);
var r: receiver<u64> = move rx;
loop {
match channel.recv(r) {
ok(v) => { acc = acc + v; }
closed => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
cancelled => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
}
}
let x = task.join(move a);
let y = task.join(move b);
}
acc
}
err(e) => { trap; }
}
}
@@ -0,0 +1,36 @@
// Two tasks square the two halves of one buffer; the halves are lent until the joins.
// expect: run
// result: [1,4,9,16]
// equivalent: phase3/run/tasks_parallel_square.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.parallelsquare
fn square(s: slice_mut<u64>) -> void
effects []
{
for i in 0..s.len {
s[i] = s[i] * s[i];
}
}
fn main() -> [u64; 4]
effects [task.spawn]
{
var buf: [u64; 4] = zero;
buf[0] = 1;
buf[1] = 2;
buf[2] = 3;
buf[3] = 4;
{
mut s = buf;
let (l, r) = s.split_at(2);
scope sc {
let t1 = task.spawn(sc, square, l);
let t2 = task.spawn(sc, square, r);
task.join(move t1);
task.join(move t2);
}
}
buf
}
@@ -0,0 +1,82 @@
module demo.parallelsquare
air 0
lang 0.1
features [arrays, effects, ownership, tasks]
fn @square(%s: slice_mut<u64>) -> void
effects []
entry:
%c_1 = const.usize 0
%len_2 = slice.len %s
br @while_3(%c_1)
while_3(%i_6: usize):
%cmp_8 = lt.usize %i_6, %len_2
cbr %cmp_8, @body_9(), @after_4()
after_4:
ret
step_5(%i_7: usize):
%one_16 = const.usize 1
%i_17 = add.checked.usize %i_7, %one_16
br @while_3(%i_17)
body_9:
%e_10 = borrow.index %s, %i_6
%v_11 = load %e_10
borrow.end %e_10
%e_12 = borrow.index %s, %i_6
%v_13 = load %e_12
borrow.end %e_12
%t_14 = mul.checked.u64 %v_11, %v_13
%e_15 = borrow.index %s, %i_6
store %e_15, %t_14
borrow.end %e_15
br @step_5(%i_6)
fn @main() -> array<u64, 4>
effects [task.spawn]
entry:
%buf_1 = local.alloc array<u64, 4>
local.zero %buf_1
%c_2 = const.u64 1
%buf_3 = borrow.mut %buf_1
%c_4 = const.usize 0
%e_5 = borrow.index %buf_3, %c_4
store %e_5, %c_2
borrow.end %e_5
borrow.end %buf_3
%c_6 = const.u64 2
%buf_7 = borrow.mut %buf_1
%c_8 = const.usize 1
%e_9 = borrow.index %buf_7, %c_8
store %e_9, %c_6
borrow.end %e_9
borrow.end %buf_7
%c_10 = const.u64 3
%buf_11 = borrow.mut %buf_1
%c_12 = const.usize 2
%e_13 = borrow.index %buf_11, %c_12
store %e_13, %c_10
borrow.end %e_13
borrow.end %buf_11
%c_14 = const.u64 4
%buf_15 = borrow.mut %buf_1
%c_16 = const.usize 3
%e_17 = borrow.index %buf_15, %c_16
store %e_17, %c_14
borrow.end %e_17
borrow.end %buf_15
%buf_18 = borrow.mut %buf_1
%s_19 = slice.make %buf_18
%c_20 = const.usize 2
%l_21, %r_22 = slice.split %s_19, %c_20
%sc_23 = task.scope.begin
%t_24 = task.spawn %sc_23, @square(%l_21)
%t_25 = task.spawn %sc_23, @square(%r_22)
task.join %t_24
task.join %t_25
task.scope.end %sc_23
borrow.end %r_22
borrow.end %l_21
borrow.end %s_19
borrow.end %buf_18
%buf_26 = local.load %buf_1
ret %buf_26
@@ -0,0 +1,61 @@
// A producer task sends 0..4; the consumer receives until closed and closes the receiver,
// which is carried through the loop and rebound on `pending`.
// expect: run
// grant: heap=mem.alloc:64
// schedules: 20
// quantum: 2
// result: 10
// equivalent: phase3/run/channels_producer_consumer.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.producerconsumer
fn produce(tx: sender<u64>, n: u64) -> u8
effects [task.wait]
{
var i: u64 = 0;
while i != n {
match channel.send(tx, i) {
ok => {}
closed(w) => { break; }
cancelled(w) => { break; }
}
i = i + 1;
}
channel.close_sender(move tx);
0
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(2, heap) {
ok(tx, rx) => {
var acc: u64 = 0;
scope sc {
let t = task.spawn(sc, produce, move tx, 5);
var r: receiver<u64> = move rx;
loop {
match channel.recv(r) {
ok(v) => { acc = acc + v; }
closed => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
cancelled => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
}
}
let x = task.join(move t);
}
acc
}
err(e) => { trap; }
}
}
@@ -0,0 +1,80 @@
module demo.producerconsumer
air 0
lang 0.1
features [cancellation, capabilities, channels, effects, heap, ownership, resources, tasks]
fn @produce(%tx: sender<u64>, %n: u64) -> u8
effects [task.wait]
entry:
%c_1 = const.u64 0
br @while_2(%c_1)
while_2(%i_4: u64):
%cmp_5 = ne.u64 %i_4, %n
cbr %cmp_5, @body_6(), @after_3()
after_3:
channel.close_sender %tx
%c_17 = const.u8 0
ret %c_17
body_6:
%tx_7 = borrow.mut %tx
channel.send %tx_7, %i_4, ok -> @ok_8, closed -> @closed_9, cancelled -> @cancelled_11
ok_8:
borrow.end %tx_7
br @endmatch_13(%i_4)
closed_9(%closed_10: u64):
borrow.end %tx_7
br @after_3()
cancelled_11(%cancelled_12: u64):
borrow.end %tx_7
br @after_3()
endmatch_13(%i_14: u64):
%c_15 = const.u64 1
%t_16 = add.checked.u64 %i_14, %c_15
br @while_2(%t_16)
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
entry:
%c_1 = const.usize 2
channel.make u64, %c_1, %heap, ok -> @ok_2, err -> @err_5
ok_2(%ok_3: sender<u64>, %ok_4: receiver<u64>):
%c_7 = const.u64 0
%sc_8 = task.scope.begin
%c_9 = const.u64 5
%t_10 = task.spawn %sc_8, @produce(%ok_3, %c_9)
br @loop_11(%c_7, %ok_4)
err_5(%err_6: alloc_error):
trap
loop_11(%acc_13: u64, %r_14: receiver<u64>):
%r_16 = borrow.mut %r_14
channel.recv %r_16, ok -> @ok_17, closed -> @closed_19, cancelled -> @cancelled_20
after_12(%acc_15: u64):
%r_37 = task.join %t_10
task.scope.end %sc_8
br @endmatch_38(%acc_15)
ok_17(%ok_18: u64):
borrow.end %r_16
%t_21 = add.checked.u64 %acc_13, %ok_18
br @endmatch_34(%t_21, %r_14)
closed_19:
borrow.end %r_16
channel.close_receiver %r_14, ok -> @ok_22, pending -> @pending_23
cancelled_20:
borrow.end %r_16
channel.close_receiver %r_14, ok -> @ok_28, pending -> @pending_29
ok_22:
br @after_12(%acc_13)
pending_23(%pending_24: receiver<u64>):
br @endmatch_25(%acc_13, %pending_24)
endmatch_25(%acc_26: u64, %r_27: receiver<u64>):
br @endmatch_34(%acc_26, %r_27)
ok_28:
br @after_12(%acc_13)
pending_29(%pending_30: receiver<u64>):
br @endmatch_31(%acc_13, %pending_30)
endmatch_31(%acc_32: u64, %r_33: receiver<u64>):
br @endmatch_34(%acc_32, %r_33)
endmatch_34(%acc_35: u64, %r_36: receiver<u64>):
br @loop_11(%acc_35, %r_36)
endmatch_38(%match_39: u64):
ret %match_39
@@ -0,0 +1,28 @@
// The parent reads a buffer half it lent exclusively to a running task (E4101).
// expect: reject E4101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.access_lent
fn bump(s: slice_mut<u64>) -> void
effects []
{
s[0] = s[0] + 1;
}
fn main() -> u64
effects [task.spawn]
{
var buf: [u64; 4] = zero;
var seen: u64 = 0;
{
mut s = buf;
let (l, r) = s.split_at(2);
scope sc {
let a = task.spawn(sc, bump, l);
seen = l[0];
task.join(move a);
}
}
seen
}
@@ -0,0 +1,19 @@
// An endpoint operand is written by name; the operation borrows it (one canonical spelling).
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.endpoint_borrow_written
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
channel.send(mut tx, 1u64) or trap;
channel.close_sender(move tx);
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,17 @@
// Task handles are function-bound: a task<T> parameter needs the reserved feature task_transfer.
// expect: reject E0006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.handle_as_parameter
fn finish(t: task<u64>) -> u64
effects []
{
task.join(move t)
}
fn main() -> u64
effects []
{
0
}
@@ -0,0 +1,27 @@
// A region is not Share: lending a ref<region> to a task is rejected (E4002).
// expect: reject E4002
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.not_share
fn look(r: ref<region>) -> u64
effects []
{
0
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn]
{
let r = region.create(heap) or trap;
var v: u64 = 0;
{
ref arena = r;
scope sc {
let t = task.spawn(sc, look, arena);
v = task.join(move t);
}
}
region.destroy(move r);
v
}
@@ -0,0 +1,17 @@
// A receiver that is never closed: the frontend inserts no close; the verifier reports the leak.
// expect: reject E3002
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.receiver_leak
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);
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,23 @@
// channel.recv may suspend: it requires the effect task.wait (E3101).
// expect: reject E3101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.recv_without_effect
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
channel.close_sender(move tx);
match channel.recv(rx) {
ok(v) => {}
closed => {}
cancelled => {}
}
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,27 @@
// The same exclusive borrow lent to two live tasks: a possible data race (E4101).
// expect: reject E4101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.same_mut_twice
fn bump(s: slice_mut<u64>) -> void
effects []
{
s[0] = s[0] + 1;
}
fn main() -> u64
effects [task.spawn]
{
var buf: [u64; 2] = zero;
{
mut s = buf;
scope sc {
let a = task.spawn(sc, bump, s);
let b = task.spawn(sc, bump, s);
task.join(move a);
task.join(move b);
}
}
buf[0]
}
@@ -0,0 +1,20 @@
// A task not joined before its scope ends: the verifier reports E4301.
// expect: reject E4301
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.scope_unjoined
fn work() -> u64
effects []
{
1
}
fn main() -> u64
effects [task.spawn]
{
scope sc {
let t = task.spawn(sc, work);
}
0
}
@@ -0,0 +1,22 @@
// A borrow lent to a task stays lent until the join, so it is bound first, not written inline.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.spawn_inline_borrow
fn bump(s: slice_mut<u64>) -> void
effects []
{
s[0] = s[0] + 1;
}
fn main() -> u64
effects [task.spawn]
{
var buf: [u64; 2] = zero;
scope sc {
let a = task.spawn(sc, bump, mut buf);
task.join(move a);
}
buf[0]
}
@@ -0,0 +1,28 @@
// A sender moved into a task is written `move tx`.
// expect: reject E7003
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.spawn_missing_move
fn produce(tx: sender<u64>) -> u8
effects []
{
channel.close_sender(move tx);
0
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(1, heap) {
ok(tx, rx) => {
scope sc {
let t = task.spawn(sc, produce, tx);
task.join(move t);
}
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
@@ -0,0 +1,19 @@
// task.spawn spawns into a scope bound by `scope s { … }`.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.spawn_outside_scope
fn work() -> u64
effects []
{
1
}
fn main() -> u64
effects [task.spawn]
{
let s = 0u64;
let t = task.spawn(s, work);
task.join(move t)
}
@@ -0,0 +1,27 @@
// channel.send consumes the value: using it afterwards is E2001 from the verifier.
// expect: reject E2001
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.use_after_send
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<own<u64>>(1, heap) {
ok(tx, rx) => {
let o = own.new(1u64, heap) or trap;
channel.send(tx, move o) or trap;
var v: u64 = 0;
{
ref q = o;
v = *q;
}
channel.close_sender(move tx);
let w = channel.recv(rx) or trap;
own.free(move w);
channel.close_receiver(move rx) or trap;
v
}
err(e) => { trap; }
}
}
@@ -0,0 +1,60 @@
// 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
// equivalent: phase3/run/channels_rendezvous.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.rendezvous
fn produce(tx: sender<u64>) -> u8
effects [task.wait]
{
var i: u64 = 1;
while i != 4 {
match channel.send(tx, i) {
ok => {}
closed(w) => { break; }
cancelled(w) => { break; }
}
i = i + 1;
}
channel.close_sender(move tx);
0
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<u64>(0, heap) {
ok(tx, rx) => {
var acc: u64 = 0;
scope sc {
let t = task.spawn(sc, produce, move tx);
var r: receiver<u64> = move rx;
loop {
match channel.recv(r) {
ok(v) => { acc = acc + v; }
closed => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
cancelled => {
match channel.close_receiver(move r) {
ok => { break; }
pending(r) => {}
}
}
}
}
let x = task.join(move t);
}
acc
}
err(e) => { trap; }
}
}
@@ -0,0 +1,30 @@
// The same shared borrow of Share data is lent to two tasks.
// expect: run
// schedules: 10
// result: 42
// equivalent: phase3/run/tasks_shared_read.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.sharedread
fn read(p: ref<u64>) -> u64
effects []
{
*p
}
fn main() -> u64
effects [task.spawn]
{
var x: u64 = 21;
ref r = x;
var sum: u64 = 0;
scope sc {
let t1 = task.spawn(sc, read, r);
let t2 = task.spawn(sc, read, r);
let a = task.join(move t1);
let b = task.join(move t2);
sum = a + b;
}
sum
}
@@ -0,0 +1,26 @@
// Spawning beyond the deterministic task limit is an environment outcome, not a trap.
// expect: run
// task_limit: 2
// limit_exceeded: tasks
// equivalent: phase3/run/tasks_limit.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.tasklimit
fn noop() -> void
effects []
{
}
fn main() -> void
effects [task.spawn]
{
scope sc {
let a = task.spawn(sc, noop);
let b = task.spawn(sc, noop);
let c = task.spawn(sc, noop);
task.join(move a);
task.join(move b);
task.join(move c);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Quick Reference §7: a scope with two tasks over disjoint halves (layer 7). // Quick Reference §7: a scope with two tasks over disjoint halves (layer 7).
// expect: run // expect: run
// result: 30 // result: 32
// phase: 6 // phase: 6
// spec: docs/agent/quick-reference.md // spec: docs/agent/quick-reference.md
module demo.qrtasks module demo.qrtasks