Phase 6A: .aji layer 5 (linear values, own, regions, outcome matches, or trap)

- explicit move for named linear values; E7003 with suggestion "move x";
  move of a copyable value is E7006; moved state left to the verifier
- own.new/own.array/region.create/region.new/region.array/cap.narrow.budget
  as outcome matches or with `or trap`; own.take/own.free/region.reset/
  region.destroy as AIR names in AIR operand order
- region.new/region.array take an explicit ref/mut region binding (E7005
  otherwise); reset/destroy end nothing (verifier E2104)
- match kind (enum/outcome/integer) decided by the parser; built-in error
  enums (alloc_error, cap_error, io_error) matched exhaustively
- cap<K> types; linear owners borrowed in place
- features header = registry closure of the features used
- parameters keep their source names (grants by @main parameter name)
- aji lower --stats: mechanical_air_eliminated = 1 - source/AIR bytes
- spec 15, grammar, quick reference, plan updated
This commit is contained in:
dev committed 2026-10-05 12:06:23 +03:00
1 parent eca30f817a
commit bdcf871e5d
28 files changed
+882 -78

No files matched your search

+14 -1
View File
@@ -124,7 +124,20 @@ Capabilities are only ever received (as `main` parameters, passed down as argume
| `fs.read` / `fs.write` | same | `fs.open_read(c, path) → ok(f)`, `fs.create(c, path)`, `fs.open_append(c, path)`; `fs.read(f, mut buf) → ok(n)`; `fs.write_all(f, ref bytes)`; `fs.sync(f)`; `fs.close(move f)` |
| `net.listen` / `net.connect` | same; `net.recv` needs `net.read`, `net.send_all` needs `net.write` | `net.listen(c, b"127.0.0.1:7") → ok(l)`; `net.accept(l) → ok(s)`; `net.connect(c, addr) → ok(s)`; `net.recv(s, mut buf) → ok(n)` (0 = closed); `net.send_all(s, ref bytes)`; `net.close_stream(move s)`; `net.close_listener(move l)` |
| `clock.read`, `random.read` | same | `clock.monotonic(c)` (infallible, `u64`); `random.fill(c, mut buf)` (infallible) |
| `mem.alloc` | `mem.alloc` | `own.new(heap, v) → ok(o) / err(e)`; `own.array(heap, n, v)`; `own.take(move o)`, `own.free(move o)`; `region.create(heap) → ok(r)`; `region.new(r, v) → ok(p)`; `region.array(r, n, v)`; `region.reset(r)`; `region.destroy(move r)` |
| `mem.alloc` | `mem.alloc` | `own.new(v, heap) → ok(o) / err(e)`; `own.array(n, v, heap)`; `own.take(move o)`, `own.free(move o)`; `region.create(heap) → ok(r)`; `ref arena = r;` then `region.new(arena, v) → ok(p)`, `region.array(arena, n, v)`; `region.reset(r)`; `region.destroy(move r)`; `cap.narrow.budget(heap, n) → ok(small) / err(e)` |
A region allocation needs an explicit borrow of the region that outlives the allocations; `region.reset`/`region.destroy` while one is live is `E2104`, so end it first with a block:
```aji
{
ref arena = r;
let item = region.new(arena, 1u64) or trap; // item: mut<u64>, ends with this block
*item = *item + 1;
}
region.reset(r);
```
`err(e)` binds a real value: `match e { alloc_error::budget_exceeded => …, alloc_error::out_of_memory => … }`.
- **Narrowing:** `cap.narrow.prefix(c, b"/data")` and `cap.narrow.budget(heap, 4096)`, each giving `ok(c2) / err(e)`.
- Resource operands (`f`, `s`, `l`, `r`, endpoints) are borrowed automatically for an operation; data borrows (`mut buf`, `ref bytes`) are always written.
+2 -2
View File
@@ -41,8 +41,8 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| 1 | scalars, expressions, functions, control flow, variables carried across joins, short-circuit `and`/`or`, casts | done |
| 2 | structs (named construction, declaration-order lowering), enums (`Enum::Variant`), exhaustive `match` over enums (no `_`) and integers (`_` required), `match` as an expression; outcome matches and `or trap` move to layer 5 with the fallible operations | 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 | `own`, regions, resources, unsafe | todo |
| 6 | capabilities, intrinsics, I/O | todo |
| 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 | host capabilities and grants, intrinsics, I/O, resources (`file`, `stream`, `listener`), `cap.narrow.prefix`, `trusted`/unsafe | todo |
| 7 | tasks, channels | todo |
| 8 | `lock`, `select`, cancellation, shields | todo |
+3 -1
View File
@@ -39,6 +39,8 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ;
(* `region`, `listener`, `stream`, `io_error`, `alloc_error`,
`cap_error` are built-in type names (ident). *)
(* A built-in operation is a call whose callee is a dotted path:
`own.new(v, mem)`, `region.new(arena, v)`, `cap.narrow.budget(c, n)`. *)
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
statement = "let" binding [ ":" type ] "=" expr ";"
@@ -92,5 +94,5 @@ field_init = ident ":" expr ;
place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ;
string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \t \\ \" \xHH *)
string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *)
ident = ( letter | "_" ) { letter | digit | "_" } ;
+31 -7
View File
@@ -192,7 +192,10 @@ The value is evaluated first, then the place is borrowed for the store and the b
**Moves.**
- A named linear value is consumed only by `move x`. Using a named linear value as a consuming operand without `move` is `E7003`.
- A named linear value (`own<T>`, `own_array<T>`, `region`, and the resources and endpoints of later layers) is consumed only by `move x`. Using a named linear value as a consuming operand without `move` is `E7003`; the diagnostic carries `suggestion: "move x"`. Consuming operands are: call arguments, `let`/`var` initializers, assignments, `return`, the value operand of an allocation, and `own.take`, `own.free`, `region.destroy`.
- `move` of a copyable value is `E7006`.
- The frontend does not track moved state. Use after move (`E2001`), double consumption (`E2002`), use after consume (`E3001`) and leaks (`E3002`) are found by the verifier on the lowered AIR and reported at the source location.
- A linear value used as a borrow place (`ref x`, `mut x`, `ref r = x;`) is borrowed in place: `own<T>` as `ref<T>`/`mut<T>`, `own_array<T>` as `slice<T>`/`slice_mut<T>`, `region` as `ref<region>`. There is no implicit dereference of an owner.
- A temporary, that is the result of a call or operation used directly as an operand, needs no `move`: it has no other owner in the source.
- Copyable values are copied by plain use.
@@ -217,6 +220,8 @@ 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`.
- **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)`.
- **`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`.
@@ -286,23 +291,42 @@ Step 4 happens at **every normal exit** from the block: fall-through, and every
**Resource and endpoint operands.** An operation whose AIR operand is a borrow of a resource or endpoint accepts the resource by name and borrows it for the duration of the operation:
- `file<…>`, `stream`, `listener`, `region`;
- `file<…>`, `stream`, `listener`;
- `sender<T>`, `receiver<T>`;
- `task<T>` for `task.cancel`.
For example `net.accept(l)`, `fs.read(f, mut buf)`, `channel.send(tx, move v)`. Data borrows (`ref`/`mut` of values, arrays and slices) are always written. A mutex is borrowed explicitly: `lock ref m`.
For example `net.accept(l)`, `fs.read(f, mut buf)`, `channel.send(tx, move v)`. Data borrows (`ref`/`mut` of values, arrays and slices) are always written. A mutex is borrowed explicitly: `lock ref m`. A region is borrowed explicitly too (§8).
## 8. Allocation, resources and intrinsics
Allocation and resource operations keep their AIR names and operand order:
- `own.new(mem, v)` and `own.array(mem, n, v)` (matches, §6);
- `own.take(move o)`, `own.free(move o)`;
- `region.create(mem)`, `region.new(r, v)`, `region.array(r, n, v)`;
- `own.new(v, mem)` and `own.array(n, v, mem)` (outcome matches, §6): `ok(o)` binds `own<T>` / `own_array<T>`, `err(e)` an `alloc_error`;
- `let v = own.take(move o);`, `own.free(move o);` (`own<T>` or `own_array<T>`; there is no take for arrays);
- `region.create(mem)`: `ok(r)` binds a `region`;
- `region.new(rb, v)`, `region.array(rb, n, v)`: `rb` MUST be a `ref`/`mut` borrow binding of the region; `ok(item)` binds `mut<T>` / `slice_mut<T>`;
- `region.reset(r)`, `region.destroy(move r)`;
- `cap.narrow.budget(c, n)`, `cap.narrow.prefix(c, path)`;
- `cap.narrow.budget(c, n)`: `ok(c2)` binds a `cap<K>`, `err(e)` a `cap_error`; `cap.narrow.prefix(c, path)` (layer 6);
- capabilities are values of type `cap<K>`, received as parameters and copied by plain use (no `move`);
- intrinsics under their registered names (`reference/intrinsics.md`): `io.stdout_write(out, ref buf[0..n])`, `fs.open_read(c, b"data.txt")`, `fs.close(move f)`, `net.listen(c, b"127.0.0.1:7")`.
**Region borrows are explicit.** The borrow of a region that `region.new`/`region.array` take is written by the programmer and lexically outlives the allocation borrows derived from it:
```aji
{
ref arena = r;
match region.new(arena, 1u64) {
ok(item) => { *item = *item + 1; }
err(e) => { trap; }
}
}
region.reset(r);
```
Passing the region itself is `E7005`; the frontend never creates a temporary region borrow. `region.reset` and `region.destroy` end no borrow: a live allocation borrow at a reset or destroy is the verifier's `E2104`. The programmer narrows the scope.
**Linear aggregates.** A struct or enum with a linear field (`own<T>`, `region`, a resource) needs the reserved feature `linear_aggregates`. The frontend lowers it as written and the AIR is rejected (`E0006`) until that feature is published.
A byte string or array used where a `slice<u8>` is expected is materialized in frame storage and borrowed for the operation.
## 9. Frame storage, borrow scopes and features
+16 -1
View File
@@ -103,7 +103,22 @@ pub const Pattern = struct {
pub const Arm = struct { pattern: Pattern, body: Expr };
pub const Match = struct { scrutinee: Expr, arms: []const Arm, span: Span };
pub const Match = struct {
scrutinee: Expr,
arms: []const Arm,
span: Span,
/// Decided by the parser from the arms' patterns (spec 15 §6).
kind: Kind,
pub const Kind = enum {
/// `Enum::Variant` arms: `enum.switch`.
@"enum",
/// Outcome arms (`ok(…)`, `err(e)`, `closed`, …) of a fallible operation: its terminator's edges.
outcome,
/// Integer literals and `_`: `switch`.
integer,
};
};
pub const SelectArm = struct {
span: Span,
+394 -51
View File
@@ -15,11 +15,15 @@
//! 1. scalars, expressions, functions, control flow;
//! 2. structs, enums, exhaustive `match`;
//! 3–4. addressable values (frame storage chosen by lowering), lexical
//! borrows, places, arrays, slices, byte strings.
//! borrows, places, arrays, slices, byte strings;
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
//! outcome matches and `or trap`.
const std = @import("std");
const ast = @import("ast.zig");
const parse_mod = @import("parse.zig");
const authority = @import("../air/authority.zig");
const features_mod = @import("../air/features.zig");
const Allocator = std.mem.Allocator;
const Span = ast.Span;
@@ -37,23 +41,37 @@ pub const Ty = union(enum) {
mut: *const Ty,
slice: *const Ty,
slice_mut: *const Ty,
own: *const Ty,
own_array: *const Ty,
region,
/// `cap<K>`: the kind.
cap: []const u8,
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
builtin: authority.Builtin,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return t == .own or t == .own_array or t == .region;
}
fn eql(a: Ty, b: Ty) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
return switch (a) {
.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 => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
else => true,
};
}
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -202,6 +220,8 @@ const Lowerer = struct {
bindings: std.ArrayList(Binding) = .empty,
loops: std.ArrayList(Loop) = .empty,
counter: u32 = 0,
/// The current function's parameter names, which generated names avoid.
params: []const ast.Param = &.{},
ret: Ty = .void,
/// Statements still to be lowered in each enclosing block (innermost
/// last), for inferring the type of an untyped `let` from its uses.
@@ -236,7 +256,10 @@ 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 => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| @tagName(b),
};
}
@@ -299,10 +322,9 @@ const Lowerer = struct {
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
var features: std.ArrayList(u8) = .empty;
const uses = l.featureUse(type_lines.items);
if (uses.arrays) try features.appendSlice(l.arena, "arrays, ");
try features.appendSlice(l.arena, "effects");
if (uses.ownership) try features.appendSlice(l.arena, ", ownership");
const roots = try l.featureRoots(type_lines.items);
const closure = try features_mod.closure(l.arena, &features_mod.registry, roots, null);
for (closure, 0..) |f, i| try features.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else ", ", f }));
try l.line(try l.fmt("module {s}", .{l.m.name}), whole);
try l.line("air 0", whole);
@@ -313,31 +335,38 @@ const Lowerer = struct {
for (l.fns.items) |f| try l.emitFunction(f);
}
/// Which features the lowered AIR uses: `arrays` (and so `ownership`)
/// for arrays and slices, `ownership` for frame storage and borrows.
fn featureUse(l: *Lowerer, type_lines: []const Inst) struct { arrays: bool, ownership: bool } {
var arrays = false;
var ownership = false;
const scan = struct {
fn has(text: []const u8, word: []const u8) bool {
return std.mem.indexOf(u8, text, word) != null;
}
}.has;
/// The features the lowered AIR uses directly; the header is their
/// dependency closure (spec 15 §9). `effects` is always declared.
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
var texts: std.ArrayList([]const u8) = .empty;
for (type_lines) |t| texts.append(l.arena, t.text) catch {};
for (type_lines) |t| try texts.append(l.arena, t.text);
for (l.fns.items) |f| {
texts.append(l.arena, f.header) catch {};
try texts.append(l.arena, f.header);
for (f.blocks) |b| {
for (b.params.items) |p| texts.append(l.arena, l.tyText(p.ty)) catch {};
for (b.insts.items) |inst| texts.append(l.arena, inst.text) catch {};
for (b.params.items) |p| try texts.append(l.arena, l.tyText(p.ty));
for (b.insts.items) |inst| try texts.append(l.arena, inst.text);
}
}
for (texts.items) |t| {
if (scan(t, "array<") or scan(t, "slice") or scan(t, "array.splat") or scan(t, "borrow.index")) arrays = true;
if (scan(t, "local.") or scan(t, "borrow.") or scan(t, " load ") or scan(t, "= load ") or std.mem.startsWith(u8, t, "store ") or scan(t, "ref<") or scan(t, "mut<")) ownership = true;
var roots: std.ArrayList([]const u8) = .empty;
try roots.append(l.arena, "effects");
const Rule = struct { []const u8, []const []const u8 };
const rules = [_]Rule{
.{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } },
.{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } },
.{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } },
.{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
const hit = for (r[1]) |w| {
if (std.mem.indexOf(u8, t, w) != null or (std.mem.eql(u8, w, "store ") and std.mem.startsWith(u8, t, "store "))) break true;
} else false;
if (hit) break true;
} else false;
if (used) try roots.append(l.arena, r[0]);
}
if (arrays) ownership = true;
return .{ .arrays = arrays, .ownership = ownership };
return roots.items;
}
/// `type @T = struct { … }` / `enum { … }` in canonical form.
@@ -387,13 +416,15 @@ const Lowerer = struct {
if (std.mem.eql(u8, n, "void")) return .void;
if (std.mem.eql(u8, n, "never")) return .never;
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
const later = [_][]const u8{ "region", "listener", "stream", "io_error", "alloc_error", "cap_error" };
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (later layers)");
if (std.mem.eql(u8, n, "region")) return .region;
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
const later = [_][]const u8{ "listener", "stream" };
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (layer 6)");
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array };
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) {
@@ -401,8 +432,14 @@ const Lowerer = struct {
.mut => l.wrap(.mut, in),
.slice => l.wrap(.slice, in),
.slice_mut => l.wrap(.slice_mut, in),
.own => l.wrap(.own, in),
.own_array => l.wrap(.own_array, in),
};
},
.cap => |k| {
if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "kind", .value = k }});
return .{ .cap = k };
},
else => return l.notYet(t.span, "this type (later layers)"),
}
}
@@ -418,6 +455,7 @@ const Lowerer = struct {
l.facts = .empty;
l.addressable = .empty;
l.counter = 0;
l.params = f.params;
try l.findAddressable(f.body);
const sig = l.sigs.get(f.name).?;
l.ret = sig.ret;
@@ -427,7 +465,8 @@ const Lowerer = struct {
var header: std.ArrayList(u8) = .empty;
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name}));
for (f.params, sig.params, 0..) |p, t, i| {
const v = try l.freshName(p.name);
// Parameters keep their source names: `@main` capabilities are granted by name.
const v = p.name;
// Borrow parameters are lent by the caller: never ended here.
try l.bindings.append(l.arena, .{ .name = p.name, .mutable = false, .value = v, .ty = t, .kind = if (t.isBorrow()) .borrow else .ssa });
try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, l.tyText(t) }));
@@ -479,8 +518,13 @@ const Lowerer = struct {
}
fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 {
l.counter += 1;
return l.fmt("{s}_{d}", .{ base, l.counter });
while (true) {
l.counter += 1;
const n = try l.fmt("{s}_{d}", .{ base, l.counter });
for (l.params) |p| {
if (std.mem.eql(u8, p.name, n)) break;
} else return n;
}
}
fn newBlock(l: *Lowerer, kind: []const u8) Error!usize {
@@ -646,7 +690,17 @@ const Lowerer = struct {
// An untyped `let` takes its type from how the name is used
// later (`return`, arguments, operations, annotations).
if (want == null and l.peekType(x.e) == null) want = l.inferUses(x.names[0]);
const v = try l.expr(x.e, want);
if (x.e.kind == .or_trap) {
const v = try l.expr(x.e, want);
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
if (v.ty.isBorrow()) {
// `let item = region.new(arena, v) or trap;`: a borrow bound to the block.
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
} else try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty });
return;
}
const v = try l.consuming(x.e, want);
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;`", &.{});
@@ -662,7 +716,7 @@ const Lowerer = struct {
if (l.addressable.contains(x.name)) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.expr(e, ty);
const v = try l.consuming(e, ty);
try l.checkTy(e.span, v.ty, ty);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
} else try l.emit(try l.fmt("local.zero %{s}", .{st}), s.span);
@@ -670,7 +724,7 @@ const Lowerer = struct {
return;
}
const v = if (x.init) |e| blk: {
const v = try l.expr(e, ty);
const v = try l.consuming(e, ty);
try l.checkTy(e.span, v.ty, ty);
break :blk v;
} else try l.zeroValue(ty, x.name, s.span);
@@ -684,7 +738,7 @@ const Lowerer = struct {
const ty = b.ty;
const kind = b.kind;
const storage = b.value;
const v = try l.expr(x.e, ty);
const v = try l.consuming(x.e, ty);
try l.checkTy(x.e.span, v.ty, ty);
if (kind == .storage) {
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ storage, v.name }), s.span);
@@ -711,7 +765,7 @@ const Lowerer = struct {
},
.@"return" => |e| {
if (e) |x| {
const v = try l.expr(x, l.ret);
const v = try l.consuming(x, l.ret);
try l.checkTy(x.span, v.ty, l.ret);
if (l.cur != null) {
try l.endScopes(0, s.span);
@@ -853,8 +907,9 @@ const Lowerer = struct {
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.sigs.get(n)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum"),
else => null,
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,
},
.move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum"),
.struct_lit => |x| l.enumOrStruct(x.name),
.field => |x| blk: {
@@ -1053,8 +1108,12 @@ const Lowerer = struct {
if (std.mem.eql(u8, x.name, "len")) return l.lenOf(e, x.e.*);
return l.fieldValue(e, x.e.*, x.name);
},
.or_trap => return l.notYet(e.span, "`or trap` (layer 5, with fallible operations)"),
.move => return l.notYet(e.span, "`move` (layer 5, with linear values)"),
.or_trap => |x| return l.orTrap(e, x.*),
.move => |n| {
const b = l.lookup(n) orelse return l.unknown(e.span, n);
if (!b.ty.isLinear()) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.tyText(b.ty) } });
return .{ .name = b.value, .ty = b.ty };
},
}
}
@@ -1124,7 +1183,30 @@ const Lowerer = struct {
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (pathOf(callee)) |p| if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
if (l.fallible(p) != null) return l.fail("E7006", e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }});
if (std.mem.eql(u8, p, "own.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{});
const o = try l.consuming(args[0], null);
if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own<T>`", &.{.{ .name = "found", .value = l.tyText(o.ty) }});
return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span);
}
if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{});
const o = try l.consuming(args[0], null);
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
return .{ .name = "", .ty = .void };
}
if (std.mem.eql(u8, p, "region.reset")) {
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{});
const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
return .{ .name = "", .ty = .void };
}
return l.notYet(callee.span, "this built-in operation (later layers)");
}
if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at"))
return l.fail("E7006", e.span, "`split_at` yields two borrows: `let (left, right) = s.split_at(k);`", &.{});
if (callee.kind != .name) return l.notYet(callee.span, "built-in operations (later layers)");
@@ -1267,7 +1349,9 @@ const Lowerer = struct {
/// `match` over an enum (`enum.switch`; exhaustive, no `_`) or an
/// integer (`switch`; `_` required). Payload names live in their arm.
fn matchExpr(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
if (m.kind == .outcome) return l.outcomeMatch(m, want);
const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.expr(m.scrutinee, st);
const depth = l.bindings.items.len;
const vars = try l.carried(depth);
@@ -1358,6 +1442,46 @@ const Lowerer = struct {
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// A match over a built-in enum (`alloc_error::out_of_memory`, …):
/// exhaustive, no `_`, like a declared enum.
fn builtinMatch(l: *Lowerer, m: ast.Match, b: authority.Builtin, want: ?Ty) Error!Value {
const name = @tagName(b);
const sv = try l.expr(m.scrutinee, .{ .builtin = b });
const depth = l.bindings.items.len;
const vars = try l.carried(depth);
const before = try l.snapshot();
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ name, sv.name }));
for (m.arms, blocks, 0..) |arm, *blk, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null or !std.mem.eql(u8, arm.pattern.kind.ctor.qualifier.?, name))
return l.fail("E7006", arm.pattern.span, try l.fmt("an arm names one variant as `{s}::variant`; `_` is not allowed", .{name}), &.{});
const c = arm.pattern.kind.ctor;
if (b.variantIndex(c.name) == null) return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = name }, .{ .name = "variant", .value = c.name } });
if (c.binds.len != 0) return l.fail("E7005", arm.pattern.span, "built-in error variants have no payload", &.{});
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
}
var missing: std.ArrayList(u8) = .empty;
for (b.variants()) |v| {
const covered = for (m.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, v)) break true;
} else false;
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", name, v }));
}
if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }});
try l.term(head.items, m.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (m.arms, blocks) |arm, blk| {
l.restore(before);
l.cur = blk;
const v = try l.armBody(arm.body, want);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
const v = try l.expr(body, want);
if (v.ty == .void) return null;
@@ -1438,10 +1562,19 @@ const Lowerer = struct {
try temps.appendSlice(l.arena, &.{ r.name, sl.name });
return sl;
},
else => return l.expr(a, want),
else => return l.consuming(a, want),
}
}
/// An operand that consumes its value: a named linear value must be
/// written `move x` (spec 15 §5). Use after move, double consumption and
/// leaks are the verifier's (E2001, E2002, E3001, E3002).
fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
if (e.kind == .name) if (l.lookup(e.kind.name)) |b| if (b.ty.isLinear() and b.kind == .ssa)
return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } });
return l.expr(e, want);
}
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
var x = e;
while (true) switch (x.kind) {
@@ -1480,7 +1613,18 @@ const Lowerer = struct {
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
.ssa => return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }}),
.ssa => {
// A linear value (owner, region) is borrowed in place.
const bt: ?Ty = switch (b.ty) {
.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),
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 }});
const v = try l.def(n, t, try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
}
},
.bytes => |bytes| {
@@ -1708,6 +1852,183 @@ const Lowerer = struct {
}
}
// ------------------------------------------------------------ fallible operations (layer 5)
const Outcome = struct { role: []const u8, params: []const Ty };
/// A lowered fallible operation: its AIR text before the targets and its
/// outcomes in AIR order.
const Fallible = struct { text: []const u8, outcomes: []const Outcome };
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" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
return null;
}
fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value {
const c = try l.expr(a, null);
if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.tyText(c.ty) } });
return c;
}
/// The region borrow of `region.new`/`region.array` must be an explicit
/// borrow binding, so that it outlives the allocation borrows derived
/// from it (spec 15 §8).
fn regionBorrow(l: *Lowerer, a: ast.Expr) Error!Value {
if (a.kind == .name) if (l.lookup(a.kind.name)) |b| {
if (b.kind == .borrow and (b.ty == .ref or b.ty == .mut) and b.ty.inner().? == .region) return .{ .name = b.value, .ty = b.ty };
if (b.ty == .region) return l.fail("E7005", a.span, "allocation in a region takes a borrow of it that outlives the allocations: bind `ref arena = region;` in an enclosing block and pass `arena`", &.{.{ .name = "name", .value = a.kind.name }});
};
return l.fail("E7005", a.span, "allocation in a region takes a `ref<region>` borrow binding", &.{});
}
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", &.{});
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 {
fn n(lw: *Lowerer, sp: Span, as: []const ast.Expr, k: usize, op: []const u8) Error!void {
if (as.len != k) return lw.fail("E7005", sp, "wrong number of operands", &.{ .{ .name = "operation", .value = op }, .{ .name = "expected", .value = try lw.fmt("{d}", .{k}) } });
}
}.n;
const alloc_err: Ty = .{ .builtin = .alloc_error };
const usize_ty: Ty = .{ .int = "usize" };
if (std.mem.eql(u8, path, "own.new")) {
try want(l, e.span, args, 2, path);
const v = try l.consuming(args[0], null);
const c = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("own.new %{s}, %{s}", .{ v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "own.array")) {
try want(l, e.span, args, 3, path);
const n = try l.expr(args[0], usize_ty);
try l.checkTy(args[0].span, n.ty, usize_ty);
const v = try l.consuming(args[1], null);
const c = try l.expectCap(args[2], "mem.alloc");
return .{ .text = try l.fmt("own.array %{s}, %{s}, %{s}", .{ n.name, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own_array, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.create")) {
try want(l, e.span, args, 1, path);
const c = try l.expectCap(args[0], "mem.alloc");
return .{ .text = try l.fmt("region.create %{s}", .{c.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{.region} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.new")) {
try want(l, e.span, args, 2, path);
const rb = try l.regionBorrow(args[0]);
const v = try l.consuming(args[1], null);
return .{ .text = try l.fmt("region.new %{s}, %{s}", .{ rb.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.array")) {
try want(l, e.span, args, 3, path);
const rb = try l.regionBorrow(args[0]);
const n = try l.expr(args[1], usize_ty);
try l.checkTy(args[1].span, n.ty, usize_ty);
const v = try l.consuming(args[2], null);
return .{ .text = try l.fmt("region.array %{s}, %{s}, %{s}", .{ rb.name, n.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.slice_mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "cap.narrow.budget")) {
try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null);
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.tyText(c.ty) }});
const n = try l.expr(args[1], usize_ty);
try l.checkTy(args[1].span, n.ty, usize_ty);
return .{ .text = try l.fmt("cap.narrow.budget %{s}, %{s}", .{ c.name, n.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }) };
}
return l.fail("E7006", e.span, "not a fallible operation", &.{.{ .name = "operation", .value = path }});
}
fn outs(l: *Lowerer, o: []const Outcome) Error![]const Outcome {
const out = try l.arena.alloc(Outcome, o.len);
for (o, out) |x, *y| y.* = .{ .role = x.role, .params = try l.arena.dupe(Ty, x.params) };
return out;
}
/// Creates one block per outcome (parameters = the outcome's values)
/// and emits the terminator `<op>, ok -> @a, err -> @b`.
fn outcomeBlocks(l: *Lowerer, f: Fallible, span: Span) Error![]const usize {
const blocks = try l.arena.alloc(usize, f.outcomes.len);
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, f.text);
for (f.outcomes, blocks) |o, *b| {
b.* = try l.newBlock(o.role);
for (o.params) |pt| try l.blocks.items[b.*].params.append(l.arena, .{ .name = try l.freshName(o.role), .ty = pt });
try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name }));
}
try l.term(text.items, span);
return blocks;
}
/// `match op(…) { ok(x) => …, err(e) => … }`: the arms are the edges of
/// the operation's terminator; every outcome exactly once (spec 15 §6).
fn outcomeMatch(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
const f = try l.lowerFallible(m.scrutinee);
for (m.arms, 0..) |arm, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null)
return l.fail("E7006", arm.pattern.span, "every arm of an outcome match names an outcome of the operation (`ok(…)`, `err(e)`, …)", &.{});
const c = arm.pattern.kind.ctor;
const o = for (f.outcomes) |o| {
if (std.mem.eql(u8, o.role, c.name)) break o;
} else return l.fail("E7002", arm.pattern.span, "this operation has no such outcome", &.{.{ .name = "outcome", .value = c.name }});
for (m.arms[0..i]) |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 }});
if (c.binds.len != o.params.len) return l.fail("E7005", arm.pattern.span, "the outcome binds a different number of values", &.{ .{ .name = "outcome", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{o.params.len}) } });
}
var missing: std.ArrayList(u8) = .empty;
for (f.outcomes) |o| {
const covered = for (m.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, o.role)) break true;
} else false;
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (missing.items.len == 0) "" else ", ", o.role }));
}
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 vars = try l.carried(depth);
const before = try l.snapshot();
const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (f.outcomes, blocks) |o, blk| {
const arm = for (m.arms) |a| {
if (std.mem.eql(u8, a.pattern.kind.ctor.name, o.role)) break a;
} else unreachable;
l.restore(before);
l.cur = blk;
// The outcome's values are bound in the arm; a borrow among them
// (a region allocation) ends with the arm.
try l.scopes.append(l.arena, .empty);
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 (std.mem.eql(u8, bn, "_")) 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 });
}
const v = try l.armBody(arm.body, want);
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, arm.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 = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// `op(…) or trap`: the `ok` value; every other outcome traps.
fn orTrap(l: *Lowerer, e: ast.Expr, inner_e: ast.Expr) Error!Value {
const f = try l.lowerFallible(inner_e);
const blocks = try l.outcomeBlocks(f, e.span);
for (f.outcomes, blocks) |o, blk| if (!std.mem.eql(u8, o.role, "ok")) {
l.cur = blk;
try l.term("trap", e.span);
};
const ok = for (f.outcomes, blocks) |o, blk| {
if (std.mem.eql(u8, o.role, "ok")) break blk;
} else unreachable;
l.cur = ok;
const ps = l.blocks.items[ok].params.items;
if (ps.len == 0) return .{ .name = "", .ty = .void };
if (ps.len != 1) return l.fail("E7006", e.span, "`or trap` on an operation with several results: use `match`", &.{});
return .{ .name = ps[0].name, .ty = ps[0].ty };
}
fn ifExpr(l: *Lowerer, span: Span, x: ast.If, want: ?Ty) Error!Value {
// `if i < s.len`: the verifier proves `i < len(s)` in the true branch
// (spec 08 §12); record it so that `s[i]` there needs no runtime check.
@@ -1770,15 +2091,37 @@ fn elemOf(t: Ty) ?Ty {
};
}
/// `a.b.c` for a callee made of names and fields.
/// 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 {
return switch (e.kind) {
.field => |f| switch (f.e.kind) {
.name => |n| if (std.mem.eql(u8, n, "slice") and std.mem.eql(u8, f.name, "copy")) "slice.copy" else null,
else => null,
},
else => null,
const known = [_][]const u8{
"slice.copy", "own.new", "own.array", "own.take", "own.free",
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
for (known) |k| if (std.mem.eql(u8, k, text)) return k;
return null;
}
fn dotted(e: ast.Expr, buf: []u8) ?[]const u8 {
switch (e.kind) {
.name => |n| {
if (n.len > buf.len) return null;
@memcpy(buf[0..n.len], n);
return buf[0..n.len];
},
.field => |f| {
const base = dotted(f.e.*, buf) orelse return null;
const len = base.len + 1 + f.name.len;
if (len > buf.len) return null;
buf[base.len] = '.';
@memcpy(buf[base.len + 1 .. len], f.name);
return buf[0..len];
},
else => return null,
}
}
fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
+9 -1
View File
@@ -701,7 +701,15 @@ const Parser = struct {
const scrut = try p.condition();
_ = try p.expect(.l_brace, "`{`");
const as = try p.arms();
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start) }) } };
var kind: ast.Match.Kind = .integer;
for (as) |a| switch (a.pattern.kind) {
.ctor => |c| {
kind = if (c.qualifier != null) .@"enum" else .outcome;
break;
},
else => {},
};
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } };
}
if (isKeyword(t.text)) return p.fail(t, "an expression");
_ = p.next();
+2
View File
@@ -125,6 +125,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
.air_lines = ac.lines,
.expansion_bytes = @as(f64, @floatFromInt(ac.bytes)) / @as(f64, @floatFromInt(@max(sc.bytes, 1))),
.expansion_lines = @as(f64, @floatFromInt(ac.lines)) / @as(f64, @floatFromInt(@max(sc.lines, 1))),
// 1 − source/AIR: the share of AIR text the frontend writes for the author.
.mechanical_air_eliminated = 1.0 - @as(f64, @floatFromInt(sc.bytes)) / @as(f64, @floatFromInt(@max(ac.bytes, 1))),
});
try out.writeByte('\n');
return .accepted;
@@ -3,22 +3,22 @@ air 0
lang 0.1
features [arrays, effects, ownership]
fn @get(%s_1: slice<u64>, %i_2: usize) -> u64
fn @get(%s: slice<u64>, %i: usize) -> u64
effects []
entry:
%len_3 = slice.len %s_1
%cmp_4 = lt.usize %i_2, %len_3
cbr %cmp_4, @then_5(), @else_6()
then_5:
%e_7 = borrow.index.proven %s_1, %i_2
%v_8 = load %e_7
borrow.end %e_7
ret %v_8
else_6:
br @endif_9()
endif_9:
%c_10 = const.u64 0
ret %c_10
%len_1 = slice.len %s
%cmp_2 = lt.usize %i, %len_1
cbr %cmp_2, @then_3(), @else_4()
then_3:
%e_5 = borrow.index.proven %s, %i
%v_6 = load %e_5
borrow.end %e_5
ret %v_6
else_4:
br @endif_7()
endif_7:
%c_8 = const.u64 0
ret %c_8
fn @main() -> u64
effects []
@@ -0,0 +1,22 @@
// err(e) binds a real alloc_error; it is matched like any closed enum.
// expect: run
// grant: heap=mem.alloc:8
// result: 2
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.allocerror
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
match own.array(64, 0u64, heap) {
ok(a) => {
own.free(move a);
1
}
err(e) => match e {
alloc_error::budget_exceeded => 2,
alloc_error::out_of_memory => 3,
},
}
}
@@ -0,0 +1,27 @@
module demo.allocerror
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%c_1 = const.usize 64
%c_2 = const.u64 0
own.array %c_1, %c_2, %heap, ok -> @ok_3, err -> @err_5
ok_3(%ok_4: own_array<u64>):
own.free %ok_4
%c_7 = const.u64 1
br @endmatch_14(%c_7)
err_5(%err_6: alloc_error):
enum.switch alloc_error %err_6, budget_exceeded -> @case_budget_exceeded_8, out_of_memory -> @case_out_of_memory_9
case_budget_exceeded_8:
%c_10 = const.u64 2
br @endmatch_12(%c_10)
case_out_of_memory_9:
%c_11 = const.u64 3
br @endmatch_12(%c_11)
endmatch_12(%match_13: u64):
br @endmatch_14(%match_13)
endmatch_14(%match_15: u64):
ret %match_15
@@ -0,0 +1,23 @@
// cap.narrow.budget gives a smaller allocation budget; caps are copied plainly.
// expect: run
// grant: heap=mem.alloc:256
// result: 5
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.narrow
fn make(small: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(5u64, small) or trap;
own.take(move x)
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
match cap.narrow.budget(heap, 16) {
ok(small) => make(small),
err(e) => 0,
}
}
@@ -0,0 +1,25 @@
// own.new is matched over its outcomes; the owner is borrowed in place, moved explicitly and taken.
// expect: run
// grant: heap=mem.alloc:64
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.ownbasic
fn bump(c: mut<u64>) -> void
effects []
{
*c = *c + 1;
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
match own.new(41u64, heap) {
ok(x) => {
bump(mut x);
own.take(move x)
}
err(e) => 0,
}
}
@@ -0,0 +1,30 @@
module demo.ownbasic
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @bump(%c: mut<u64>) -> void
effects []
entry:
%v_1 = load %c
%c_2 = const.u64 1
%t_3 = add.checked.u64 %v_1, %c_2
store %c, %t_3
ret
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%c_1 = const.u64 41
own.new %c_1, %heap, ok -> @ok_2, err -> @err_4
ok_2(%ok_3: own<u64>):
%x_6 = borrow.mut %ok_3
call @bump(%x_6)
borrow.end %x_6
%v_7 = own.take %ok_3
br @endmatch_9(%v_7)
err_4(%err_5: alloc_error):
%c_8 = const.u64 0
br @endmatch_9(%c_8)
endmatch_9(%match_10: u64):
ret %match_10
@@ -0,0 +1,22 @@
// `or trap`: ok continues, err traps; own.free consumes the owner.
// expect: run
// grant: heap=mem.alloc:64
// result: 9
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.ortrap
fn read(c: ref<u64>) -> u64
effects []
{
*c
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(9u64, heap) or trap;
let v = read(ref x);
own.free(move x);
v
}
@@ -0,0 +1,30 @@
// A region borrow is bound explicitly and outlives the allocation borrows derived from it.
// expect: run
// grant: heap=mem.alloc:256
// result: 30
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.region
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let r = region.create(heap) or trap;
var total: u64 = 0;
{
ref arena = r;
match region.new(arena, 10u64) {
ok(item) => {
*item = *item + 10;
total = total + *item;
}
err(e) => {}
}
let s = region.array(arena, 4, 2u64) or trap;
s[0] = 8;
total = total + s[0] + s[1];
}
region.reset(r);
region.destroy(move r);
total
}
@@ -0,0 +1,54 @@
module demo.region
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
region.create %heap, ok -> @ok_1, err -> @err_3
ok_1(%ok_2: region):
%c_5 = const.u64 0
%r_6 = borrow.ref %ok_2
%c_7 = const.u64 10
region.new %r_6, %c_7, ok -> @ok_8, err -> @err_10
err_3(%err_4: alloc_error):
trap
ok_8(%ok_9: mut<u64>):
%v_12 = load %ok_9
%c_13 = const.u64 10
%t_14 = add.checked.u64 %v_12, %c_13
store %ok_9, %t_14
%v_15 = load %ok_9
%t_16 = add.checked.u64 %c_5, %v_15
borrow.end %ok_9
br @endmatch_17(%t_16)
err_10(%err_11: alloc_error):
br @endmatch_17(%c_5)
endmatch_17(%total_18: u64):
%c_19 = const.usize 4
%c_20 = const.u64 2
region.array %r_6, %c_19, %c_20, ok -> @ok_21, err -> @err_23
ok_21(%ok_22: slice_mut<u64>):
%c_25 = const.u64 8
%c_26 = const.usize 0
%e_27 = borrow.index %ok_22, %c_26
store %e_27, %c_25
borrow.end %e_27
%c_28 = const.usize 0
%e_29 = borrow.index %ok_22, %c_28
%v_30 = load %e_29
borrow.end %e_29
%t_31 = add.checked.u64 %total_18, %v_30
%c_32 = const.usize 1
%e_33 = borrow.index %ok_22, %c_32
%v_34 = load %e_33
borrow.end %e_33
%t_35 = add.checked.u64 %t_31, %v_34
borrow.end %ok_22
borrow.end %r_6
region.reset %ok_2
region.destroy %ok_2
ret %t_35
err_23(%err_24: alloc_error):
trap
@@ -0,0 +1,19 @@
// Correct source, but the owner is consumed again after its move: the verifier reports E2002.
// expect: reject E2002
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.doubleconsume
fn sink(o: own<u64>) -> void
effects []
{
own.free(move o);
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(1u64, heap) or trap;
sink(move x);
own.take(move x)
}
@@ -0,0 +1,12 @@
// An owner that is never consumed: the verifier reports the leak.
// expect: reject E3002
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.leak
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(1u64, heap) or trap;
7
}
@@ -0,0 +1,13 @@
// A struct with a linear field needs the unpublished linear_aggregates feature: AIR rejects it.
// expect: reject E0006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.linearfield
struct Holder { o: own<u64> }
fn main() -> u64
effects []
{
0
}
@@ -0,0 +1,12 @@
// Allocation without the effect: the verifier's E3101 (with suggested_effects).
// expect: reject E3101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.missingeffect
fn main(heap: cap<mem.alloc>) -> u64
effects []
{
let x = own.new(1u64, heap) or trap;
own.take(move x)
}
@@ -0,0 +1,12 @@
// A named linear value passed without `move`: the frontend asks for it (hint "move x").
// expect: reject E7003
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.missingmove
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(1u64, heap) or trap;
own.take(x)
}
@@ -0,0 +1,13 @@
// An outcome match handles every outcome of the operation.
// expect: reject E7004
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.missingoutcome
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
match own.new(1u64, heap) {
ok(x) => own.take(move x),
}
}
@@ -0,0 +1,12 @@
// `move` applies only to linear values.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.movecopy
fn main() -> u64
effects []
{
let a = 3u64;
move a
}
@@ -0,0 +1,14 @@
// region.new takes an explicit region borrow binding; the frontend creates no hidden one.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.regionvalue
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let r = region.create(heap) or trap;
let item = region.new(r, 1u64) or trap;
region.destroy(move r);
0
}
@@ -0,0 +1,20 @@
// region.reset while an allocation borrow is live: the frontend ends nothing early; the verifier reports E2104.
// expect: reject E2104
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.resetlive
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let r = region.create(heap) or trap;
var v: u64 = 0;
{
ref arena = r;
let item = region.new(arena, 1u64) or trap;
region.reset(r);
v = *item;
}
region.destroy(move r);
v
}
@@ -0,0 +1,12 @@
// A fallible operation used as a plain value: handle it with match or `or trap`.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.unhandled
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(1u64, heap);
0
}
@@ -0,0 +1,25 @@
// Correct source, but the owner is borrowed after its move: the verifier reports E2001.
// expect: reject E2001
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.useaftermove
fn sink(o: own<u64>) -> void
effects []
{
own.free(move o);
}
fn read(c: ref<u64>) -> u64
effects []
{
*c
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let x = own.new(1u64, heap) or trap;
sink(move x);
read(ref x)
}