Phase 6A: .aji layer 6 (intrinsics, resources, narrowing, unsafe operations)

- intrinsics from the registry as plain calls: fallible ones are outcome
  matches or `or trap` (E7006 otherwise), infallible ones plain calls
- resource operands by name, borrowed mut for the one operation and ended
  on every edge; a mut binding/parameter passes as is; `mut f` is E7006
- closes consume with `move` (E7003); no inserted closes (E3002/E3001)
- data operands explicit (ref/mut/byte string, E7005 otherwise)
- file<…>, stream, listener types; cap.narrow.prefix with cap_error edges
- ref/mut unchecked s[i] (also as a binding) and assume(c) under
  effects [unsafe]; boundary left to the verifier (E6001)
- trusted is reserved and rejected (E7006)
- parameter names preserved; generated names avoid them (normative)
- parser: >> closes two type arguments
- conformance: `equivalent:` compares the run record with a reference
  AIR program (hello, file_copy, tcp_echo, narrow ok/not_subset/invalid,
  random)
- spec 15, grammar, quick reference (io_error match fixed), plan, examples
This commit is contained in:
dev committed 2026-10-05 12:16:54 +03:00
1 parent bdcf871e5d
commit c18fb7acc1
39 files changed
+1309 -69

No files matched your search

+3 -2
View File
@@ -111,18 +111,19 @@ let n = net.recv(conn, mut buf) or trap; // any non-ok outcome traps
- Arms are named after the outcomes and the `match` must cover all of them (`E7004`).
- `or trap` is the only shorthand: it takes the `ok` value and traps on anything else.
- Matching an `err(e)` of type `io_error`: `match e { not_found => …, _ => … }`.
- `err(e)` binds a real `io_error`. Match it like any enum, every variant and no `_`: `match e { io_error::not_found => …, io_error::permission_denied => …, … }`, or just `trap`.
- Closing consumes the resource on **both** outcomes.
## 6. Authority, allocation, I/O
Capabilities are only ever received (as `main` parameters, passed down as arguments) or narrowed. They are copyable.
Capabilities are only ever received (as `main` parameters, passed down as arguments) or narrowed. They are copyable. A capability is needed only to acquire: the file or stream you get back carries the authority, so `fs.read(f, mut buf)` takes no capability. Pass a resource **by name** (the call borrows it); pass data with explicit `ref`/`mut`. Paths are byte strings: `b"/in/data.txt"`.
| Kind (`cap<K>`) | Effect | Operations (all fallible unless noted) |
|---|---|---|
| `io.read` / `io.write` | same | `io.stdin_read(c, mut buf) → ok(n)`; `io.stdout_write(c, ref bytes)`, `io.stderr_write(c, ref bytes)` |
| `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)` |
| narrowing | — | `cap.narrow.prefix(c, b"/data/logs") → ok(c2) / err(e: cap_error)` (`fs.read`, `fs.write`) |
| `clock.read`, `random.read` | same | `clock.monotonic(c)` (infallible, `u64`); `random.fill(c, mut buf)` (infallible) |
| `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)` |
+1 -1
View File
@@ -42,7 +42,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| 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 | 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 |
| 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 |
| 8 | `lock`, `select`, cancellation, shields | todo |
+3 -2
View File
@@ -24,8 +24,7 @@ variant = ident [ "(" type { "," type } ")" ] ;
fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
"effects" "[" [ path { "," path } ] "]"
[ "trusted" string ]
block ;
block ; (* `trusted` is reserved and rejected, E7006 *)
param = ident ":" type ;
type = int_type | "bool" | "void" | "never" | ident
@@ -33,6 +32,7 @@ type = int_type | "bool" | "void" | "never" | ident
| wrapper "<" type ">"
| "cap" "<" path ">"
| "file" "<" ( "read" | "write" | "append" ) ">" ;
(* `>>` closes two type arguments: mut<file<write>> *)
wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array"
| "task" | "sender" | "receiver" | "mutex" ;
int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
@@ -45,6 +45,7 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
statement = "let" binding [ ":" type ] "=" expr ";"
| "var" ident ":" type "=" ( expr | "zero" ) ";"
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" place ";" (* borrow binding *)
| place "=" expr ";"
| "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";"
| expr ";"
+20 -5
View File
@@ -60,8 +60,13 @@ effects [io.read, io.write]
- A file holds one module: `module <dotted.path>`, then type and function declarations in any order.
- `//` starts a line comment.
- Function `f` lowers to `@f`; type `T` to `@T`.
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then optionally `trusted "<obligation>"` (spec 13 §6), then the body block.
- **The entry point** is `main`. Its parameters are capabilities bound by name (spec 05 §10.2).
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block.
- **Parameter names are preserved.** A parameter `p` lowers to `%p`. Names the compiler generates are chosen so that they never equal a parameter name of the function. The names of `@main`'s parameters are part of the instantiation contract.
- **The entry point** is `main`. Its parameters are capabilities `cap<K>`, bound by name (spec 05 §10.2). Startup values of other types (command-line arguments, for example) are not part of `.aji` 0.1.
- **Grants are not source semantics.** A program only declares `main`'s capability parameters. Granting them is instantiation after the module is lowered and verified (`aji run --grant …`, `aji.toml`, spec 12 §1). A missing grant is `not_instantiated` at run time, never a source or verifier diagnostic.
- **One source for every profile.** The frontend does not know the execution profile. The same `.aji` runs in the deterministic and the hosted profile (spec 11).
- **`trusted` is not available.** It is the boundary of runtime, std and toolchain modules (spec 13 §6.3), not something a program declares about its own code. The word is reserved and a `trusted` clause is `E7006`.
- **Unsafe operations** are the format-0 ones and nothing else: `ref unchecked s[i]` / `mut unchecked s[i]` (also bound: `ref unchecked e = s[i];`) lower to `borrow.index.unchecked`, and `assume(c)` to `assume`. Their boundary is the AIR one: the function declares `effects [unsafe]`, which propagates to its callers. Outside it the verifier reports `E6001`. There is no `unsafe { … }` block, because AIR has no block-level unsafe boundary. There is no FFI, raw address or syscall surface in format 0, so none exists in source.
## 3. Types
@@ -289,7 +294,7 @@ Arms bind the send values not sent on their edge, in the order of first appearan
Step 4 happens at **every normal exit** from the block: fall-through, and every `return`, `break` and `continue` that leaves it. The `cancelled { … }` block is the lock's cancelled edge. On a trap nothing is unlocked: the execution terminates (spec 04 §33.2). The guard is never a source value. The critical-section rule (spec 04 §41) applies to the block's contents.
**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:
**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 (§8):
- `file<…>`, `stream`, `listener`;
- `sender<T>`, `receiver<T>`;
@@ -306,9 +311,19 @@ Allocation and resource operations keep their AIR names and operand order:
- `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)`: `ok(c2)` binds a `cap<K>`, `err(e)` a `cap_error`; `cap.narrow.prefix(c, path)` (layer 6);
- `cap.narrow.budget(c, n)` and `cap.narrow.prefix(c, path)`: `ok(c2)` binds a `cap<K>`, `err(e)` a `cap_error` (`invalid_restriction`, `not_subset`, `unsupported_restriction`). Narrowing is always fallible and never yields an empty capability;
- 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")`.
- intrinsics under their registered names and operand order (`reference/intrinsics.md`), as plain calls: `io.stdout_write(out, ref buf[0..n])`, `fs.open_read(c, b"/in/data.txt")`, `fs.close(move f)`, `net.listen(c, b"127.0.0.1:7")`. There are no methods, no `File.open()` and no implicit I/O.
**Intrinsics.**
- **Failure.** A fallible intrinsic is an outcome match (`ok(results…)`, `err(e)` with `e: io_error`) or `op(…) or trap` (§6). Used as a plain value or statement it is `E7006`. An infallible one (`clock.monotonic`, `random.fill`) is a plain call; matching it is `E7006`.
- **Authority.** A capability is needed only to acquire authority: `fs.open_read(c, path)` returns a `file<read>` that carries it, and `fs.read(f, mut buf)` takes no capability. The capability kind is checked by the verifier (`E3201`), and the effect too (`E3101`).
- **Resource operands.** An operand the registry marks as borrowed is the resource **by name**. The frontend borrows it `mut` for that one operation and ends the borrow on every outcome edge. A `mut` borrow binding or parameter of the resource (`f: mut<file<write>>`) is passed as is. Writing `mut f` there is `E7006` (one spelling); a resource of the wrong type or mode is `E7005`.
- **Consumed operands** (`fs.close`, `net.close_stream`, `net.close_listener`) take `move f` (`E7003` without it). The frontend never inserts a close: an unclosed resource is the verifier's `E3002`, use after close `E3001`.
- **Data operands** are always written: `ref bytes` / `ref buf[a..b]` / a byte string for read bytes, `mut buf` / `mut buf[a..b]` for a buffer the operation fills (`E7005` otherwise).
- **Paths and addresses** are byte strings or borrowed bytes, passed as they are. There is no `Path` type and the frontend does not normalize. Whether a path is absolute, free of `.`/`..` and inside the capability's scope is decided by the intrinsic at run time (`invalid_input`, `permission_denied`; for narrowing, `invalid_restriction`, `not_subset`).
- **Source map.** The intrinsic's terminator maps to the call. The borrow ends on each edge map to the call, and each arm's code to its arm. A runtime trap under `or trap` points at the call (`source_location` in the run record). A verifier diagnostic on an operand points at that operand's construct.
**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:
+19 -25
View File
@@ -1,32 +1,26 @@
module examples.file_copy;
// Run: aji run --grant fs_read=fs.read:/in --grant fs_write=fs.write:/out \
// --vfs '/in/data.txt=some text' examples/file_copy.aji
module examples.file_copy
fn copy(
fs_read: cap<fs.read>,
fs_write: cap<fs.write>,
src: slice<u8>,
dst: slice<u8>,
alloc: cap<mem.alloc>
) -> Result<void, IoError>
effects [mem.alloc, fs.read, fs.write]
fn copy(input: mut<file<read>>, output: mut<file<write>>) -> void
effects [fs.read, fs.write]
{
let input = fs.open_read(fs_read, src)?;
defer fs.close(move input);
let output = fs.open_write(fs_write, dst)?;
defer fs.close(move output);
var region = region.create(alloc, limit = 64 KiB)?;
defer region.destroy(move region);
let buffer = region.alloc_zeroed_array<u8>(mut region, 64 KiB)?;
while true {
let n = fs.read(ref input, buffer)?;
var buf: [u8; 64] = zero;
loop {
let n = fs.read(input, mut buf) or trap;
if n == 0 {
break;
}
fs.write_all(ref output, slice.prefix(buffer, n))?;
fs.write_all(output, ref buf[0..n]) or trap;
}
return Ok();
}
fn main(fs_read: cap<fs.read>, fs_write: cap<fs.write>) -> void
effects [fs.read, fs.write]
{
let input = fs.open_read(fs_read, b"/in/data.txt") or trap;
let output = fs.create(fs_write, b"/out/copy.txt") or trap;
copy(mut input, mut output);
fs.close(move input) or trap;
fs.close(move output) or trap;
}
+4 -6
View File
@@ -1,10 +1,8 @@
module examples.hello;
// Run: aji run --grant stdout=io.write examples/hello.aji
module examples.hello
fn main(
stdout: cap<io.write>
) -> Result<void, IoError>
fn main(stdout: cap<io.write>) -> void
effects [io.write]
{
io.stdout_write(stdout, "hello from aji\n")?;
return Ok();
io.stdout_write(stdout, b"hello from aji\n") or trap;
}
+1 -1
View File
@@ -144,7 +144,7 @@ pub const Stmt = struct {
@"var": struct { name: []const u8, ty: Type, init: ?Expr },
assign: struct { place: Expr, e: Expr },
/// `ref r = place;` / `mut r = place;`: a borrow bound for the rest of the block.
borrow: struct { mutable: bool, name: []const u8, place: Expr },
borrow: struct { mutable: bool, unchecked: bool = false, name: []const u8, place: Expr },
@"break",
@"continue",
@"return": ?Expr,
+179 -15
View File
@@ -17,7 +17,9 @@
//! 3–4. addressable values (frame storage chosen by lowering), lexical
//! borrows, places, arrays, slices, byte strings;
//! 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
//! narrowing, unsafe operations.
const std = @import("std");
const ast = @import("ast.zig");
@@ -48,12 +50,14 @@ pub const Ty = union(enum) {
cap: []const u8,
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
builtin: authority.Builtin,
/// `file<read|write|append>`, `stream`, `listener`.
resource: authority.Resource,
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;
return t == .own or t == .own_array or t == .region or t == .resource;
}
fn eql(a: Ty, b: Ty) bool {
@@ -65,6 +69,7 @@ pub const Ty = union(enum) {
.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,
.resource => |r| r == b.resource,
else => true,
};
}
@@ -220,6 +225,10 @@ const Lowerer = struct {
bindings: std.ArrayList(Binding) = .empty,
loops: std.ArrayList(Loop) = .empty,
counter: u32 = 0,
/// Features found while lowering rather than by scanning the text.
uses: std.EnumSet(UseFeature) = .empty,
/// Set while lowering a `ref unchecked …` place: its index is unchecked.
unchecked: bool = false,
/// The current function's parameter names, which generated names avoid.
params: []const ast.Param = &.{},
ret: Ty = .void,
@@ -259,7 +268,14 @@ const Lowerer = struct {
.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),
.builtin => |b| blk: {
if (b == .io_error) l.uses.insert(.resources);
break :blk @tagName(b);
},
.resource => |r| blk: {
l.uses.insert(.resources);
break :blk r.text();
},
};
}
@@ -337,6 +353,8 @@ const Lowerer = struct {
/// The features the lowered AIR uses directly; the header is their
/// dependency closure (spec 15 §9). `effects` is always declared.
const UseFeature = enum { capabilities, resources, unsafe };
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
var texts: std.ArrayList([]const u8) = .empty;
for (type_lines) |t| try texts.append(l.arena, t.text);
@@ -366,6 +384,8 @@ const Lowerer = struct {
} else false;
if (used) try roots.append(l.arena, r[0]);
}
var it = l.uses.iterator();
while (it.next()) |u| try roots.append(l.arena, @tagName(u));
return roots.items;
}
@@ -418,8 +438,8 @@ const Lowerer = struct {
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
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)");
if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream };
if (std.mem.eql(u8, n, "listener")) return .{ .resource = .listener };
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
@@ -440,7 +460,10 @@ const Lowerer = struct {
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)"),
.file => |m| {
const r: authority.Resource = if (std.mem.eql(u8, m, "read")) .file_read else if (std.mem.eql(u8, m, "write")) .file_write else if (std.mem.eql(u8, m, "append")) .file_append else return l.fail("E7002", t.span, "unknown file mode (read, write, append)", &.{.{ .name = "mode", .value = m }});
return .{ .resource = r };
},
}
}
@@ -460,7 +483,10 @@ const Lowerer = struct {
const sig = l.sigs.get(f.name).?;
l.ret = sig.ret;
if (f.from != null) return l.notYet(f.span, "borrow returns (layer 4)");
if (f.trusted != null) return l.notYet(f.span, "trusted functions (layer 5)");
// `trusted` is the boundary of runtime, std and toolchain modules; an
// ordinary program cannot declare its own code trusted (spec 15 §8).
if (f.trusted != null) return l.fail("E7006", f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) l.uses.insert(.unsafe);
var header: std.ArrayList(u8) = .empty;
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name}));
@@ -752,7 +778,7 @@ const Lowerer = struct {
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
const p = try l.placeBorrow(x.place, x.mutable, true, s.span);
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
if (p.ends.len == 0) {
// Borrowing a borrow binding: a reborrow, ended at scope end.
const rb = try l.def(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), s.span);
@@ -1205,6 +1231,19 @@ const Lowerer = struct {
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
return .{ .name = "", .ty = .void };
}
if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops });
const v: Value = if (x.results.len == 0) blk: {
try l.emit(text, e.span);
break :blk .{ .name = "", .ty = .void };
} else try l.def("r", resultTy(x.results[0]), text, e.span);
try l.endNow(temps.items, e.span);
return v;
}
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"))
@@ -1218,6 +1257,14 @@ const Lowerer = struct {
try l.emit(try l.fmt("assert %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
if (std.mem.eql(u8, name, "assume")) {
if (args.len != 1) return l.fail("E7005", e.span, "`assume` takes one boolean", &.{});
const v = try l.expr(args[0], .bool);
try l.checkTy(args[0].span, v.ty, .bool);
l.uses.insert(.unsafe);
try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
const sig = l.sigs.get(name) orelse return l.unknown(callee.span, name);
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var arg_names: std.ArrayList(u8) = .empty;
@@ -1546,7 +1593,7 @@ const Lowerer = struct {
fn argument(l: *Lowerer, a: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value {
switch (a.kind) {
.borrow => |x| {
const p = try l.placeBorrow(x.place.*, x.mutable, true, a.span);
const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, a.span);
if (p.ends.len == 0) {
const rb = try l.def("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), a.span);
try temps.append(l.arena, rb.name);
@@ -1575,6 +1622,17 @@ const Lowerer = struct {
return l.expr(e, want);
}
/// `ref unchecked s[i]`: `borrow.index.unchecked` (spec 13 §6). Only an
/// element place can be unchecked; the boundary (`effects [unsafe]`) is
/// the verifier's (`E6001`).
fn uncheckedPlace(l: *Lowerer, place: ast.Expr, mutable: bool, unchecked: bool, span: Span) Error!Placed {
if (!unchecked) return l.placeBorrow(place, mutable, true, span);
if (place.kind != .index or place.kind.index.hi != null) return l.fail("E7006", place.span, "`unchecked` applies to one element `s[i]`", &.{});
l.unchecked = true;
defer l.unchecked = false;
return l.placeBorrow(place, mutable, true, span);
}
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
var x = e;
while (true) switch (x.kind) {
@@ -1619,6 +1677,7 @@ const Lowerer = struct {
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
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 }});
@@ -1650,7 +1709,10 @@ const Lowerer = struct {
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try l.placeRaw(x.e.*, mutable, span);
l.unchecked = outer_unchecked;
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }});
if (x.hi) |hi| {
@@ -1669,12 +1731,17 @@ const Lowerer = struct {
const sub_ = try l.def("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
const unchecked = l.unchecked;
l.unchecked = false;
const i = try l.expr(x.lo.*, .{ .int = "usize" });
try l.checkTy(x.lo.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true;
} else false;
const v = try l.def("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ if (proven) "borrow.index.proven" else "borrow.index", base.v.name, i.name }), span);
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.def("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.fail("E7006", place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
@@ -1858,15 +1925,82 @@ const Lowerer = struct {
/// 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 };
/// `temps`: borrows made for the operation, ended at the start of every
/// outcome block.
const Fallible = struct { text: []const u8, outcomes: []const Outcome, temps: []const []const u8 = &.{} };
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" };
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
.u64 => .{ .int = "u64" },
.resource => |x| .{ .resource = x },
};
}
/// Operands of an intrinsic in registry order (`reference/intrinsics.md`).
/// A capability is passed plainly; a resource operand that is borrowed
/// is named and borrowed for the operation; a consumed one is `move`d;
/// data borrows are written (`ref`/`mut`, or a byte string).
fn intrinsicOperands(l: *Lowerer, e: ast.Expr, x: authority.Intrinsic, args: []const ast.Expr, temps: *std.ArrayList([]const u8)) Error![]const u8 {
if (args.len != x.operands.len) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{x.operands.len}) } });
var text: std.ArrayList(u8) = .empty;
for (x.operands, args, 0..) |o, a, i| {
const v: Value = switch (o) {
.cap => |k| try l.expectCap(a, k),
.bytes, .buffer => blk: {
const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" });
if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{});
const v = try l.argument(a, want, temps);
if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.tyText(want) }, .{ .name = "found", .value = l.tyText(v.ty) } });
break :blk v;
},
.borrowed => |rs| try l.resourceOperand(a, rs, temps),
.consumed => |rs| blk: {
const v = try l.consuming(a, null);
if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null)
return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.tyText(v.ty) } });
break :blk v;
},
};
try text.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return text.items;
}
/// A resource operand the operation borrows: the resource by name
/// (borrowed `mut` for the operation) or a `mut` borrow binding of one.
fn resourceOperand(l: *Lowerer, a: ast.Expr, rs: []const authority.Resource, temps: *std.ArrayList([]const u8)) Error!Value {
const expected = try l.resourceList(rs);
if (a.kind == .borrow) return l.fail("E7006", a.span, "a resource operand is written by name; the operation borrows it", &.{.{ .name = "expected", .value = expected }});
if (a.kind != .name) return l.fail("E7005", a.span, "a resource is expected here, by name", &.{.{ .name = "expected", .value = expected }});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const r: ?authority.Resource = switch (b.ty) {
.resource => |r| r,
.mut => |in| if (in.* == .resource) in.resource else null,
else => null,
};
if (r == null or std.mem.indexOfScalar(authority.Resource, rs, r.?) == null)
return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = l.tyText(b.ty) } });
if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty };
const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span);
try temps.append(l.arena, v.name);
return v;
}
fn resourceList(l: *Lowerer, rs: []const authority.Resource) Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
for (rs, 0..) |r, i| try out.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }));
return out.items;
}
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) } });
@@ -1928,6 +2062,30 @@ const Lowerer = struct {
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 (authority.intrinsicIndex(path)) |ix| {
const x = authority.intrinsics[ix];
if (!x.fallible) return l.fail("E7006", e.span, "this intrinsic cannot fail: call it plainly", &.{.{ .name = "operation", .value = x.name }});
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const ok = try l.arena.alloc(Ty, x.results.len);
for (x.results, ok) |r, *t| t.* = resultTy(r);
return .{
.text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }),
.outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "err", .params = &.{.{ .builtin = .io_error }} } }),
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "cap.narrow.prefix")) {
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) }});
var temps: std.ArrayList([]const u8) = .empty;
const bytes = try l.wrap(.slice, .{ .int = "u8" });
const p = try l.argument(args[1], bytes, &temps);
if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.tyText(p.ty) }});
return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items };
}
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);
@@ -1957,6 +2115,11 @@ const Lowerer = struct {
try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name }));
}
try l.term(text.items, span);
// The operation's temporary borrows end on every edge.
for (blocks) |b| {
l.cur = b;
try l.endNow(f.temps, span);
}
return blocks;
}
@@ -2095,13 +2258,14 @@ fn elemOf(t: Ty) ?Ty {
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
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",
"slice.copy", "own.new", "own.array", "own.take", "own.free",
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget", "cap.narrow.prefix",
};
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;
if (authority.intrinsicIndex(text)) |i| return authority.intrinsics[i].name;
return null;
}
+30 -11
View File
@@ -16,7 +16,7 @@ pub const Result = union(enum) { ok: ast.Module, err: Failure };
pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result {
const tokens = try lex.tokenize(arena, src);
var p: Parser = .{ .arena = arena, .tokens = tokens };
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens) };
const m = p.module() catch |e| switch (e) {
error.Syntax => return .{ .err = p.failure.? },
error.OutOfMemory => return error.OutOfMemory,
@@ -28,7 +28,7 @@ const Error = error{ Syntax, OutOfMemory };
const Parser = struct {
arena: Allocator,
tokens: []const Token,
tokens: []Token,
pos: usize = 0,
failure: ?Failure = null,
/// Struct literals are not allowed where a `{` starts a block (conditions).
@@ -63,6 +63,21 @@ const Parser = struct {
return p.next();
}
/// The `>` closing a type argument. `>>` closes two (`mut<file<write>>`):
/// the first half is taken and the second stays as the next token.
fn closeAngle(p: *Parser) Error!void {
const t = p.peek();
if (t.tag == .shr) {
var rest = t;
rest.tag = .gt;
rest.text = t.text[1..];
rest.pos.col += 1;
p.tokens[p.pos] = rest;
return;
}
_ = try p.expect(.gt, "`>`");
}
fn isWord(t: Token, w: []const u8) bool {
return t.tag == .ident and std.mem.eql(u8, t.text, w);
}
@@ -197,9 +212,11 @@ const Parser = struct {
_ = try p.expect(.r_bracket, "`]`");
var trusted: ?[]const u8 = null;
if (p.atWord("trusted")) {
_ = p.next();
const t = try p.expect(.bytes, "an obligation string b\"…\"");
trusted = (try lex.decodeBytes(p.arena, t.text)) orelse return p.fail(t, "a valid string");
// Reserved: lowering rejects it with E7006 (spec 15 §8), so the
// obligation text, in whatever form, is skipped up to the body.
const t = p.next();
while (p.peek().tag != .l_brace and p.peek().tag != .eof) _ = p.next();
trusted = t.text;
}
const body = try p.block();
return .{ .name = name, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body };
@@ -225,16 +242,16 @@ const Parser = struct {
_ = p.next();
if (std.mem.eql(u8, t.text, "cap")) {
const k = try p.path();
_ = try p.expect(.gt, "`>`");
try p.closeAngle();
return .{ .span = p.span(start), .kind = .{ .cap = k } };
}
if (std.mem.eql(u8, t.text, "file")) {
const m = try p.ident("`read`, `write` or `append`");
_ = try p.expect(.gt, "`>`");
try p.closeAngle();
return .{ .span = p.span(start), .kind = .{ .file = m } };
}
const inner = try p.typeExpr();
_ = try p.expect(.gt, "`>`");
try p.closeAngle();
return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = t.text, .inner = try p.box(ast.Type, inner) } } };
}
@@ -279,13 +296,15 @@ const Parser = struct {
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e } } };
}
if ((isWord(t, "ref") or isWord(t, "mut")) and p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) {
const unchecked_borrow = isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq;
if ((isWord(t, "ref") or isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) {
_ = p.next();
if (unchecked_borrow) _ = p.next();
const name = try p.ident("a name for the borrow");
_ = try p.expect(.eq, "`=`");
const place = try p.expr();
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .name = name, .place = place } } };
return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .unchecked = unchecked_borrow, .name = name, .place = place } } };
}
if (isWord(t, "var")) {
_ = p.next();
@@ -608,7 +627,7 @@ const Parser = struct {
if (std.mem.eql(u8, name, "make") and p.peek().tag == .lt and e.kind.field.e.kind == .name and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) {
_ = p.next();
const ty = try p.typeExpr();
_ = try p.expect(.gt, "`>`");
try p.closeAngle();
const args = try p.callArgs();
const callee = try p.box(ast.Expr, e);
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } };
+1
View File
@@ -31,6 +31,7 @@ Every test starts with a block of `;` lines. Keys:
| `stdout` / `stderr` | no | expected captured output (same escapes) |
| `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 |
| `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 |
| `phase` | yes | implementation phase number |
| `spec` | yes | spec section that justifies the expectation |
@@ -0,0 +1,18 @@
// stdin is read into a buffer and the part read is echoed to stdout.
// expect: run
// grant: input=io.read
// grant: out=io.write
// stdin: echo me
// result: null
// stdout: echo me
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.echostdin
fn main(input: cap<io.read>, out: cap<io.write>) -> void
effects [io.read, io.write]
{
var buf: [u8; 16] = zero;
let n = io.stdin_read(input, mut buf) or trap;
io.stdout_write(out, ref buf[0..n]) or trap;
}
@@ -0,0 +1,28 @@
// Copy /in/data.txt to /out/copy.txt through scoped capabilities; the files are closed explicitly.
// expect: run
// grant: src=fs.read:/in
// grant: dst=fs.write:/out
// vfs: /in/data.txt=Aji copies files.\n
// result: null
// file: /out/copy.txt=Aji copies files.\n
// equivalent: phase2/run/file_copy.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.filecopy
fn main(src: cap<fs.read>, dst: cap<fs.write>) -> void
effects [fs.read, fs.write]
{
let input = fs.open_read(src, b"/in/data.txt") or trap;
let output = fs.create(dst, b"/out/copy.txt") or trap;
var buf: [u8; 4] = zero;
loop {
let n = fs.read(input, mut buf) or trap;
if n == 0 {
break;
}
fs.write_all(output, ref buf[0..n]) or trap;
}
fs.close(move input) or trap;
fs.close(move output) or trap;
}
@@ -0,0 +1,215 @@
module demo.filecopy
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%src: cap<fs.read>, %dst: cap<fs.write>) -> void
effects [fs.read, fs.write]
entry:
%bytes_1 = local.alloc array<u8, 12>
%bytes_45 = local.alloc array<u8, 13>
%buf_92 = local.alloc array<u8, 4>
local.zero %bytes_1
%w_2 = borrow.mut %bytes_1
%i_3 = const.usize 0
%c_4 = const.u8 47
%e_5 = borrow.index %w_2, %i_3
store %e_5, %c_4
borrow.end %e_5
%i_6 = const.usize 1
%c_7 = const.u8 105
%e_8 = borrow.index %w_2, %i_6
store %e_8, %c_7
borrow.end %e_8
%i_9 = const.usize 2
%c_10 = const.u8 110
%e_11 = borrow.index %w_2, %i_9
store %e_11, %c_10
borrow.end %e_11
%i_12 = const.usize 3
%c_13 = const.u8 47
%e_14 = borrow.index %w_2, %i_12
store %e_14, %c_13
borrow.end %e_14
%i_15 = const.usize 4
%c_16 = const.u8 100
%e_17 = borrow.index %w_2, %i_15
store %e_17, %c_16
borrow.end %e_17
%i_18 = const.usize 5
%c_19 = const.u8 97
%e_20 = borrow.index %w_2, %i_18
store %e_20, %c_19
borrow.end %e_20
%i_21 = const.usize 6
%c_22 = const.u8 116
%e_23 = borrow.index %w_2, %i_21
store %e_23, %c_22
borrow.end %e_23
%i_24 = const.usize 7
%c_25 = const.u8 97
%e_26 = borrow.index %w_2, %i_24
store %e_26, %c_25
borrow.end %e_26
%i_27 = const.usize 8
%c_28 = const.u8 46
%e_29 = borrow.index %w_2, %i_27
store %e_29, %c_28
borrow.end %e_29
%i_30 = const.usize 9
%c_31 = const.u8 116
%e_32 = borrow.index %w_2, %i_30
store %e_32, %c_31
borrow.end %e_32
%i_33 = const.usize 10
%c_34 = const.u8 120
%e_35 = borrow.index %w_2, %i_33
store %e_35, %c_34
borrow.end %e_35
%i_36 = const.usize 11
%c_37 = const.u8 116
%e_38 = borrow.index %w_2, %i_36
store %e_38, %c_37
borrow.end %e_38
borrow.end %w_2
%b_39 = borrow.ref %bytes_1
%s_40 = slice.make %b_39
intrinsic fs.open_read(%src, %s_40), ok -> @ok_41, err -> @err_43
ok_41(%ok_42: file<read>):
borrow.end %s_40
borrow.end %b_39
local.zero %bytes_45
%w_46 = borrow.mut %bytes_45
%i_47 = const.usize 0
%c_48 = const.u8 47
%e_49 = borrow.index %w_46, %i_47
store %e_49, %c_48
borrow.end %e_49
%i_50 = const.usize 1
%c_51 = const.u8 111
%e_52 = borrow.index %w_46, %i_50
store %e_52, %c_51
borrow.end %e_52
%i_53 = const.usize 2
%c_54 = const.u8 117
%e_55 = borrow.index %w_46, %i_53
store %e_55, %c_54
borrow.end %e_55
%i_56 = const.usize 3
%c_57 = const.u8 116
%e_58 = borrow.index %w_46, %i_56
store %e_58, %c_57
borrow.end %e_58
%i_59 = const.usize 4
%c_60 = const.u8 47
%e_61 = borrow.index %w_46, %i_59
store %e_61, %c_60
borrow.end %e_61
%i_62 = const.usize 5
%c_63 = const.u8 99
%e_64 = borrow.index %w_46, %i_62
store %e_64, %c_63
borrow.end %e_64
%i_65 = const.usize 6
%c_66 = const.u8 111
%e_67 = borrow.index %w_46, %i_65
store %e_67, %c_66
borrow.end %e_67
%i_68 = const.usize 7
%c_69 = const.u8 112
%e_70 = borrow.index %w_46, %i_68
store %e_70, %c_69
borrow.end %e_70
%i_71 = const.usize 8
%c_72 = const.u8 121
%e_73 = borrow.index %w_46, %i_71
store %e_73, %c_72
borrow.end %e_73
%i_74 = const.usize 9
%c_75 = const.u8 46
%e_76 = borrow.index %w_46, %i_74
store %e_76, %c_75
borrow.end %e_76
%i_77 = const.usize 10
%c_78 = const.u8 116
%e_79 = borrow.index %w_46, %i_77
store %e_79, %c_78
borrow.end %e_79
%i_80 = const.usize 11
%c_81 = const.u8 120
%e_82 = borrow.index %w_46, %i_80
store %e_82, %c_81
borrow.end %e_82
%i_83 = const.usize 12
%c_84 = const.u8 116
%e_85 = borrow.index %w_46, %i_83
store %e_85, %c_84
borrow.end %e_85
borrow.end %w_46
%b_86 = borrow.ref %bytes_45
%s_87 = slice.make %b_86
intrinsic fs.create(%dst, %s_87), ok -> @ok_88, err -> @err_90
err_43(%err_44: io_error):
borrow.end %s_40
borrow.end %b_39
trap
ok_88(%ok_89: file<write>):
borrow.end %s_87
borrow.end %b_86
local.zero %buf_92
br @loop_93()
err_90(%err_91: io_error):
borrow.end %s_87
borrow.end %b_86
trap
loop_93:
%input_95 = borrow.mut %ok_42
%buf_96 = borrow.mut %buf_92
%s_97 = slice.make %buf_96
intrinsic fs.read(%input_95, %s_97), ok -> @ok_98, err -> @err_100
after_94:
intrinsic fs.close(%ok_42), ok -> @ok_116, err -> @err_117
ok_98(%ok_99: usize):
borrow.end %s_97
borrow.end %buf_96
borrow.end %input_95
%c_102 = const.usize 0
%cmp_103 = eq.usize %ok_99, %c_102
cbr %cmp_103, @then_104(), @else_105()
err_100(%err_101: io_error):
borrow.end %s_97
borrow.end %buf_96
borrow.end %input_95
trap
then_104:
br @after_94()
else_105:
br @endif_106()
endif_106:
%output_107 = borrow.mut %ok_89
%buf_108 = borrow.ref %buf_92
%s_109 = slice.make %buf_108
%c_110 = const.usize 0
%len_111 = sub.checked.usize %ok_99, %c_110
%s_112 = slice.sub %s_109, %c_110, %len_111
intrinsic fs.write_all(%output_107, %s_112), ok -> @ok_113, err -> @err_114
ok_113:
borrow.end %s_112
borrow.end %s_109
borrow.end %buf_108
borrow.end %output_107
br @loop_93()
err_114(%err_115: io_error):
borrow.end %s_112
borrow.end %s_109
borrow.end %buf_108
borrow.end %output_107
trap
ok_116:
intrinsic fs.close(%ok_89), ok -> @ok_119, err -> @err_120
err_117(%err_118: io_error):
trap
ok_119:
ret
err_120(%err_121: io_error):
trap
+15
View File
@@ -0,0 +1,15 @@
// Hello world in source; its run equals the reference AIR program's.
// expect: run
// grant: out=io.write
// result: null
// stdout: hello, aji\n
// equivalent: phase2/run/hello.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.hello
fn main(out: cap<io.write>) -> void
effects [io.write]
{
io.stdout_write(out, b"hello, aji\n") or trap;
}
@@ -0,0 +1,78 @@
module demo.hello
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%out: cap<io.write>) -> void
effects [io.write]
entry:
%bytes_1 = local.alloc array<u8, 11>
local.zero %bytes_1
%w_2 = borrow.mut %bytes_1
%i_3 = const.usize 0
%c_4 = const.u8 104
%e_5 = borrow.index %w_2, %i_3
store %e_5, %c_4
borrow.end %e_5
%i_6 = const.usize 1
%c_7 = const.u8 101
%e_8 = borrow.index %w_2, %i_6
store %e_8, %c_7
borrow.end %e_8
%i_9 = const.usize 2
%c_10 = const.u8 108
%e_11 = borrow.index %w_2, %i_9
store %e_11, %c_10
borrow.end %e_11
%i_12 = const.usize 3
%c_13 = const.u8 108
%e_14 = borrow.index %w_2, %i_12
store %e_14, %c_13
borrow.end %e_14
%i_15 = const.usize 4
%c_16 = const.u8 111
%e_17 = borrow.index %w_2, %i_15
store %e_17, %c_16
borrow.end %e_17
%i_18 = const.usize 5
%c_19 = const.u8 44
%e_20 = borrow.index %w_2, %i_18
store %e_20, %c_19
borrow.end %e_20
%i_21 = const.usize 6
%c_22 = const.u8 32
%e_23 = borrow.index %w_2, %i_21
store %e_23, %c_22
borrow.end %e_23
%i_24 = const.usize 7
%c_25 = const.u8 97
%e_26 = borrow.index %w_2, %i_24
store %e_26, %c_25
borrow.end %e_26
%i_27 = const.usize 8
%c_28 = const.u8 106
%e_29 = borrow.index %w_2, %i_27
store %e_29, %c_28
borrow.end %e_29
%i_30 = const.usize 9
%c_31 = const.u8 105
%e_32 = borrow.index %w_2, %i_30
store %e_32, %c_31
borrow.end %e_32
%i_33 = const.usize 10
%c_34 = const.u8 10
%e_35 = borrow.index %w_2, %i_33
store %e_35, %c_34
borrow.end %e_35
borrow.end %w_2
%b_36 = borrow.ref %bytes_1
%s_37 = slice.make %b_36
intrinsic io.stdout_write(%out, %s_37), ok -> @ok_38, err -> @err_39
ok_38:
borrow.end %s_37
borrow.end %b_36
ret
err_39(%err_40: io_error):
borrow.end %s_37
borrow.end %b_36
trap
@@ -0,0 +1,32 @@
// A missing file: err(e) binds the io_error, matched like any closed enum.
// expect: run
// grant: src=fs.read:/in
// result: 1
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.ioerror
fn main(src: cap<fs.read>) -> u8
effects [fs.read]
{
match fs.open_read(src, b"/in/missing.txt") {
ok(f) => {
fs.close(move f) or trap;
0
}
err(e) => match e {
io_error::not_found => 1,
io_error::permission_denied => 2,
io_error::already_exists => 3,
io_error::invalid_input => 4,
io_error::no_space => 5,
io_error::broken_pipe => 6,
io_error::connection_refused => 7,
io_error::connection_reset => 8,
io_error::address_in_use => 9,
io_error::address_unavailable => 10,
io_error::timed_out => 11,
io_error::other => 12,
},
}
}
@@ -0,0 +1,12 @@
// Grants are not part of the source: a missing one is not_instantiated at run time, not a compile error.
// expect: run
// not_instantiated: missing_capability
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.missinggrant
fn main(out: cap<io.write>) -> void
effects [io.write]
{
io.stdout_write(out, b"x") or trap;
}
@@ -0,0 +1,27 @@
// cap.narrow.prefix to /data/../etc under scope /data: the err edge carries the cap_error.
// expect: run
// grant: fs=fs.read:/data
// result: 1
// equivalent: phase2/run/narrow_invalid.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.narrowinvalid
fn classify(fs: cap<fs.read>, path: slice<u8>) -> u8
effects []
{
match cap.narrow.prefix(fs, path) {
ok(c) => 0,
err(e) => match e {
cap_error::invalid_restriction => 1,
cap_error::not_subset => 2,
cap_error::unsupported_restriction => 3,
},
}
}
fn main(fs: cap<fs.read>) -> u8
effects []
{
classify(fs, b"/data/../etc")
}
@@ -0,0 +1,27 @@
// cap.narrow.prefix to /etc under scope /data: the err edge carries the cap_error.
// expect: run
// grant: fs=fs.read:/data
// result: 2
// equivalent: phase2/run/narrow_not_subset.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.narrownot_subset
fn classify(fs: cap<fs.read>, path: slice<u8>) -> u8
effects []
{
match cap.narrow.prefix(fs, path) {
ok(c) => 0,
err(e) => match e {
cap_error::invalid_restriction => 1,
cap_error::not_subset => 2,
cap_error::unsupported_restriction => 3,
},
}
}
fn main(fs: cap<fs.read>) -> u8
effects []
{
classify(fs, b"/etc")
}
@@ -0,0 +1,21 @@
// cap.narrow.prefix: ok narrows, err binds a cap_error matched exhaustively.
// expect: run
// grant: fs=fs.read:/data
// result: 0
// equivalent: phase2/run/narrow_ok.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.narrowprefix
fn main(fs: cap<fs.read>) -> u8
effects []
{
match cap.narrow.prefix(fs, b"/data/logs") {
ok(logs) => 0,
err(e) => match e {
cap_error::invalid_restriction => 1,
cap_error::not_subset => 2,
cap_error::unsupported_restriction => 3,
},
}
}
@@ -0,0 +1,17 @@
// An infallible intrinsic is a plain call.
// expect: run
// grant: rng=random.read
// seed: 7
// result: [90,118,249,78]
// equivalent: phase2/run/random_seeded.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.random
fn main(rng: cap<random.read>) -> [u8; 4]
effects [random.read]
{
var b: [u8; 4] = zero;
random.fill(rng, mut b);
b
}
@@ -0,0 +1,12 @@
// Closing consumes the resource: a named one must be written `move f`.
// expect: reject E7003
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.closenomove
fn main(src: cap<fs.read>) -> void
effects [fs.read]
{
let f = fs.open_read(src, b"/in/a") or trap;
fs.close(f) or trap;
}
@@ -0,0 +1,12 @@
// Data borrows stay explicit: a buffer is passed as `mut buf`.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.databorrow
fn main(input: cap<io.read>) -> usize
effects [io.read]
{
var buf: [u8; 4] = zero;
io.stdin_read(input, buf) or trap
}
@@ -0,0 +1,14 @@
// An infallible intrinsic has no outcomes to match.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.infalliblematch
fn main(clock: cap<clock.read>) -> u64
effects [clock.read]
{
match clock.monotonic(clock) {
ok(t) => t,
err(e) => 0,
}
}
@@ -0,0 +1,11 @@
// An intrinsic without its effect: the verifier's E3101 names it.
// expect: reject E3101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.ioeffect
fn main(out: cap<io.write>) -> void
effects []
{
io.stdout_write(out, b"x") or trap;
}
@@ -0,0 +1,14 @@
// A resource 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.resourceborrow
fn main(src: cap<fs.read>) -> void
effects [fs.read]
{
let f = fs.open_read(src, b"/in/a") or trap;
var buf: [u8; 4] = zero;
let n = fs.read(mut f, mut buf) or trap;
fs.close(move f) or trap;
}
@@ -0,0 +1,11 @@
// The frontend never inserts a close: an unclosed file is the verifier's leak.
// expect: reject E3002
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.resourceleak
fn main(src: cap<fs.read>) -> void
effects [fs.read]
{
let f = fs.open_read(src, b"/in/a") or trap;
}
@@ -0,0 +1,19 @@
// `trusted` belongs to runtime, std and toolchain modules; a program cannot declare its own code trusted.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.trusted
fn get(s: slice<u64>, i: usize) -> u64
effects []
trusted "callers check the bound"
{
ref unchecked e = s[i];
*e
}
fn main() -> u64
effects []
{
0
}
@@ -0,0 +1,18 @@
// `unchecked` applies to one element, not a range.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.uncheckedrange
fn f(s: slice<u64>) -> u64
effects [unsafe]
{
ref unchecked r = s[0..2];
0
}
fn main() -> u64
effects []
{
0
}
@@ -0,0 +1,11 @@
// A fallible intrinsic is handled with `match` or `or trap`; there is no implicit propagation.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.unhandledio
fn main(out: cap<io.write>) -> void
effects [io.write]
{
io.stdout_write(out, b"x");
}
@@ -0,0 +1,18 @@
// An unsafe operation outside an `unsafe` function: the verifier decides (E6001).
// expect: reject E6001
// phase: 6
// spec: docs/spec/13-contracts-and-unsafe.md
module demo.unsafeboundary
fn get(s: slice<u64>, i: usize) -> u64
effects []
{
ref unchecked e = s[i];
*e
}
fn main() -> u64
effects []
{
0
}
@@ -0,0 +1,14 @@
// A file used after it was closed: the verifier reports it.
// expect: reject E3001
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.useafterclose
fn main(src: cap<fs.read>) -> void
effects [fs.read]
{
let f = fs.open_read(src, b"/in/a") or trap;
fs.close(move f) or trap;
var buf: [u8; 4] = zero;
let n = fs.read(f, mut buf) or trap;
}
@@ -0,0 +1,11 @@
// A capability of the wrong kind: the verifier's E3201.
// expect: reject E3201
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.wrongcap
fn main(out: cap<io.read>) -> void
effects [io.write]
{
io.stdout_write(out, b"x") or trap;
}
@@ -0,0 +1,13 @@
// fs.write_all needs a writable file; a file<read> is rejected at the operand.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.wrongmode
fn main(src: cap<fs.read>) -> void
effects [fs.read, fs.write]
{
let f = fs.open_read(src, b"/in/a") or trap;
fs.write_all(f, b"x") or trap;
fs.close(move f) or trap;
}
@@ -0,0 +1,24 @@
// A function borrows a resource through a mut<file<…>> parameter; the caller lends it with `mut f`.
// expect: run
// grant: dst=fs.write:/out
// result: null
// file: /out/a.txt=ab
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.resourceparam
fn put(f: mut<file<write>>, byte: u8) -> void
effects [fs.write]
{
var one: [u8; 1] = [byte; 1];
fs.write_all(f, ref one) or trap;
}
fn main(dst: cap<fs.write>) -> void
effects [fs.write]
{
let f = fs.create(dst, b"/out/a.txt") or trap;
put(mut f, 97);
put(mut f, 98);
fs.close(move f) or trap;
}
@@ -0,0 +1,27 @@
// TCP echo over the deterministic loopback; streams and the listener are closed explicitly.
// expect: run
// grant: listen=net.listen
// grant: connect=net.connect
// result: [112,105,110,103]
// equivalent: phase2/run/tcp_echo.air
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.tcpecho
fn main(listen: cap<net.listen>, connect: cap<net.connect>) -> [u8; 4]
effects [net.listen, net.connect, net.read, net.write]
{
let l = net.listen(listen, b"127.0.0.1:7") or trap;
let client = net.connect(connect, b"127.0.0.1:7") or trap;
let server = net.accept(l) or trap;
net.send_all(client, b"ping") or trap;
var buf: [u8; 4] = zero;
let n = net.recv(server, mut buf) or trap;
net.send_all(server, ref buf[0..n]) or trap;
var back: [u8; 4] = zero;
let m = net.recv(client, mut back) or trap;
net.close_stream(move server) or trap;
net.close_stream(move client) or trap;
net.close_listener(move l) or trap;
back
}
@@ -0,0 +1,252 @@
module demo.tcpecho
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%listen: cap<net.listen>, %connect: cap<net.connect>) -> array<u8, 4>
effects [net.listen, net.connect, net.read, net.write]
entry:
%bytes_1 = local.alloc array<u8, 11>
%bytes_42 = local.alloc array<u8, 11>
%bytes_89 = local.alloc array<u8, 4>
%buf_108 = local.alloc array<u8, 4>
%back_125 = local.alloc array<u8, 4>
local.zero %bytes_1
%w_2 = borrow.mut %bytes_1
%i_3 = const.usize 0
%c_4 = const.u8 49
%e_5 = borrow.index %w_2, %i_3
store %e_5, %c_4
borrow.end %e_5
%i_6 = const.usize 1
%c_7 = const.u8 50
%e_8 = borrow.index %w_2, %i_6
store %e_8, %c_7
borrow.end %e_8
%i_9 = const.usize 2
%c_10 = const.u8 55
%e_11 = borrow.index %w_2, %i_9
store %e_11, %c_10
borrow.end %e_11
%i_12 = const.usize 3
%c_13 = const.u8 46
%e_14 = borrow.index %w_2, %i_12
store %e_14, %c_13
borrow.end %e_14
%i_15 = const.usize 4
%c_16 = const.u8 48
%e_17 = borrow.index %w_2, %i_15
store %e_17, %c_16
borrow.end %e_17
%i_18 = const.usize 5
%c_19 = const.u8 46
%e_20 = borrow.index %w_2, %i_18
store %e_20, %c_19
borrow.end %e_20
%i_21 = const.usize 6
%c_22 = const.u8 48
%e_23 = borrow.index %w_2, %i_21
store %e_23, %c_22
borrow.end %e_23
%i_24 = const.usize 7
%c_25 = const.u8 46
%e_26 = borrow.index %w_2, %i_24
store %e_26, %c_25
borrow.end %e_26
%i_27 = const.usize 8
%c_28 = const.u8 49
%e_29 = borrow.index %w_2, %i_27
store %e_29, %c_28
borrow.end %e_29
%i_30 = const.usize 9
%c_31 = const.u8 58
%e_32 = borrow.index %w_2, %i_30
store %e_32, %c_31
borrow.end %e_32
%i_33 = const.usize 10
%c_34 = const.u8 55
%e_35 = borrow.index %w_2, %i_33
store %e_35, %c_34
borrow.end %e_35
borrow.end %w_2
%b_36 = borrow.ref %bytes_1
%s_37 = slice.make %b_36
intrinsic net.listen(%listen, %s_37), ok -> @ok_38, err -> @err_40
ok_38(%ok_39: listener):
borrow.end %s_37
borrow.end %b_36
local.zero %bytes_42
%w_43 = borrow.mut %bytes_42
%i_44 = const.usize 0
%c_45 = const.u8 49
%e_46 = borrow.index %w_43, %i_44
store %e_46, %c_45
borrow.end %e_46
%i_47 = const.usize 1
%c_48 = const.u8 50
%e_49 = borrow.index %w_43, %i_47
store %e_49, %c_48
borrow.end %e_49
%i_50 = const.usize 2
%c_51 = const.u8 55
%e_52 = borrow.index %w_43, %i_50
store %e_52, %c_51
borrow.end %e_52
%i_53 = const.usize 3
%c_54 = const.u8 46
%e_55 = borrow.index %w_43, %i_53
store %e_55, %c_54
borrow.end %e_55
%i_56 = const.usize 4
%c_57 = const.u8 48
%e_58 = borrow.index %w_43, %i_56
store %e_58, %c_57
borrow.end %e_58
%i_59 = const.usize 5
%c_60 = const.u8 46
%e_61 = borrow.index %w_43, %i_59
store %e_61, %c_60
borrow.end %e_61
%i_62 = const.usize 6
%c_63 = const.u8 48
%e_64 = borrow.index %w_43, %i_62
store %e_64, %c_63
borrow.end %e_64
%i_65 = const.usize 7
%c_66 = const.u8 46
%e_67 = borrow.index %w_43, %i_65
store %e_67, %c_66
borrow.end %e_67
%i_68 = const.usize 8
%c_69 = const.u8 49
%e_70 = borrow.index %w_43, %i_68
store %e_70, %c_69
borrow.end %e_70
%i_71 = const.usize 9
%c_72 = const.u8 58
%e_73 = borrow.index %w_43, %i_71
store %e_73, %c_72
borrow.end %e_73
%i_74 = const.usize 10
%c_75 = const.u8 55
%e_76 = borrow.index %w_43, %i_74
store %e_76, %c_75
borrow.end %e_76
borrow.end %w_43
%b_77 = borrow.ref %bytes_42
%s_78 = slice.make %b_77
intrinsic net.connect(%connect, %s_78), ok -> @ok_79, err -> @err_81
err_40(%err_41: io_error):
borrow.end %s_37
borrow.end %b_36
trap
ok_79(%ok_80: stream):
borrow.end %s_78
borrow.end %b_77
%l_83 = borrow.mut %ok_39
intrinsic net.accept(%l_83), ok -> @ok_84, err -> @err_86
err_81(%err_82: io_error):
borrow.end %s_78
borrow.end %b_77
trap
ok_84(%ok_85: stream):
borrow.end %l_83
%client_88 = borrow.mut %ok_80
local.zero %bytes_89
%w_90 = borrow.mut %bytes_89
%i_91 = const.usize 0
%c_92 = const.u8 112
%e_93 = borrow.index %w_90, %i_91
store %e_93, %c_92
borrow.end %e_93
%i_94 = const.usize 1
%c_95 = const.u8 105
%e_96 = borrow.index %w_90, %i_94
store %e_96, %c_95
borrow.end %e_96
%i_97 = const.usize 2
%c_98 = const.u8 110
%e_99 = borrow.index %w_90, %i_97
store %e_99, %c_98
borrow.end %e_99
%i_100 = const.usize 3
%c_101 = const.u8 103
%e_102 = borrow.index %w_90, %i_100
store %e_102, %c_101
borrow.end %e_102
borrow.end %w_90
%b_103 = borrow.ref %bytes_89
%s_104 = slice.make %b_103
intrinsic net.send_all(%client_88, %s_104), ok -> @ok_105, err -> @err_106
err_86(%err_87: io_error):
borrow.end %l_83
trap
ok_105:
borrow.end %s_104
borrow.end %b_103
borrow.end %client_88
local.zero %buf_108
%server_109 = borrow.mut %ok_85
%buf_110 = borrow.mut %buf_108
%s_111 = slice.make %buf_110
intrinsic net.recv(%server_109, %s_111), ok -> @ok_112, err -> @err_114
err_106(%err_107: io_error):
borrow.end %s_104
borrow.end %b_103
borrow.end %client_88
trap
ok_112(%ok_113: usize):
borrow.end %s_111
borrow.end %buf_110
borrow.end %server_109
%server_116 = borrow.mut %ok_85
%buf_117 = borrow.ref %buf_108
%s_118 = slice.make %buf_117
%c_119 = const.usize 0
%len_120 = sub.checked.usize %ok_113, %c_119
%s_121 = slice.sub %s_118, %c_119, %len_120
intrinsic net.send_all(%server_116, %s_121), ok -> @ok_122, err -> @err_123
err_114(%err_115: io_error):
borrow.end %s_111
borrow.end %buf_110
borrow.end %server_109
trap
ok_122:
borrow.end %s_121
borrow.end %s_118
borrow.end %buf_117
borrow.end %server_116
local.zero %back_125
%client_126 = borrow.mut %ok_80
%back_127 = borrow.mut %back_125
%s_128 = slice.make %back_127
intrinsic net.recv(%client_126, %s_128), ok -> @ok_129, err -> @err_131
err_123(%err_124: io_error):
borrow.end %s_121
borrow.end %s_118
borrow.end %buf_117
borrow.end %server_116
trap
ok_129(%ok_130: usize):
borrow.end %s_128
borrow.end %back_127
borrow.end %client_126
intrinsic net.close_stream(%ok_85), ok -> @ok_133, err -> @err_134
err_131(%err_132: io_error):
borrow.end %s_128
borrow.end %back_127
borrow.end %client_126
trap
ok_133:
intrinsic net.close_stream(%ok_80), ok -> @ok_136, err -> @err_137
err_134(%err_135: io_error):
trap
ok_136:
intrinsic net.close_listener(%ok_39), ok -> @ok_139, err -> @err_140
err_137(%err_138: io_error):
trap
ok_139:
%back_142 = local.load %back_125
ret %back_142
err_140(%err_141: io_error):
trap
@@ -0,0 +1,22 @@
// Unsafe operations inside a function that declares `unsafe`; its callers declare it too.
// expect: run
// result: 30
// phase: 6
// spec: docs/spec/13-contracts-and-unsafe.md
module demo.unchecked
fn get(s: slice<u64>, i: usize) -> u64
effects [unsafe]
{
assume(i < s.len);
ref unchecked e = s[i];
*e
}
fn main() -> u64
effects [unsafe]
{
var a: [u64; 3] = [10; 3];
a[2] = 20;
get(ref a, 0) + get(ref a, 2)
}
+55 -1
View File
@@ -54,6 +54,9 @@ const Header = struct {
files: []const struct { []const u8, []const u8 },
phase: u8,
spec: []const u8,
/// `.aji` only: a reference AIR program (relative to the conformance
/// root) whose observable run must equal this one's.
equivalent: ?[]const u8 = null,
};
pub fn main(init: std.process.Init) !void {
@@ -165,13 +168,60 @@ fn runSource(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, rel: []const
switch (header.expect) {
.accept => if (report.status == .accepted) return .{ .outcome = .pass },
.reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass },
.run => |want| if (report.status == .accepted) return runModule(arena, path, report.module.?, want, header),
.run => |want| if (report.status == .accepted) {
const r = try runModule(arena, path, report.module.?, want, header);
if (r.outcome != .pass) return r;
if (header.equivalent) |ref| return equivalentRun(arena, io, dir, ref, report.module.?, header);
return r;
},
}
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{
fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items),
}) };
}
/// Source/AIR equivalence: the lowered program and a hand-written reference
/// AIR program, run with the same world and grants, must give the same run
/// record byte for byte. The AIR text may differ (the frontend may build
/// another correct CFG). A trap is compared by its code only, since the
/// record also carries the AIR location.
fn equivalentRun(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, ref: []const u8, lowered: aji.air.Module, header: Header) !Result {
const text = dir.readFileAlloc(io, ref, arena, .limited(16 << 20)) catch
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "equivalent: cannot read {s}", .{ref}) };
const body = try arena.dupe(u8, text);
var line_start: usize = 0;
while (line_start < body.len and body[line_start] == ';') {
const end = std.mem.indexOfScalarPos(u8, body, line_start, '\n') orelse body.len;
@memset(body[line_start..end], ' ');
line_start = end + 1;
}
const report = try aji.check.checkAir(arena, ref, body);
if (report.status != .accepted) return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "equivalent: {s} is {t}", .{ ref, report.status }) };
var records: [2][]const u8 = undefined;
var codes: [2]?[]const u8 = .{ null, null };
for ([_]aji.air.Module{ lowered, report.module.? }, &records, &codes) |m, *rec, *code| {
var output: aji.interp.Output = undefined;
const outcome = try aji.interp.run(arena, m, "main", .{
.fuel = header.fuel,
.grants = header.grants,
.world = header.world,
.output = &output,
.quantum = header.quantum,
.task_limit = header.task_limit,
});
var w: std.Io.Writer.Allocating = .init(arena);
try aji.interp.writeOutcome(m, outcome, output, &w.writer);
rec.* = w.written();
if (outcome == .trapped) code.* = outcome.trapped.code.id;
}
const same = if (codes[0] != null or codes[1] != null)
codes[0] != null and codes[1] != null and std.mem.eql(u8, codes[0].?, codes[1].?)
else
std.mem.eql(u8, records[0], records[1]);
if (same) return .{ .outcome = .pass };
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "not equivalent to {s}: {s} vs {s}", .{ ref, records[0], records[1] }) };
}
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.lessThan(u8, a, b);
}
@@ -405,6 +455,7 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
var want_stdout: ?[]const u8 = null;
var want_stderr: ?[]const u8 = null;
var spec: ?[]const u8 = null;
var equivalent: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, source, '\n');
while (lines.next()) |line| {
@@ -484,6 +535,8 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
phase = try std.fmt.parseInt(u8, value, 10);
} else if (std.mem.eql(u8, key, "spec")) {
spec = value;
} else if (std.mem.eql(u8, key, "equivalent")) {
equivalent = value;
} else return error.UnknownKey;
}
if (expect) |*e| switch (e.*) {
@@ -506,6 +559,7 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
.files = want_files.items,
.phase = phase orelse return error.MissingPhase,
.spec = spec orelse return error.MissingSpec,
.equivalent = equivalent,
};
}