Phase 2: I/O intrinsics, linear resources, deterministic profile (RFC 0007)

- air: resource types file<read|write|append>, listener, stream; io_error;
  intrinsic registry (19 intrinsics) synced with reference/intrinsics.md;
  fallible intrinsics as ok/err terminators; fs prefix narrowing;
  linear_aggregates gating
- verifier: intrinsic form, operand, result and capability-kind checks
  (E1001, E3201, E5002); intrinsic effects (E3101); resource linearity
  in the borrow walker with per-edge moves: E3002 leaks and join
  mismatches, E3001, E2001, E2002, E2101 for close while borrowed;
  resources as borrow roots
- interp: deterministic world (captured console, VFS, loopback TCP,
  instruction clock, pinned xoshiro256 PRNG), blocked outcome, run
  record with stdout/stderr/files
- CLI: --stdin, --vfs, --seed, --result-file, --profile (hosted: exit 3),
  exit code 7; runner: stdin/vfs/seed/stdout/stderr/file/blocked headers
- conformance: hello, file copy and TCP echo exit programs; 37 new tests;
  4000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 14:02:17 +03:00
1 parent 571cc6e362
commit d405d4ea50
49 files changed
+2325 -81

No files matched your search

+1 -1
View File
@@ -131,7 +131,7 @@ zig fmt --check build.zig build.zig.zon src tools
Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing. Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing.
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]…` prints one JSON run record; capabilities reach a program only as named `@main` parameters. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7). `aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` is specified but not implemented yet. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
## Testing policy ## Testing policy
+3
View File
@@ -24,6 +24,9 @@ pub fn build(b: *std.Build) void {
mod.addAnonymousImport("capabilities_md", .{ mod.addAnonymousImport("capabilities_md", .{
.root_source_file = b.path("docs/reference/capabilities.md"), .root_source_file = b.path("docs/reference/capabilities.md"),
}); });
mod.addAnonymousImport("intrinsics_md", .{
.root_source_file = b.path("docs/reference/intrinsics.md"),
});
// CLI: `aji`. // CLI: `aji`.
const exe = b.addExecutable(.{ const exe = b.addExecutable(.{
+1
View File
@@ -13,5 +13,6 @@
"docs/reference/air-features.md", "docs/reference/air-features.md",
"docs/reference/effects.md", "docs/reference/effects.md",
"docs/reference/capabilities.md", "docs/reference/capabilities.md",
"docs/reference/intrinsics.md",
}, },
} }
+1 -1
View File
@@ -48,7 +48,7 @@ Reason: Zig's standard library changes between minor versions; an unpinned toolc
## DD-009 — CLI diagnostics are JSON Lines on stdout ## DD-009 — CLI diagnostics are JSON Lines on stdout
`aji` writes one JSON diagnostic per line on stdout, human notes on stderr, and uses fixed exit codes (0 accepted or returned, 1 rejected, 2 usage/I/O, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated). `aji` writes one JSON diagnostic per line on stdout, human notes on stderr, and uses fixed exit codes (0 accepted or returned, 1 rejected, 2 usage/I/O, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked).
Reason: agents consume diagnostics programmatically (spec 10); mixing prose into the machine channel breaks repair loops. Reason: agents consume diagnostics programmatically (spec 10); mixing prose into the machine channel breaks repair loops.
+1
View File
@@ -32,6 +32,7 @@ Planned header extensions (added by the phase that needs them):
|---|---|---| |---|---|---|
| `expect: run` + `result:` / `trap:` | P0 (implemented) | module must verify; run record must match | | `expect: run` + `result:` / `trap:` | P0 (implemented) | module must verify; run record must match |
| `stdout:` | P2 | expected output, `\n`-escaped (needs `io.write`) | | `stdout:` | P2 | expected output, `\n`-escaped (needs `io.write`) |
| `stdin:` / `vfs:` / `seed:` / `stdout:` / `stderr:` / `file:` / `blocked:` | P2 (implemented) | deterministic world inputs and expected observable output |
| `grant:` / `not_instantiated:` | P2 (implemented) | capability grants for `@main`; expected instantiation failure | | `grant:` / `not_instantiated:` | P2 (implemented) | capability grants for `@main`; expected instantiation failure |
| `fuel:` | P0 (implemented) | instruction limit; default 1 000 000 (spec 11 §7.1) | | `fuel:` | P0 (implemented) | instruction limit; default 1 000 000 (spec 11 §7.1) |
| `seed:` / `schedules:` / `quantum:` | P3 | scheduler seed / schedule budget / instructions per forced scheduling point (spec 11 §7.2) | | `seed:` / `schedules:` / `quantum:` | P3 | scheduler seed / schedule budget / instructions per forced scheduling point (spec 11 §7.2) |
+1 -1
View File
@@ -99,5 +99,5 @@ These run through all phases rather than belonging to one.
|---|---| |---|---|
| P0 | done; AIR format 0 frozen as the semantic baseline (spec 07 §8.7) | | P0 | done; AIR format 0 frozen as the semantic baseline (spec 07 §8.7) |
| P1 | done (exit review in the phase file) | | P1 | done (exit review in the phase file) |
| P2 | in progress: RFC 0006 (effects, capabilities) accepted and implemented; next RFC 0007 (I/O) and RFC 0008 (heap, regions) | | P2 | in progress: RFC 0006 (effects, capabilities) and RFC 0007 (I/O, resources, deterministic profile) implemented; next RFC 0008 (heap, regions), hosted profile, unsafe boundaries |
| P3–P8 | not started | | P3–P8 | not started |
@@ -21,21 +21,22 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
| ID | Status | Task | Depends | Output | Done when | | ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| P2-1 | done | Resolve Q-011, Q-012, Q-018 (RFC 0006; Q-018 resolved in P0) | — | spec 05, 07, 10 | questions resolved; runtime record format defined | | P2-1 | done | Resolve Q-011, Q-012, Q-018 (RFC 0006; Q-018 resolved in P0) | — | spec 05, 07, 10 | questions resolved; runtime record format defined |
| P2-2 | todo | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) | | P2-2 | done | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) |
| P2-2a | done | Publish features `effects` and `capabilities` (spec text, registry status, `supported`); effect checking applies to modules declaring `effects` | P2-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests; baseline modules unaffected | | P2-2a | done | Publish features `effects` and `capabilities` (spec text, registry status, `supported`); effect checking applies to modules declaring `effects` | P2-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests; baseline modules unaffected |
| P2-2b | todo | Specify and publish `heap` (`Own<T>`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published | | P2-2b | todo | Specify and publish `heap` (`Own<T>`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published |
| P2-2c | todo | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) | | P2-2c | todo | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) |
| P2-2d | todo | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject | | P2-2d | todo | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject |
| P2-2e | todo | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer | | P2-2e | todo | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer |
| P2-3 | todo | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present | | P2-3 | done | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present |
| P2-4 | doing | Effect verifier (calls done; intrinsics with RFC 0007) | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees | | P2-4 | done | Effect verifier (calls and intrinsics) | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees |
| P2-5 | doing | Capability verifier: unforgeability, narrowing, transfer rules (types, E3202, instantiation done; E3201 with intrinsics) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject | | P2-5 | done | Capability verifier: unforgeability, narrowing, transfer rules (E3201, E3202, instantiation) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject |
| P2-6 | todo | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected | | P2-6 | done | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected |
| P2-7 | todo | Unsafe boundary verifier | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject | | P2-7 | todo | Unsafe boundary verifier | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject |
| P2-8 | todo | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs | | P2-8 | doing | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs |
| P2-9 | doing | Entry-point capability instantiation (`--grant` done; `aji.toml` `[capabilities]` pending) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) | | P2-9 | doing | Entry-point capability instantiation (`--grant` done; `aji.toml` `[capabilities]` pending) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) |
| P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test | | P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
| P2-11 | todo | Reference programs: hello (real `io.write` if deferred from P0), file-copy, tcp-echo (single task) | P2-8 | `tests/programs/` | all three run; cleanup on every error path verified | | P2-11 | done | Reference programs: hello (real `io.write` if deferred from P0), file-copy, tcp-echo (single task) | P2-8 | `tests/programs/` | all three run; cleanup on every error path verified |
| P2-8a | todo | Hosted profile: real console, files and TCP; run record through `--result-file` (spec 11 §8) | P2-8 | `src/interp/host.zig` | hello, file-copy and tcp-echo run against the real OS in CI |
| P2-12 | todo | Phase exit review | all | plan status | exit criterion passes | | P2-12 | todo | Phase exit review | all | plan status | exit criterion passes |
## Conformance tests to add ## Conformance tests to add
+1 -1
View File
@@ -242,4 +242,4 @@ Resource types and their consumption rules: spec 06 §6. Resources are used thro
On a trap it reports `{"status":"trapped", "code":…, "kind":…, "function":…, "block":…, "inst":…}` (spec 01 §6). On a trap it reports `{"status":"trapped", "code":…, "kind":…, "function":…, "block":…, "inst":…}` (spec 01 §6).
Programs that declare `capabilities` also get `"stdout"` and `"stderr"` (captured output) and `"files"` (files written in the virtual file system) in the record of the `deterministic` profile (spec 11 §8). When the deterministic runtime detects quiescence it reports `{"status":"blocked","kind":"no_future_event",…}` (spec 11 §8). When instantiation fails (spec 05 §10.2) the program does not start and the runner reports `{"status":"not_instantiated","reason":…,…}`. When the runner stops execution because an execution limit is exhausted (spec 11 §7), it reports `{"status":"limit_exceeded","kind":"fuel","limit":N,"steps":N}`. This is an outcome of the execution environment, not of the program, and is not a trap. Programs that declare `capabilities` also get `"stdout"` and `"stderr"` (captured output) and `"files"` (files written in the virtual file system, keyed by path in byte order) in the record of the `deterministic` profile (spec 11 §8). These byte strings are written as JSON strings in which printable ASCII other than `"` and `\` appears as is, `"`, `\` and newline are escaped as `\"`, `\\` and `\n`, and every other byte `b` as `\u00XX`, so any output is valid, deterministic JSON. When the deterministic runtime detects quiescence it reports `{"status":"blocked","kind":"no_future_event",…}` (spec 11 §8). When instantiation fails (spec 05 §10.2) the program does not start and the runner reports `{"status":"not_instantiated","reason":…,…}`. When the runner stops execution because an execution limit is exhausted (spec 11 §7), it reports `{"status":"limit_exceeded","kind":"fuel","limit":N,"steps":N}`. This is an outcome of the execution environment, not of the program, and is not a trap.
+1 -1
View File
@@ -115,7 +115,7 @@ The run record gains fields for observable output. `aji run` uses the **determin
| files | in-memory file system seeded by `--vfs PATH=TEXT`; files written during the run are reported as `"files"` in the run record | real file system, limited by capability scopes | | files | in-memory file system seeded by `--vfs PATH=TEXT`; files written during the run are reported as `"files"` in the run record | real file system, limited by capability scopes |
| network | in-process loopback: `net.connect` to a listening address of the same run queues a connection that `net.accept` returns; sends are buffered; an operation that would wait for an event that can never occur ends the run with the environment outcome `blocked` (below) | real sockets | | network | in-process loopback: `net.connect` to a listening address of the same run queues a connection that `net.accept` returns; sends are buffered; an operation that would wait for an event that can never occur ends the run with the environment outcome `blocked` (below) | real sockets |
| clock | the number of instructions executed so far (1 ns per instruction) | real monotonic clock | | clock | the number of instructions executed so far (1 ns per instruction) | real monotonic clock |
| random | PRNG seeded by `--seed N` (default 0), algorithm fixed by the spec | host CSPRNG | | random | xoshiro256\*\* whose state is initialized by SplitMix64 from `--seed N` (default 0); bytes are taken from successive 64-bit outputs, least significant byte first | host CSPRNG |
**Quiescence.** In the `deterministic` profile, when an operation would wait, no other execution unit can run, and no future deterministic event can complete the wait, the run ends with the environment outcome **Quiescence.** In the `deterministic` profile, when an operation would wait, no other execution unit can run, and no future deterministic event can complete the wait, the run ends with the environment outcome
+120 -2
View File
@@ -45,8 +45,8 @@ pub const Kind = struct {
pub const kinds = [_]Kind{ pub const kinds = [_]Kind{
.{ .name = "clock.read", .scope = .none, .forms = &.{} }, .{ .name = "clock.read", .scope = .none, .forms = &.{} },
.{ .name = "fs.read", .scope = .path_prefix, .forms = &.{} }, .{ .name = "fs.read", .scope = .path_prefix, .forms = &.{"prefix"} },
.{ .name = "fs.write", .scope = .path_prefix, .forms = &.{} }, .{ .name = "fs.write", .scope = .path_prefix, .forms = &.{"prefix"} },
.{ .name = "io.read", .scope = .none, .forms = &.{} }, .{ .name = "io.read", .scope = .none, .forms = &.{} },
.{ .name = "io.write", .scope = .none, .forms = &.{} }, .{ .name = "io.write", .scope = .none, .forms = &.{} },
.{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{} }, .{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{} },
@@ -63,10 +63,20 @@ pub const kinds = [_]Kind{
/// Built-in enums: spelled without `@`, fixed variants, no payloads. /// Built-in enums: spelled without `@`, fixed variants, no payloads.
pub const Builtin = enum { pub const Builtin = enum {
cap_error, cap_error,
io_error,
pub fn variants(b: Builtin) []const []const u8 { pub fn variants(b: Builtin) []const []const u8 {
return switch (b) { return switch (b) {
.cap_error => &.{ "invalid_restriction", "not_subset", "unsupported_restriction" }, .cap_error => &.{ "invalid_restriction", "not_subset", "unsupported_restriction" },
.io_error => &.{ "not_found", "permission_denied", "already_exists", "invalid_input", "no_space", "broken_pipe", "connection_refused", "connection_reset", "address_in_use", "address_unavailable", "timed_out", "other" },
};
}
/// Feature a built-in enum belongs to.
pub fn feature(b: Builtin) []const u8 {
return switch (b) {
.cap_error => "capabilities",
.io_error => "resources",
}; };
} }
@@ -111,6 +121,94 @@ pub fn validScope(kind: u16, scope: ?[]const u8) bool {
}; };
} }
// ---------------------------------------------------------------- intrinsics (reference/intrinsics.md)
/// Linear resource types (spec 06 §6).
pub const Resource = enum {
file_read,
file_write,
file_append,
listener,
stream,
pub fn text(r: Resource) []const u8 {
return switch (r) {
.file_read => "file<read>",
.file_write => "file<write>",
.file_append => "file<append>",
.listener => "listener",
.stream => "stream",
};
}
};
/// Shape of an intrinsic operand.
pub const Operand = union(enum) {
/// `cap<kind>`.
cap: []const u8,
/// `slice<u8>` (read).
bytes,
/// `slice_mut<u8>` (written).
buffer,
/// `mut<R>` for one of the listed resources; not consumed.
borrowed: []const Resource,
/// A resource of one of the listed types, consumed on both edges.
consumed: []const Resource,
};
pub const ResultType = union(enum) {
usize,
u64,
resource: Resource,
};
pub const Intrinsic = struct {
name: []const u8,
operands: []const Operand,
/// Fallible: results are `@ok` parameters and `@err` gets an `io_error`.
/// Infallible: at most one result, bound with `%r =`.
fallible: bool,
results: []const ResultType,
effect: ?[]const u8,
};
const files_w = &[_]Resource{ .file_write, .file_append };
const files_any = &[_]Resource{ .file_read, .file_write, .file_append };
pub const intrinsics = [_]Intrinsic{
.{ .name = "clock.monotonic", .operands = &.{.{ .cap = "clock.read" }}, .fallible = false, .results = &.{.u64}, .effect = "clock.read" },
.{ .name = "fs.close", .operands = &.{.{ .consumed = files_any }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "fs.create", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_write }}, .effect = "fs.write" },
.{ .name = "fs.open_append", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_append }}, .effect = "fs.write" },
.{ .name = "fs.open_read", .operands = &.{ .{ .cap = "fs.read" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_read }}, .effect = "fs.read" },
.{ .name = "fs.read", .operands = &.{ .{ .borrowed = &.{.file_read} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "fs.read" },
.{ .name = "fs.sync", .operands = &.{.{ .borrowed = files_w }}, .fallible = true, .results = &.{}, .effect = "fs.write" },
.{ .name = "fs.write_all", .operands = &.{ .{ .borrowed = files_w }, .bytes }, .fallible = true, .results = &.{}, .effect = "fs.write" },
.{ .name = "io.stderr_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
.{ .name = "io.stdin_read", .operands = &.{ .{ .cap = "io.read" }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "io.read" },
.{ .name = "io.stdout_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
.{ .name = "net.accept", .operands = &.{.{ .borrowed = &.{.listener} }}, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.listen" },
.{ .name = "net.close_listener", .operands = &.{.{ .consumed = &.{.listener} }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "net.close_stream", .operands = &.{.{ .consumed = &.{.stream} }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "net.connect", .operands = &.{ .{ .cap = "net.connect" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.connect" },
.{ .name = "net.listen", .operands = &.{ .{ .cap = "net.listen" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .listener }}, .effect = "net.listen" },
.{ .name = "net.recv", .operands = &.{ .{ .borrowed = &.{.stream} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "net.read" },
.{ .name = "net.send_all", .operands = &.{ .{ .borrowed = &.{.stream} }, .bytes }, .fallible = true, .results = &.{}, .effect = "net.write" },
.{ .name = "random.fill", .operands = &.{ .{ .cap = "random.read" }, .buffer }, .fallible = false, .results = &.{}, .effect = "random.read" },
};
pub fn intrinsicIndex(name: []const u8) ?u16 {
for (intrinsics, 0..) |x, i| if (std.mem.eql(u8, x.name, name)) return @intCast(i);
return null;
}
/// Whether an intrinsic mentions resource types (needs feature `resources`).
pub fn usesResources(x: Intrinsic) bool {
for (x.operands) |o| if (o == .borrowed or o == .consumed) return true;
for (x.results) |r| if (r == .resource) return true;
return false;
}
/// Names in the first column of the first table of a reference file whose /// Names in the first column of the first table of a reference file whose
/// rows start with "| `". /// rows start with "| `".
fn tableNames(comptime md: []const u8, buf: [][]const u8) usize { fn tableNames(comptime md: []const u8, buf: [][]const u8) usize {
@@ -151,3 +249,23 @@ test "instantiation scopes" {
try std.testing.expect(!validScope(kindIndex("io.write").?, "/x")); try std.testing.expect(!validScope(kindIndex("io.write").?, "/x"));
try std.testing.expect(validScope(kindIndex("mem.alloc").?, "1048576")); try std.testing.expect(validScope(kindIndex("mem.alloc").?, "1048576"));
} }
test "intrinsic registry mirrors reference/intrinsics.md" {
const md = @embedFile("intrinsics_md");
var n: usize = 0;
var lines = std.mem.splitScalar(u8, md, '\n');
while (lines.next()) |line| {
if (!std.mem.startsWith(u8, line, "| `")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
const name = std.mem.trim(u8, cols.next().?, " `");
// Only intrinsic rows: a single dotted name (the narrowing table lists kinds).
if (std.mem.indexOfScalar(u8, name, '.') == null or std.mem.indexOfScalar(u8, name, ',') != null) continue;
if (intrinsicIndex(name) == null) {
std.debug.print("intrinsic {s} is documented but not registered\n", .{name});
return error.RegistryOutOfSync;
}
n += 1;
}
try std.testing.expectEqual(intrinsics.len, n);
for (intrinsics, 0..) |x, i| if (i > 0) try std.testing.expect(std.mem.lessThan(u8, intrinsics[i - 1].name, x.name));
}
+3 -1
View File
@@ -30,14 +30,16 @@ pub const registry = [_]Feature{
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 }, .{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
.{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 }, .{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "ownership", "regions" }, .status = .reserved, .phase = 4 }, .{ .name = "islands", .depends = &.{ "capabilities", "effects", "ownership", "regions" }, .status = .reserved, .phase = 4 },
.{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 }, .{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 }, .{ .name = "regions", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, .{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
}; };
/// Features implemented by this toolchain, sorted. /// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership" }; pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership", "resources" };
pub const Reason = enum { pub const Reason = enum {
unknown_feature, unknown_feature,
+15 -1
View File
@@ -77,6 +77,8 @@ pub const Type = union(enum) {
/// Index into `authority.kinds`. /// Index into `authority.kinds`.
cap: u16, cap: u16,
builtin: authority.Builtin, builtin: authority.Builtin,
// Feature `resources` (spec 06 §6).
resource: authority.Resource,
pub const Array = struct { elem: Type, len: u64 }; pub const Array = struct { elem: Type, len: u64 };
@@ -89,6 +91,7 @@ pub const Type = union(enum) {
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem), .array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k, .cap => |k| b.cap == k,
.builtin => |e| b.builtin == e, .builtin => |e| b.builtin == e,
.resource => |r| b.resource == r,
.bool, .void, .never => true, .bool, .void, .never => true,
}; };
} }
@@ -119,9 +122,11 @@ pub const Type = union(enum) {
} }
/// Value types may be stored in fields, payloads, elements and locals. /// Value types may be stored in fields, payloads, elements and locals.
/// (A borrowed resource `mut<file<read>>` has a resource as its inner type.)
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool { pub fn isValue(t: Type) bool {
return switch (t) { return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut => false, .void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource => false,
else => true, else => true,
}; };
} }
@@ -232,6 +237,9 @@ pub const Op = union(enum) {
/// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new /// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new
/// capability or at `err` with a `cap_error`, as block parameters. /// capability or at `err` with a `cap_error`, as block parameters.
cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 }, cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 },
/// Intrinsic call (spec 05 §11). With `ok`/`err` it is the fallible
/// terminator form; without, the infallible form.
intrinsic: struct { index: u16, args: []const ValueId, ok: ?u32 = null, err: ?u32 = null },
ret: ?ValueId, ret: ?ValueId,
trap, trap,
@@ -241,6 +249,7 @@ pub const Op = union(enum) {
pub fn isTerminator(op: Op) bool { pub fn isTerminator(op: Op) bool {
return switch (op) { return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true, .br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
.intrinsic => |x| x.ok != null,
else => false, else => false,
}; };
} }
@@ -366,6 +375,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.cap); f(ctx, x.cap);
for (x.args) |v| f(ctx, v); for (x.args) |v| f(ctx, v);
}, },
.intrinsic => |x| for (x.args) |v| f(ctx, v),
.ret => |v| if (v) |x| f(ctx, x), .ret => |v| if (v) |x| f(ctx, x),
.local_alloc => {}, .local_alloc => {},
.local_store => |x| { .local_store => |x| {
@@ -419,6 +429,10 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
try buf.append(gpa, x.ok); try buf.append(gpa, x.ok);
try buf.append(gpa, x.err); try buf.append(gpa, x.err);
}, },
.intrinsic => |x| if (x.ok) |ok| {
try buf.append(gpa, ok);
try buf.append(gpa, x.err.?);
},
else => {}, else => {},
} }
} }
+49 -8
View File
@@ -423,7 +423,9 @@ const Parser = struct {
while (p.peek().tag != .r_brace) { while (p.peek().tag != .r_brace) {
const fname = try p.expect(.word, "field name"); const fname = try p.expect(.word, "field name");
_ = try p.expect(.colon, "`:`"); _ = try p.expect(.colon, "`:`");
const ty_span = p.peek().span;
const ty = try p.parseType(); const ty = try p.parseType();
try p.gateLinearMember(ty, ty_span);
for (fields.items) |f| if (std.mem.eql(u8, f.name, fname.text)) for (fields.items) |f| if (std.mem.eql(u8, f.name, fname.text))
try p.report("E0003", fname.span, "duplicate field", &.{.{ .name = "name", .value = .{ .str = fname.text } }}); try p.report("E0003", fname.span, "duplicate field", &.{.{ .name = "name", .value = .{ .str = fname.text } }});
try fields.append(p.arena, .{ .name = fname.text, .ty = ty }); try fields.append(p.arena, .{ .name = fname.text, .ty = ty });
@@ -442,7 +444,10 @@ const Parser = struct {
if (p.peek().tag == .l_paren) { if (p.peek().tag == .l_paren) {
_ = p.next(); _ = p.next();
while (p.peek().tag != .r_paren) { while (p.peek().tag != .r_paren) {
try payload.append(p.arena, try p.parseType()); const ty_span = p.peek().span;
const ty = try p.parseType();
try p.gateLinearMember(ty, ty_span);
try payload.append(p.arena, ty);
if (p.peek().tag != .comma) break; if (p.peek().tag != .comma) break;
_ = p.next(); _ = p.next();
} }
@@ -477,9 +482,13 @@ const Parser = struct {
if (std.mem.eql(u8, t.text, "void")) return .void; if (std.mem.eql(u8, t.text, "void")) return .void;
if (std.mem.eql(u8, t.text, "never")) return .never; if (std.mem.eql(u8, t.text, "never")) return .never;
if (std.meta.stringToEnum(authority.Builtin, t.text)) |b| { if (std.meta.stringToEnum(authority.Builtin, t.text)) |b| {
try p.requireFeature("capabilities", t.span, t.text); try p.requireFeature(b.feature(), t.span, t.text);
return .{ .builtin = b }; return .{ .builtin = b };
} }
if (eql(t.text, "listener") or eql(t.text, "stream")) {
try p.requireFeature("resources", t.span, t.text);
return .{ .resource = if (eql(t.text, "listener")) .listener else .stream };
}
if (std.mem.eql(u8, t.text, "f32") or std.mem.eql(u8, t.text, "f64")) { if (std.mem.eql(u8, t.text, "f32") or std.mem.eql(u8, t.text, "f64")) {
try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{ try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{
.{ .name = "reason", .value = .{ .str = "reserved_type" } }, .{ .name = "reason", .value = .{ .str = "reserved_type" } },
@@ -496,6 +505,18 @@ const Parser = struct {
/// `local<T>`, `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`, `array<T, N>` (spec 07 §8.8). /// `local<T>`, `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`, `array<T, N>` (spec 07 §8.8).
fn parseCompoundType(p: *Parser, t: Token) Error!air.Type { fn parseCompoundType(p: *Parser, t: Token) Error!air.Type {
if (eql(t.text, "file")) {
try p.requireFeature("resources", t.span, "file");
_ = try p.expect(.lt, "`<`");
const mode = try p.expect(.word, "`read`, `write` or `append`");
_ = try p.expect(.gt, "`>`");
const Mode = enum { read, write, append };
return .{ .resource = switch (std.meta.stringToEnum(Mode, mode.text) orelse return p.fail(mode, "`read`, `write` or `append`")) {
.read => .file_read,
.write => .file_write,
.append => .file_append,
} };
}
if (eql(t.text, "cap")) { if (eql(t.text, "cap")) {
try p.requireFeature("capabilities", t.span, "cap"); try p.requireFeature("capabilities", t.span, "cap");
_ = try p.expect(.lt, "`<`"); _ = try p.expect(.lt, "`<`");
@@ -517,8 +538,10 @@ const Parser = struct {
.slice, .slice_mut, .array => "arrays", .slice, .slice_mut, .array => "arrays",
}, t.span, t.text); }, t.span, t.text);
_ = try p.expect(.lt, "`<`"); _ = try p.expect(.lt, "`<`");
const inner_span = p.peek().span;
const inner = try p.parseType(); const inner = try p.parseType();
if (kind == .array) { if (kind == .array) {
try p.gateLinearMember(inner, inner_span);
_ = try p.expect(.comma, "`,`"); _ = try p.expect(.comma, "`,`");
const n_tok = try p.expect(.number, "array length"); const n_tok = try p.expect(.number, "array length");
const n = std.fmt.parseInt(u64, n_tok.text, 0) catch 0; const n = std.fmt.parseInt(u64, n_tok.text, 0) catch 0;
@@ -543,6 +566,11 @@ const Parser = struct {
}; };
} }
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
if (t == .resource) try p.requireFeature("linear_aggregates", span, "resource as a member");
}
fn declares(p: *Parser, feature: []const u8) bool { fn declares(p: *Parser, feature: []const u8) bool {
for (p.declared) |d| if (eql(d, feature)) return true; for (p.declared) |d| if (eql(d, feature)) return true;
return false; return false;
@@ -842,7 +870,7 @@ const Parser = struct {
try p.report("E0004", t.span, "unknown enum", &.{.{ .name = "name", .value = .{ .str = t.text } }}); try p.report("E0004", t.span, "unknown enum", &.{.{ .name = "name", .value = .{ .str = t.text } }});
return error.SyntaxError; return error.SyntaxError;
}; };
try p.requireFeature("capabilities", t.span, t.text); try p.requireFeature(b.feature(), t.span, t.text);
break :blk .{ .builtin = b }; break :blk .{ .builtin = b };
} else .{ .named = try p.typeRef(.@"enum") }; } else .{ .named = try p.typeRef(.@"enum") };
const value = try p.useValue(); const value = try p.useValue();
@@ -890,10 +918,23 @@ const Parser = struct {
if (eql(op_tok.text, "intrinsic")) { if (eql(op_tok.text, "intrinsic")) {
try p.requireFeature("capabilities", op_tok.span, "intrinsic"); try p.requireFeature("capabilities", op_tok.span, "intrinsic");
const name = try p.expect(.word, "intrinsic name"); const name = try p.expect(.word, "intrinsic name");
// No intrinsic is registered yet (RFC 0007), so every name is unknown. const which = authority.intrinsicIndex(name.text) orelse {
try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }}); try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }});
while (p.peek().tag != .nl) _ = p.next(); while (p.peek().tag != .nl) _ = p.next();
return null; return null;
};
if (authority.usesResources(authority.intrinsics[which])) try p.requireFeature("resources", name.span, name.text);
const args = try p.valueList();
if (p.peek().tag != .comma) break :op .{ .intrinsic = .{ .index = which, .args = args } };
_ = p.next();
_ = try p.expectWord("ok");
_ = try p.expect(.arrow, "`->`");
const ok = try p.blockRef();
_ = try p.expect(.comma, "`,`");
_ = try p.expectWord("err");
_ = try p.expect(.arrow, "`->`");
const err = try p.blockRef();
break :op .{ .intrinsic = .{ .index = which, .args = args, .ok = ok, .err = err } };
} }
return p.unknownOpcode(op_tok); return p.unknownOpcode(op_tok);
}; };
@@ -905,7 +946,7 @@ const Parser = struct {
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
else => false, else => false,
}; };
const may_bind = produces_value or op == .call; const may_bind = produces_value or op == .call or op == .intrinsic;
if (result_tok) |rt| { if (result_tok) |rt| {
if (!may_bind) return p.fail(rt, "instruction without result binding"); if (!may_bind) return p.fail(rt, "instruction without result binding");
} else if (produces_value) { } else if (produces_value) {
+6
View File
@@ -104,6 +104,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
}, },
.cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}), .cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}),
.builtin => |b| try w.writeAll(@tagName(b)), .builtin => |b| try w.writeAll(@tagName(b)),
.resource => |r| try w.writeAll(r.text()),
.bool, .void, .never => try w.writeAll(@tagName(t)), .bool, .void, .never => try w.writeAll(@tagName(t)),
} }
} }
@@ -280,6 +281,11 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
.slice_split => |x| try two(f, w, "slice.split", x.slice, x.at), .slice_split => |x| try two(f, w, "slice.split", x.slice, x.at),
.slice_copy => |x| try two(f, w, "slice.copy", x.dst, x.src), .slice_copy => |x| try two(f, w, "slice.copy", x.dst, x.src),
.guard => |v| try one(f, w, "guard", v), .guard => |v| try one(f, w, "guard", v),
.intrinsic => |x| {
try w.print("intrinsic {s}", .{air.authority.intrinsics[x.index].name});
try values(f, x.args, w);
if (x.ok) |ok| try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[ok].name, f.blocks[x.err.?].name });
},
.cap_narrow => |x| { .cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form}); try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w); try value(f, x.cap, w);
+2
View File
@@ -7,6 +7,8 @@ pub const Trap = machine.Trap;
pub const Outcome = machine.Outcome; pub const Outcome = machine.Outcome;
pub const Options = machine.Options; pub const Options = machine.Options;
pub const Grant = machine.Grant; pub const Grant = machine.Grant;
pub const Output = machine.Output;
pub const WorldOptions = machine.WorldOptions;
pub const run = machine.run; pub const run = machine.run;
pub const writeOutcome = machine.writeOutcome; pub const writeOutcome = machine.writeOutcome;
pub const writeValue = machine.writeValue; pub const writeValue = machine.writeValue;
+227 -5
View File
@@ -11,6 +11,9 @@
const std = @import("std"); const std = @import("std");
const air = @import("../air.zig"); const air = @import("../air.zig");
const diag = @import("../diag.zig"); const diag = @import("../diag.zig");
const world_mod = @import("world.zig");
pub const WorldOptions = world_mod.Options;
pub const call_depth_limit = 1024; pub const call_depth_limit = 1024;
@@ -30,6 +33,8 @@ pub const Value = union(enum) {
/// `cap<K>`: index into the host's authority table. Never observable /// `cap<K>`: index into the host's authority table. Never observable
/// by the program (spec 05 §10.1). /// by the program (spec 05 §10.1).
cap: u32, cap: u32,
/// Linear resource: index into the world's handle table.
resource: u32,
/// Value of a built-in enum such as `cap_error`. /// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 }, builtin: struct { which: air.authority.Builtin, variant: u32 },
@@ -64,8 +69,13 @@ pub const Outcome = union(enum) {
limit_exceeded: struct { limit: u64, steps: u64 }, limit_exceeded: struct { limit: u64, steps: u64 },
/// The host did not start the program (spec 05 §10.2). Not a trap. /// The host did not start the program (spec 05 §10.2). Not a trap.
not_instantiated: NotInstantiated, not_instantiated: NotInstantiated,
/// The deterministic runtime found no future event that could complete
/// a wait (spec 11 §8). Not a trap and not an I/O error.
blocked: Location,
}; };
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
pub const NotInstantiated = struct { pub const NotInstantiated = struct {
reason: []const u8, reason: []const u8,
parameter: []const u8, parameter: []const u8,
@@ -89,6 +99,18 @@ pub const Options = struct {
fuel: ?u64 = null, fuel: ?u64 = null,
/// Capability grants for the parameters of the entry function. /// Capability grants for the parameters of the entry function.
grants: []const Grant = &.{}, grants: []const Grant = &.{},
/// Inputs of the deterministic world (spec 11 §8).
world: WorldOptions = .{},
/// Receives the run's observable output.
output: ?*Output = null,
};
/// Observable output of a run in the deterministic profile.
pub const Output = struct {
stdout: []const u8,
stderr: []const u8,
/// Files written during the run, sorted by path.
files: []const struct { []const u8, []const u8 },
}; };
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant }; pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
@@ -99,7 +121,10 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
const idx = module.functionIndex(entry) orelse return error.EntryNotFound; const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
const f = module.functions[idx]; const f = module.functions[idx];
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound; for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel }; var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
defer if (options.output) |o| {
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
};
// Instantiation (spec 05 §10.2): every capability parameter gets exactly // Instantiation (spec 05 §10.2): every capability parameter gets exactly
// one grant of its kind, and every grant names a parameter. // one grant of its kind, and every grant names a parameter.
@@ -129,6 +154,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
.value => |v| .{ .returned = v }, .value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t }, .trap => |t| .{ .trapped = t },
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } }, .limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
.blocked => |l| .{ .blocked = l },
}; };
} }
@@ -168,7 +194,7 @@ fn kindOf(e: TrapError) TrapKind {
}; };
} }
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded }; const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location };
const Machine = struct { const Machine = struct {
arena: std.mem.Allocator, arena: std.mem.Allocator,
@@ -177,6 +203,7 @@ const Machine = struct {
fuel: ?u64, fuel: ?u64,
/// Host authority table; capabilities index into it. /// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty, authorities: std.ArrayList(Authority) = .empty,
world: world_mod.World,
/// Instructions executed so far. /// Instructions executed so far.
steps: u64 = 0, steps: u64 = 0,
@@ -211,6 +238,8 @@ const Machine = struct {
} }, } },
.nested_trap => |t| return .{ .trap = t }, .nested_trap => |t| return .{ .trap = t },
.limit_exceeded => return .limit_exceeded, .limit_exceeded => return .limit_exceeded,
.blocked => return .{ .blocked = .{ .function = f.name, .block = b.name, .inst = @intCast(ii) } },
.nested_blocked => |l| return .{ .blocked = l },
} }
} else unreachable; // verified blocks end with a terminator } else unreachable; // verified blocks end with a terminator
} }
@@ -224,6 +253,8 @@ const Machine = struct {
/// A trap raised inside a callee, already located. /// A trap raised inside a callee, already located.
nested_trap: Trap, nested_trap: Trap,
limit_exceeded, limit_exceeded,
blocked,
nested_blocked: Location,
}; };
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step { fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -291,6 +322,7 @@ const Machine = struct {
}, },
.trap => |t| return .{ .nested_trap = t }, .trap => |t| return .{ .nested_trap = t },
.limit_exceeded => return .limit_exceeded, .limit_exceeded => return .limit_exceeded,
.blocked => |l| return .{ .nested_blocked = l },
} }
}, },
.br => |t| return m.jump(f, vals, t), .br => |t| return m.jump(f, vals, t),
@@ -314,7 +346,8 @@ const Machine = struct {
}, },
// No narrowing form is registered yet, so verified AIR contains // No narrowing form is registered yet, so verified AIR contains
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008). // no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
.cap_narrow => unreachable, .cap_narrow => |x| return m.narrow(f, vals, x),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit }, .trap => return .{ .trap = .explicit },
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst), .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
@@ -388,6 +421,143 @@ const Machine = struct {
}; };
} }
// ------------------------------------------------------------ authority and I/O (spec 05 §10–§11, spec 06 §6)
fn output(m: *Machine) !Output {
const keys = try m.arena.dupe([]const u8, m.world.written.keys());
std.mem.sort([]const u8, keys, {}, struct {
fn lt(_: void, a: []const u8, b: []const u8) bool {
return std.mem.lessThan(u8, a, b);
}
}.lt);
const files = try m.arena.alloc(struct { []const u8, []const u8 }, keys.len);
for (keys, files) |k, *out| out.* = .{ k, m.world.files.get(k).?.items };
return .{ .stdout = m.world.stdout.items, .stderr = m.world.stderr.items, .files = files };
}
/// Bytes of a `slice<u8>` value.
fn bytesOf(m: *Machine, v: Value) ![]u8 {
const s = v.slice;
const items = placePtr(s.place).array[s.start..][0..s.len];
const out = try m.arena.alloc(u8, items.len);
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
return out;
}
/// Writes `bytes` into the start of a `slice_mut<u8>` value.
fn fillSlice(v: Value, bytes: []const u8) void {
const s = v.slice;
const items = placePtr(s.place).array[s.start..][0..s.len];
for (bytes, items[0..bytes.len]) |b, *x| x.* = .{ .int = .{ .ty = .u8, .bits = b } };
}
fn resourceOf(v: Value) u32 {
return switch (v) {
.resource => |hd| hd,
.place => |p| p.cell.value.resource,
else => unreachable,
};
}
fn narrow(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "cap_narrow")) !Step {
const a = m.authorities.items[vals[x.cap].cap];
// Only `prefix` is registered (reference/capabilities.md).
const path = try m.bytesOf(vals[x.args[0]]);
const reason: ?u32 = if (!world_mod.World.validPath(path)) 0 else if (!world_mod.World.within(a.scope, path)) 1 else null;
if (reason) |r| {
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
return .{ .jump = x.err };
}
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
return .{ .jump = x.ok };
}
fn intrinsic(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !Step {
const name = air.authority.intrinsics[x.index].name;
const arg = struct {
fn at(v: []Value, xx: @FieldType(air.Op, "intrinsic"), i: usize) Value {
return v[xx.args[i]];
}
}.at;
const W = world_mod.World;
var results: [1]Value = undefined;
var n_results: usize = 0;
var failure: ?world_mod.Error = null;
const is = struct {
fn eq(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
}.eq;
if (is(name, "clock.monotonic")) {
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = m.steps } });
} else if (is(name, "random.fill")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
m.world.fill(buf);
fillSlice(arg(vals, x, 1), buf);
return .next;
} else if (is(name, "io.stdout_write") or is(name, "io.stderr_write")) {
try m.world.writeOut(is(name, "io.stderr_write"), try m.bytesOf(arg(vals, x, 1)));
} else if (is(name, "io.stdin_read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.readIn(buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "fs.open_read") or is(name, "fs.create") or is(name, "fs.open_append")) {
const scope = m.authorities.items[arg(vals, x, 0).cap].scope;
const mode: air.authority.Resource = if (is(name, "fs.open_read")) .file_read else if (is(name, "fs.create")) .file_write else .file_append;
switch (try m.world.open(scope, try m.bytesOf(arg(vals, x, 1)), mode)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
.err => |e| failure = e,
}
} else if (is(name, "fs.read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.fileRead(resourceOf(arg(vals, x, 0)), buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "fs.write_all")) {
try m.world.fileWrite(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
} else if (is(name, "fs.sync")) {
// Durable by construction in the in-memory file system.
} else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) {
m.world.close(arg(vals, x, 0).resource);
} else if (is(name, "net.listen") or is(name, "net.connect")) {
const addr = try m.bytesOf(arg(vals, x, 1));
switch (if (is(name, "net.listen")) try m.world.listen(addr) else try m.world.connect(addr)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
.err => |e| failure = e,
}
} else if (is(name, "net.accept")) {
const s = m.world.accept(resourceOf(arg(vals, x, 0))) orelse return .blocked;
results[0] = .{ .resource = s };
n_results = 1;
} else if (is(name, "net.recv")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.recv(resourceOf(arg(vals, x, 0)), buf) orelse return .blocked;
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "net.send_all")) {
failure = try m.world.send(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
} else unreachable; // every registered intrinsic is handled above
_ = W;
if (failure) |e| {
vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } };
return .{ .jump = x.err.? };
}
for (f.blocks[x.ok.?].params, results[0..n_results]) |p, r| vals[p.value] = r;
return .{ .jump = x.ok.? };
}
fn usize_(v: Value) u64 { fn usize_(v: Value) u64 {
return @truncate(v.int.bits); return @truncate(v.int.bits);
} }
@@ -411,6 +581,12 @@ const Machine = struct {
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)), .local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) { .borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } }, .local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
// A borrowed resource: a place whose cell holds the handle.
.resource => |hd| blk: {
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
},
else => |x| x, else => |x| x,
}), }),
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }), .borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
@@ -611,6 +787,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
}, },
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3). // Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null), .local, .place, .slice => try s.write(null),
.resource => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity. // A capability is opaque: only its kind is shown, never its identity.
.cap => { .cap => {
try s.beginObject(); try s.beginObject();
@@ -653,8 +830,23 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
} }
} }
/// Writes bytes as a JSON string: printable ASCII as is, every other byte
/// as `\u00XX`, so arbitrary output is valid, deterministic JSON.
fn writeBytes(w: *std.Io.Writer, bytes: []const u8) std.Io.Writer.Error!void {
try w.writeByte('"');
for (bytes) |b| switch (b) {
'"' => try w.writeAll("\\\""),
'\\' => try w.writeAll("\\\\"),
'\n' => try w.writeAll("\\n"),
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try w.writeByte(b),
else => try w.print("\\u{x:0>4}", .{b}),
};
try w.writeByte('"');
}
/// Writes the run record for `outcome` as one JSON object (no newline). /// Writes the run record for `outcome` as one JSON object (no newline).
pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std.Io.Writer.Error!void { /// `output` is added for modules that declare `capabilities` (spec 07a).
pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.Io.Writer) std.Io.Writer.Error!void {
var s: std.json.Stringify = .{ .writer = w }; var s: std.json.Stringify = .{ .writer = w };
try s.beginObject(); try s.beginObject();
try s.objectField("status"); try s.objectField("status");
@@ -677,6 +869,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.objectField("inst"); try s.objectField("inst");
try s.write(t.inst); try s.write(t.inst);
}, },
.blocked => |l| {
try s.write("blocked");
try s.objectField("kind");
try s.write("no_future_event");
try s.objectField("function");
try s.write(l.function);
try s.objectField("block");
try s.write(l.block);
try s.objectField("inst");
try s.write(l.inst);
},
.not_instantiated => |n| { .not_instantiated => |n| {
try s.write("not_instantiated"); try s.write("not_instantiated");
try s.objectField("reason"); try s.objectField("reason");
@@ -706,6 +909,25 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.write(l.steps); try s.write(l.steps);
}, },
} }
if (out) |o| if (module.declares("capabilities") and outcome != .not_instantiated) {
try s.objectField("stdout");
try s.beginWriteRaw();
try writeBytes(w, o.stdout);
s.endWriteRaw();
try s.objectField("stderr");
try s.beginWriteRaw();
try writeBytes(w, o.stderr);
s.endWriteRaw();
try s.objectField("files");
try s.beginObject();
for (o.files) |file| {
try s.objectField(file[0]);
try s.beginWriteRaw();
try writeBytes(w, file[1]);
s.endWriteRaw();
}
try s.endObject();
};
try s.endObject(); try s.endObject();
} }
@@ -728,7 +950,7 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
} }
const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel }); const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel });
var out: std.Io.Writer.Allocating = .init(arena); var out: std.Io.Writer.Allocating = .init(arena);
try writeOutcome(report.module.?, outcome, &out.writer); try writeOutcome(report.module.?, outcome, null, &out.writer);
try std.testing.expectEqualStrings(expected, out.written()); try std.testing.expectEqualStrings(expected, out.written());
} }
+242
View File
@@ -0,0 +1,242 @@
//! The `deterministic` execution profile (spec 11 §8): captured console,
//! in-memory file system, in-process loopback TCP, logical clock and a
//! seeded PRNG. Every result is a function of the run's inputs.
const std = @import("std");
const air = @import("../air.zig");
const IoError = enum(u32) {
not_found,
permission_denied,
already_exists,
invalid_input,
no_space,
broken_pipe,
connection_refused,
connection_reset,
address_in_use,
address_unavailable,
timed_out,
other,
};
comptime {
// Variant indices must match the built-in enum `io_error`.
for (air.authority.Builtin.io_error.variants(), 0..) |name, i| {
std.debug.assert(std.mem.eql(u8, @tagName(@as(IoError, @fromBackingInt(@intCast(i)))), name));
}
}
pub const Error = IoError;
/// Result of an operation that creates a resource.
pub const Opened = union(enum) { ok: u32, err: IoError };
/// An open resource. Indices are never reused within a run.
pub const Handle = union(enum) {
file: struct { path: []const u8, mode: air.authority.Resource, pos: usize },
listener: struct { addr: []const u8, pending: std.ArrayList(u32) = .empty },
stream: struct { peer: ?u32, inbox: std.ArrayList(u8) = .empty, read_pos: usize = 0, peer_closed: bool = false },
closed,
};
pub const Options = struct {
stdin: []const u8 = "",
/// Initial files: path -> contents.
files: []const struct { []const u8, []const u8 } = &.{},
seed: u64 = 0,
};
pub const World = struct {
arena: std.mem.Allocator,
stdout: std.ArrayList(u8) = .empty,
stderr: std.ArrayList(u8) = .empty,
stdin: []const u8,
stdin_pos: usize = 0,
files: std.StringArrayHashMapUnmanaged(std.ArrayList(u8)) = .empty,
written: std.StringArrayHashMapUnmanaged(void) = .empty,
handles: std.ArrayList(Handle) = .empty,
listeners: std.StringHashMapUnmanaged(u32) = .empty,
/// xoshiro256** seeded by SplitMix64 from `--seed` (spec 11 §8); pinned
/// explicitly so a toolchain upgrade cannot change deterministic output.
prng: std.Random.Xoshiro256,
pub fn init(arena: std.mem.Allocator, o: Options) !World {
var w: World = .{ .arena = arena, .stdin = o.stdin, .prng = .init(o.seed) };
for (o.files) |entry| {
var contents: std.ArrayList(u8) = .empty;
try contents.appendSlice(arena, entry[1]);
try w.files.put(arena, entry[0], contents);
}
return w;
}
fn add(w: *World, h: Handle) !u32 {
try w.handles.append(w.arena, h);
return @intCast(w.handles.items.len - 1);
}
// ------------------------------------------------------------ paths
/// Absolute, no empty, `.` or `..` components (reference/intrinsics.md).
pub fn validPath(path: []const u8) bool {
if (path.len == 0 or path[0] != '/') return false;
if (path.len == 1) return true;
var it = std.mem.splitScalar(u8, path[1..], '/');
while (it.next()) |part| {
if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
}
return true;
}
/// Whether `path` lies within `scope` (null scope = whole file system).
pub fn within(scope: ?[]const u8, path: []const u8) bool {
const s = scope orelse return true;
if (std.mem.eql(u8, s, "/")) return true;
if (!std.mem.startsWith(u8, path, s)) return false;
return path.len == s.len or path[s.len] == '/';
}
// ------------------------------------------------------------ console
pub fn writeOut(w: *World, err_stream: bool, bytes: []const u8) !void {
try (if (err_stream) &w.stderr else &w.stdout).appendSlice(w.arena, bytes);
}
pub fn readIn(w: *World, buf: []u8) usize {
const n = @min(buf.len, w.stdin.len - w.stdin_pos);
@memcpy(buf[0..n], w.stdin[w.stdin_pos..][0..n]);
w.stdin_pos += n;
return n;
}
// ------------------------------------------------------------ files
pub fn open(w: *World, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !Opened {
if (!validPath(path)) return .{ .err = .invalid_input };
if (!within(scope, path)) return .{ .err = .permission_denied };
const owned = try w.arena.dupe(u8, path);
switch (mode) {
.file_read => if (!w.files.contains(owned)) return .{ .err = .not_found },
.file_write => {
try w.files.put(w.arena, owned, .empty);
try w.written.put(w.arena, owned, {});
},
.file_append => {
if (!w.files.contains(owned)) try w.files.put(w.arena, owned, .empty);
try w.written.put(w.arena, owned, {});
},
else => unreachable,
}
return .{ .ok = try w.add(.{ .file = .{ .path = owned, .mode = mode, .pos = 0 } }) };
}
pub fn fileRead(w: *World, h: u32, buf: []u8) usize {
const f = &w.handles.items[h].file;
const data = w.files.get(f.path).?.items;
const n = @min(buf.len, data.len -| f.pos);
@memcpy(buf[0..n], data[f.pos..][0..n]);
f.pos += n;
return n;
}
pub fn fileWrite(w: *World, h: u32, bytes: []const u8) !void {
const f = &w.handles.items[h].file;
try w.files.getPtr(f.path).?.appendSlice(w.arena, bytes);
}
pub fn close(w: *World, h: u32) void {
switch (w.handles.items[h]) {
.stream => |s| if (s.peer) |p| switch (w.handles.items[p]) {
.stream => |*ps| ps.peer_closed = true,
else => {},
},
.listener => |l| _ = w.listeners.remove(l.addr),
else => {},
}
w.handles.items[h] = .closed;
}
// ------------------------------------------------------------ loopback TCP
/// `host:port` with a numeric IPv4 host.
pub fn validAddr(addr: []const u8) bool {
const colon = std.mem.lastIndexOfScalar(u8, addr, ':') orelse return false;
_ = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return false;
var it = std.mem.splitScalar(u8, addr[0..colon], '.');
var n: usize = 0;
while (it.next()) |part| : (n += 1) {
_ = std.fmt.parseInt(u8, part, 10) catch return false;
}
return n == 4;
}
pub fn listen(w: *World, addr: []const u8) !Opened {
if (!validAddr(addr)) return .{ .err = .invalid_input };
const owned = try w.arena.dupe(u8, addr);
if (w.listeners.contains(owned)) return .{ .err = .address_in_use };
const h = try w.add(.{ .listener = .{ .addr = owned } });
try w.listeners.put(w.arena, owned, h);
return .{ .ok = h };
}
pub fn connect(w: *World, addr: []const u8) !Opened {
if (!validAddr(addr)) return .{ .err = .invalid_input };
const l = w.listeners.get(addr) orelse return .{ .err = .connection_refused };
const client = try w.add(.{ .stream = .{ .peer = null } });
const server = try w.add(.{ .stream = .{ .peer = client } });
w.handles.items[client].stream.peer = server;
try w.handles.items[l].listener.pending.append(w.arena, server);
return .{ .ok = client };
}
/// Null: nothing to accept, and nothing else can ever connect (the run
/// has a single execution unit): the caller reports `blocked`.
pub fn accept(w: *World, h: u32) ?u32 {
const l = &w.handles.items[h].listener;
if (l.pending.items.len == 0) return null;
return l.pending.orderedRemove(0);
}
pub fn send(w: *World, h: u32, bytes: []const u8) !?IoError {
const s = w.handles.items[h].stream;
if (s.peer_closed) return .broken_pipe;
const p = s.peer orelse return .broken_pipe;
try w.handles.items[p].stream.inbox.appendSlice(w.arena, bytes);
return null;
}
/// Null: no data and the peer is open; nothing else can ever send, so
/// the caller reports `blocked`.
pub fn recv(w: *World, h: u32, buf: []u8) ?usize {
const s = &w.handles.items[h].stream;
const avail = s.inbox.items.len - s.read_pos;
if (avail == 0) return if (s.peer_closed) 0 else null;
const n = @min(buf.len, avail);
@memcpy(buf[0..n], s.inbox.items[s.read_pos..][0..n]);
s.read_pos += n;
return n;
}
// ------------------------------------------------------------ random
pub fn fill(w: *World, buf: []u8) void {
w.prng.random().bytes(buf);
}
};
test "paths and scopes" {
try std.testing.expect(World.validPath("/data/a.txt"));
try std.testing.expect(!World.validPath("data/a.txt"));
try std.testing.expect(!World.validPath("/data/../etc"));
try std.testing.expect(!World.validPath("/data//a"));
try std.testing.expect(World.within("/data", "/data/a"));
try std.testing.expect(!World.within("/data", "/database"));
try std.testing.expect(World.within(null, "/x"));
}
test "addresses" {
try std.testing.expect(World.validAddr("127.0.0.1:8080"));
try std.testing.expect(!World.validAddr("localhost:80"));
try std.testing.expect(!World.validAddr("127.0.0.1:99999"));
}
+44 -8
View File
@@ -7,7 +7,8 @@
//! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error, //! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error,
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped, //! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped,
//! 5 execution limit exceeded (`--fuel`, spec 11 §7), //! 5 execution limit exceeded (`--fuel`, spec 11 §7),
//! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2). //! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2),
//! 7 blocked: no future event can complete a wait (spec 11 §8).
const std = @import("std"); const std = @import("std");
const aji = @import("aji"); const aji = @import("aji");
@@ -20,7 +21,10 @@ const usage =
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air> \\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air>
\\ verify, then run @main and print the run record; \\ verify, then run @main and print the run record;
\\ --fuel stops after N executed instructions; \\ --fuel stops after N executed instructions;
\\ --grant binds capability parameter P of @main \\ --grant binds capability parameter P of @main;
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
\\ --seed N; --result-file PATH also writes the record;
\\ --profile hosted is not implemented yet
\\ codes list diagnostic codes as JSON Lines \\ codes list diagnostic codes as JSON Lines
\\ features print supported AIR format, language version and features \\ features print supported AIR format, language version and features
\\ explain <code> show one diagnostic code \\ explain <code> show one diagnostic code
@@ -28,7 +32,7 @@ const usage =
\\ \\
; ;
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6 }; const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6, blocked = 7 };
pub fn main(init: std.process.Init) !void { pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator(); const arena = init.arena.allocator();
@@ -80,16 +84,36 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) { if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
var options: aji.interp.Options = .{}; var options: aji.interp.Options = .{};
var grants: std.ArrayList(aji.interp.Grant) = .empty; var grants: std.ArrayList(aji.interp.Grant) = .empty;
var files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
var result_file: ?[]const u8 = null;
var rest = args[2..]; var rest = args[2..];
while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) { while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) {
if (std.mem.eql(u8, rest[0], "--fuel")) { const flag = rest[0];
options.fuel = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--fuel takes a non-negative integer"); const value = rest[1];
} else if (std.mem.eql(u8, rest[0], "--grant")) { if (std.mem.eql(u8, flag, "--fuel")) {
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]")); options.fuel = std.fmt.parseInt(u64, value, 10) catch return usageError("--fuel takes a non-negative integer");
} else if (std.mem.eql(u8, flag, "--grant")) {
try grants.append(arena, parseGrant(value) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
} else if (std.mem.eql(u8, flag, "--profile")) {
if (std.mem.eql(u8, value, "hosted")) {
std.debug.print("aji: not implemented yet: hosted profile\n", .{});
return .unimplemented;
}
if (!std.mem.eql(u8, value, "deterministic")) return usageError("--profile takes deterministic or hosted");
} else if (std.mem.eql(u8, flag, "--stdin")) {
options.world.stdin = value;
} else if (std.mem.eql(u8, flag, "--vfs")) {
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return usageError("--vfs takes <path>=<text>");
try files.append(arena, .{ value[0..eq], value[eq + 1 ..] });
} else if (std.mem.eql(u8, flag, "--seed")) {
options.world.seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--seed takes a non-negative integer");
} else if (std.mem.eql(u8, flag, "--result-file")) {
result_file = value;
} else break; } else break;
rest = rest[2..]; rest = rest[2..];
} }
options.grants = grants.items; options.grants = grants.items;
options.world.files = files.items;
if (rest.len != 1) return usageError("check and run take exactly one file"); if (rest.len != 1) return usageError("check and run take exactly one file");
const path = rest[0]; const path = rest[0];
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| { const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
@@ -103,18 +127,30 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
} }
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) { if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
const module = report.module.?; const module = report.module.?;
var output: aji.interp.Output = undefined;
options.output = &output;
const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) { const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) {
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"), error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
error.DuplicateGrant => return usageError("a parameter is granted more than once"), error.DuplicateGrant => return usageError("a parameter is granted more than once"),
else => |e| return e, else => |e| return e,
}; };
try aji.interp.writeOutcome(module, outcome, out); try aji.interp.writeOutcome(module, outcome, output, out);
try out.writeByte('\n'); try out.writeByte('\n');
if (result_file) |rpath| {
var rec: std.Io.Writer.Allocating = .init(arena);
try aji.interp.writeOutcome(module, outcome, output, &rec.writer);
try rec.writer.writeByte('\n');
std.Io.Dir.cwd().writeFile(io, .{ .sub_path = rpath, .data = rec.written() }) catch |err| {
std.debug.print("aji: cannot write {s}: {t}\n", .{ rpath, err });
return .usage;
};
}
return switch (outcome) { return switch (outcome) {
.returned => .accepted, .returned => .accepted,
.trapped => .trapped, .trapped => .trapped,
.limit_exceeded => .limit_exceeded, .limit_exceeded => .limit_exceeded,
.not_instantiated => .not_instantiated, .not_instantiated => .not_instantiated,
.blocked => .blocked,
}; };
} }
return switch (report.status) { return switch (report.status) {
+133 -29
View File
@@ -26,6 +26,9 @@ const Seg = union(enum) {
const Mode = enum { shared, exclusive }; const Mode = enum { shared, exclusive };
/// Why a resource is no longer live (spec 06 §6.3).
const Dead = enum { none, closed, moved };
const Info = struct { const Info = struct {
/// Owned borrows are created in this function; lent ones are parameters. /// Owned borrows are created in this function; lent ones are parameters.
owned: bool, owned: bool,
@@ -55,8 +58,10 @@ const Walker = struct {
f: air.Function, f: air.Function,
types: []const air.Type, types: []const air.Type,
info: []?Info, info: []?Info,
/// Live owned borrows in the current block. /// Live owned borrows and live owned resources at the current point.
live: []bool, live: []bool,
/// How a resource stopped being live, for diagnostics.
dead: []Dead,
block: u32 = 0, block: u32 = 0,
index: u32 = 0, index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 }, span: air.Span = .{ .line = 0, .col = 0 },
@@ -107,7 +112,7 @@ const Walker = struct {
fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void { fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void {
for (w.live, 0..) |is_live, cv| { for (w.live, 0..) |is_live, cv| {
if (!is_live) continue; if (!is_live) continue;
const ci = w.info[cv].?; const ci = w.info[cv] orelse continue; // live resources are not borrows
if (ci.root != root) continue; if (ci.root != root) continue;
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue; if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
if (mode == .shared and ci.mode == .shared) continue; if (mode == .shared and ci.mode == .shared) continue;
@@ -157,6 +162,32 @@ const Walker = struct {
fn isLocal(w: *Walker, v: ValueId) bool { fn isLocal(w: *Walker, v: ValueId) bool {
return w.types[v] == .local; return w.types[v] == .local;
} }
fn isResource(w: *Walker, v: ValueId) bool {
return w.types[v] == .resource;
}
/// A non-consuming use of resource `v` (a borrow of it).
fn resourceUsable(w: *Walker, v: ValueId) !bool {
if (w.live[v]) return true;
switch (w.dead[v]) {
.closed => try w.report("E3001", "resource used after it was closed", v, null),
.moved => try w.report("E2001", "resource used after its ownership was transferred", v, null),
.none => try w.report("E3001", "resource used before it is owned", v, null),
}
return false;
}
/// Consumes resource `v` by closing or by transfer (spec 06 §6.2).
fn consume(w: *Walker, v: ValueId, how: Dead) !void {
if (!w.live[v]) {
return w.report("E2002", "resource consumed twice", v, null);
}
// Consumption is an exclusive access to the whole resource.
try w.access(v, &.{}, .exclusive, null, v);
w.live[v] = false;
w.dead[v] = how;
}
}; };
pub fn overlap(a: []const Seg, b: []const Seg) bool { pub fn overlap(a: []const Seg, b: []const Seg) bool {
@@ -177,6 +208,35 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool {
return true; // one path is a prefix of the other return true; // one path is a prefix of the other
} }
const Edge = struct { target: u32, args: []const ValueId };
fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void {
switch (op) {
.br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }),
.cbr => |x| {
try out.append(arena, .{ .target = x.then.block, .args = x.then.args });
try out.append(arena, .{ .target = x.@"else".block, .args = x.@"else".args });
},
.@"switch" => |x| {
for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args });
try out.append(arena, .{ .target = x.default.block, .args = x.default.args });
},
.enum_switch => |x| {
for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} });
if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args });
},
.cap_narrow => |x| {
try out.append(arena, .{ .target = x.ok, .args = &.{} });
try out.append(arena, .{ .target = x.err, .args = &.{} });
},
.intrinsic => |x| if (x.ok) |ok| {
try out.append(arena, .{ .target = ok, .args = &.{} });
try out.append(arena, .{ .target = x.err.?, .args = &.{} });
},
else => {},
}
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var w: Walker = .{ var w: Walker = .{
.c = c, .c = c,
@@ -184,18 +244,22 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
.types = types, .types = types,
.info = try c.arena.alloc(?Info, f.values.len), .info = try c.arena.alloc(?Info, f.values.len),
.live = try c.arena.alloc(bool, f.values.len), .live = try c.arena.alloc(bool, f.values.len),
.dead = try c.arena.alloc(Dead, f.values.len),
}; };
@memset(w.info, null); @memset(w.info, null);
@memset(w.live, false); @memset(w.live, false);
for (f.params) |p| if (p.ty.isBorrow()) { @memset(w.dead, .none);
w.info[p.value] = .{ for (f.params) |p| {
if (p.ty.isBorrow()) w.info[p.value] = .{
.owned = false, .owned = false,
.mode = if (p.ty.isMutBorrow()) .exclusive else .shared, .mode = if (p.ty.isMutBorrow()) .exclusive else .shared,
.root = p.value, .root = p.value,
.path = &.{}, .path = &.{},
.parent = null, .parent = null,
}; };
}; // Resource parameters were moved in: the function owns them (spec 06 §6.3).
if (p.ty == .resource) w.live[p.value] = true;
}
const dom = try ssa.dominators(c.arena, f); const dom = try ssa.dominators(c.arena, f);
const entry_state = try c.arena.alloc(?[]bool, f.blocks.len); const entry_state = try c.arena.alloc(?[]bool, f.blocks.len);
@@ -204,33 +268,51 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var reported_join = try c.arena.alloc(bool, f.blocks.len); var reported_join = try c.arena.alloc(bool, f.blocks.len);
@memset(reported_join, false); @memset(reported_join, false);
var succ: std.ArrayList(u32) = .empty; var out: std.ArrayList(Edge) = .empty;
for (dom.rpo) |b| { for (dom.rpo) |b| {
@memcpy(w.live, entry_state[b].?); @memcpy(w.live, entry_state[b].?);
w.block = b;
const blk = f.blocks[b]; const blk = f.blocks[b];
// Resource block parameters own their argument from here on.
for (blk.params) |p| if (p.ty == .resource) {
w.live[p.value] = true;
w.dead[p.value] = .none;
};
w.block = b;
for (blk.insts, 0..) |inst, ii| { for (blk.insts, 0..) |inst, ii| {
w.index = @intCast(ii); w.index = @intCast(ii);
w.span = inst.span; w.span = inst.span;
try step(&w, inst); try step(&w, inst);
} }
// Propagate the exit state along every edge (§11.4). // Propagate along every edge; branch arguments of resource type are
succ.clearRetainingCapacity(); // moved on their own edge only (§11.4, spec 06 §6.2).
try air.successors(blk.insts[blk.insts.len - 1].op, &succ, c.arena); out.clearRetainingCapacity();
for (succ.items) |s| { try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena);
if (entry_state[s]) |expected| { const base = try c.arena.dupe(bool, w.live);
if (!std.mem.eql(bool, expected, w.live) and !reported_join[s]) { const base_dead = try c.arena.dupe(Dead, w.dead);
reported_join[s] = true; for (out.items) |e| {
@memcpy(w.live, base);
@memcpy(w.dead, base_dead);
for (e.args) |a| if (types[a] == .resource) try w.consume(a, .moved);
// A resource parameter of the target that is still live on this
// edge would be overwritten: that instance leaks.
for (f.blocks[e.target].params) |p| if (p.ty == .resource) {
if (w.live[p.value]) try w.report("E3002", "resource not consumed before it is redefined", p.value, null);
w.live[p.value] = false;
};
if (entry_state[e.target]) |expected| {
if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) {
reported_join[e.target] = true;
for (expected, w.live, 0..) |a, x, v| if (a != x) { for (expected, w.live, 0..) |a, x, v| if (a != x) {
try c.report("E2105", f.blocks[s].span, "borrow state differs between edges into this block", &.{ const is_res = types[v] == .resource;
try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{
.{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[s].name } }, .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } }, .{ .name = if (is_res) "resource" else "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
}); });
break; break;
}; };
} }
} else entry_state[s] = try c.arena.dupe(bool, w.live); } else entry_state[e.target] = try c.arena.dupe(bool, w.live);
} }
} }
} }
@@ -245,6 +327,13 @@ fn step(w: *Walker, inst: air.Inst) !void {
const r = inst.result.?; const r = inst.result.?;
if (w.isLocal(x)) { if (w.isLocal(x)) {
try w.create(r, null, x, &.{}); try w.create(r, null, x, &.{});
} else if (w.isResource(x)) {
if (!try w.resourceUsable(x)) {
w.info[r] = .{ .owned = true, .mode = .shared, .root = x, .path = &.{}, .parent = null };
w.live[r] = true;
return;
}
try w.create(r, null, x, &.{});
} else try w.derive(r, x, null); } else try w.derive(r, x, null);
}, },
.borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }), .borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }),
@@ -270,12 +359,29 @@ fn step(w: *Walker, inst: air.Inst) !void {
// Ended even when rejected, so one mistake yields one diagnostic. // Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false; defer w.live[v] = false;
for (w.live, 0..) |is_live, cv| { for (w.live, 0..) |is_live, cv| {
if (is_live and w.info[cv].?.parent == v) { if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) {
return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) }); return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) });
} }
} }
}, },
.call => |x| try callStep(w, inst, x.callee, x.args), .call => |x| {
try lendArgs(w, x.args);
const callee = w.c.module.functions[x.callee];
for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved);
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
const a = x.args[p];
if (w.types[a].isBorrow() and w.info[a] != null) try w.derive(inst.result.?, a, .elem);
}
if (inst.result) |r| if (w.isResource(r)) {
w.live[r] = true;
};
},
.intrinsic => |x| {
try lendArgs(w, x.args);
// Closing intrinsics consume on both edges, so before propagation.
for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed);
},
.ret => |v| try retStep(w, v), .ret => |v| try retStep(w, v),
// Values of these instructions are not borrows; any borrow operand // Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage. // here was already rejected by the type stage.
@@ -284,8 +390,9 @@ fn step(w: *Walker, inst: air.Inst) !void {
_ = f; _ = f;
} }
fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId) !void { /// Borrow arguments of a call or intrinsic are lent for its duration and
const callee = w.c.module.functions[callee_index]; /// must not alias each other when one is exclusive (§11.2).
fn lendArgs(w: *Walker, args: []const ValueId) !void {
// Arguments already reported; a conflict involving one of them is the // Arguments already reported; a conflict involving one of them is the
// same mistake and is not reported again. // same mistake and is not reported again.
const reported = try w.c.arena.alloc(bool, args.len); const reported = try w.c.arena.alloc(bool, args.len);
@@ -314,17 +421,12 @@ fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId
} }
} }
} }
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
const a = args[p];
if (!w.types[a].isBorrow() or w.info[a] == null) return;
try w.derive(inst.result.?, a, .elem);
}
} }
fn retStep(w: *Walker, value: ?ValueId) !void { fn retStep(w: *Walker, value: ?ValueId) !void {
const f = w.f; const f = w.f;
var transferred: ?ValueId = null; var transferred: ?ValueId = null;
if (value) |v| if (w.isResource(v)) try w.consume(v, .moved);
if (f.ret_from) |p| { if (f.ret_from) |p| {
const pv = f.params[p].value; const pv = f.params[p].value;
const b = value.?; const b = value.?;
@@ -342,7 +444,9 @@ fn retStep(w: *Walker, value: ?ValueId) !void {
for (w.live, 0..) |is_live, v| { for (w.live, 0..) |is_live, v| {
if (!is_live) continue; if (!is_live) continue;
if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue; if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue;
try w.report("E2105", "borrow not ended before return", @intCast(v), null); if (w.isResource(@intCast(v))) {
try w.report("E3002", "resource not consumed before return", @intCast(v), null);
} else try w.report("E2105", "borrow not ended before return", @intCast(v), null);
} }
} }
+1 -1
View File
@@ -28,7 +28,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
return switch (t) { return switch (t) {
.int => |it| it.bits() / 8, .int => |it| it.bits() / 8,
.bool => 1, .bool => 1,
.ref, .mut, .cap => 8, .ref, .mut, .cap, .resource => 8,
.slice, .slice_mut => 16, .slice, .slice_mut => 16,
.builtin => |b| tagSize(b.variants().len), .builtin => |b| tagSize(b.variants().len),
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null, .array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null,
+6
View File
@@ -77,6 +77,12 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter"); try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, x.err, 1, "cap.narrow `err` target takes exactly one parameter"); try paramCount(c, f, inst.span, x.err, 1, "cap.narrow `err` target takes exactly one parameter");
}, },
// Fallible intrinsics: `ok` takes the registered results, `err` one `io_error`.
.intrinsic => |x| {
const reg = air.authority.intrinsics[x.index];
try paramCount(c, f, inst.span, x.ok.?, reg.results.len, "intrinsic `ok` target parameters do not match its results");
try paramCount(c, f, inst.span, x.err.?, 1, "intrinsic `err` target takes exactly one parameter");
},
.ret, .trap => {}, .ret, .trap => {},
else => unreachable, else => unreachable,
} }
+7
View File
@@ -26,6 +26,13 @@ pub fn check(c: *Context) !void {
}); });
}; };
}, },
.intrinsic => |x| if (air.authority.intrinsics[x.index].effect) |e| {
if (!contains(f.effects, e)) try c.report("E3101", inst.span, "intrinsic effect not declared by the caller", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "intrinsic", .value = .{ .str = air.authority.intrinsics[x.index].name } },
.{ .name = "effect", .value = .{ .str = e } },
});
},
else => {}, else => {},
}; };
} }
+102 -3
View File
@@ -84,7 +84,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
const ok = switch (t) { const ok = switch (t) {
.void, .never => pos == .ret, .void, .never => pos == .ret,
.local => false, .local => false,
.ref, .mut, .slice, .slice_mut => pos != .member, .ref, .mut, .slice, .slice_mut, .resource => pos != .member,
else => true, else => true,
}; };
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{ if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
@@ -182,11 +182,103 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.enum_make => |x| .{ .named = x.decl }, .enum_make => |x| .{ .named = x.decl },
.call => |x| m.functions[x.callee].ret, .call => |x| m.functions[x.callee].ret,
.slice_len => .{ .int = .usize }, .slice_len => .{ .int = .usize },
.intrinsic => |x| blk: {
const reg = air.authority.intrinsics[x.index];
if (reg.fallible or reg.results.len == 0) break :blk .void;
break :blk intrinsicResult(reg.results[0]);
},
.array_splat => |x| x.ty, .array_splat => |x| x.ty,
else => null, else => null,
}; };
} }
pub fn intrinsicResult(r: air.authority.ResultType) Type {
return switch (r) {
.usize => .{ .int = .usize },
.u64 => .{ .int = .u64 },
.resource => |res| .{ .resource = res },
};
}
fn operandText(arena: std.mem.Allocator, o: air.authority.Operand) ![]const u8 {
return switch (o) {
.cap => |k| std.fmt.allocPrint(arena, "cap<{s}>", .{k}),
.bytes => "slice<u8>",
.buffer => "slice_mut<u8>",
.borrowed => |rs| blk: {
var w: std.Io.Writer.Allocating = .init(arena);
for (rs, 0..) |r, i| w.writer.print("{s}mut<{s}>", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory;
break :blk w.written();
},
.consumed => |rs| blk: {
var w: std.Io.Writer.Allocating = .init(arena);
for (rs, 0..) |r, i| w.writer.print("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory;
break :blk w.written();
},
};
}
fn operandMatches(o: air.authority.Operand, t: Type) bool {
return switch (o) {
.cap => t == .cap, // the kind is checked separately (E3201)
.bytes => t == .slice and t.slice.* == .int and t.slice.int == .u8,
.buffer => t == .slice_mut and t.slice_mut.* == .int and t.slice_mut.int == .u8,
.borrowed => |rs| t == .mut and t.mut.* == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.mut.resource) != null,
.consumed => |rs| t == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.resource) != null,
};
}
fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !void {
const f = fc.f;
const span = inst.span;
const reg = air.authority.intrinsics[x.index];
if (reg.fallible != (x.ok != null)) {
return fc.c.report("E1001", span, if (reg.fallible) "intrinsic is fallible: use the `, ok -> @a, err -> @b` form" else "intrinsic is infallible: it has no `ok`/`err` targets", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
});
}
if (x.args.len != reg.operands.len) {
return fc.c.report("E1001", span, "wrong number of intrinsic operands", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
.{ .name = "expected", .value = .{ .int = @intCast(reg.operands.len) } },
.{ .name = "found", .value = .{ .int = @intCast(x.args.len) } },
});
}
for (x.args, reg.operands) |a, o| {
const t = fc.typeOf(a);
if (!operandMatches(o, t)) {
try fc.kindError(span, a, try operandText(fc.c.arena, o));
continue;
}
if (o == .cap and !std.mem.eql(u8, air.authority.kinds[t.cap].name, o.cap)) {
try fc.c.report("E3201", span, "capability of the wrong kind for this intrinsic", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
.{ .name = "expected", .value = .{ .str = o.cap } },
.{ .name = "found", .value = .{ .str = air.authority.kinds[t.cap].name } },
});
}
}
if (x.ok) |ok| {
if (inst.result != null) return fc.c.report("E1001", span, "a fallible intrinsic delivers results to its `ok` block parameters", &.{
.{ .name = "function", .value = .{ .str = f.name } },
});
for (f.blocks[ok].params, reg.results) |p, r| {
const want = intrinsicResult(r);
if (!p.ty.eql(want)) try fc.mismatch(span, try fc.c.valueName(f, p.value), want, p.ty);
}
const e = f.blocks[x.err.?].params[0];
if (!e.ty.eql(.{ .builtin = .io_error })) try fc.mismatch(span, try fc.c.valueName(f, e.value), .{ .builtin = .io_error }, e.ty);
} else if (inst.result != null and reg.results.len == 0) {
try fc.c.report("E1001", span, "intrinsic has no result to bind", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
});
}
}
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type { fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type); const b = try arena.create(Type);
b.* = t; b.* = t;
@@ -215,11 +307,13 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.local_load => if (t == .local) t.local.* else invalid, .local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) { .borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) }, .local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.resource => .{ .ref = try boxed(a, t) },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) }, .slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
else => invalid, else => invalid,
}, },
.borrow_mut => switch (t) { .borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) }, .local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.resource => .{ .mut = try boxed(a, t) },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) }, .slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
else => invalid, else => invalid,
}, },
@@ -322,8 +416,8 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
}); });
}, },
.local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"), .local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"),
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, ref<T>, mut<T>, slice<T> or slice_mut<T>"), .borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, mut<T> or slice_mut<T>"), .borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"), .borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"), .borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"), .load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
@@ -427,6 +521,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
} }
if (x.default) |d| try fc.expectTarget(span, d); if (x.default) |d| try fc.expectTarget(span, d);
}, },
.intrinsic => |x| try checkIntrinsic(fc, inst, x),
.cap_narrow => |x| { .cap_narrow => |x| {
const t = fc.typeOf(x.cap); const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>"); if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
@@ -437,6 +532,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
.{ .name = "kind", .value = .{ .str = air.authority.kinds[t.cap].name } }, .{ .name = "kind", .value = .{ .str = air.authority.kinds[t.cap].name } },
.{ .name = "form", .value = .{ .str = x.form } }, .{ .name = "form", .value = .{ .str = x.form } },
}); });
if (std.mem.eql(u8, x.form, "prefix")) {
if (x.args.len != 1) return fc.c.report("E1001", span, "cap.narrow.prefix takes one path operand", &.{.{ .name = "function", .value = .{ .str = f.name } }});
if (!operandMatches(.bytes, fc.typeOf(x.args[0]))) try fc.kindError(span, x.args[0], "slice<u8>");
}
const ok = f.blocks[x.ok].params[0]; const ok = f.blocks[x.ok].params[0];
if (!ok.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(f, ok.value), t, ok.ty); if (!ok.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(f, ok.value), t, ok.ty);
const err = f.blocks[x.err].params[0]; const err = f.blocks[x.err].params[0];
+6
View File
@@ -24,6 +24,12 @@ Every test starts with a block of `;` lines. Keys:
| `trap` | with `run` | expected trap code, e.g. `T0003` | | `trap` | with `run` | expected trap code, e.g. `T0003` |
| `not_instantiated` | with `run` | expected `reason` of a `not_instantiated` record (spec 05 §10.2) | | `not_instantiated` | with `run` | expected `reason` of a `not_instantiated` record (spec 05 §10.2) |
| `grant` | no, repeatable | `<parameter>=<kind>[:<scope>]` binding for a capability parameter of `@main` | | `grant` | no, repeatable | `<parameter>=<kind>[:<scope>]` binding for a capability parameter of `@main` |
| `blocked` | with `run` | the run must end with the environment outcome `blocked` |
| `stdin` | no | input for `io.stdin_read`; escapes `\n`, `\t`, `\\`, `\xHH` |
| `vfs` | no, repeatable | `<path>=<text>`: initial file in the deterministic file system (same escapes) |
| `seed` | no | seed of the deterministic random source |
| `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 | | `fuel` | no | instruction limit for `run` tests (spec 11 §7.1); default 1 000 000. Running out is a `FAIL`, never a pass |
| `phase` | yes | implementation phase number | | `phase` | yes | implementation phase number |
| `spec` | yes | spec section that justifies the expectation | | `spec` | yes | spec section that justifies the expectation |
@@ -0,0 +1,23 @@
; A failed close still consumes the file; closing again is a double consume.
; expect: reject E2002
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.close_twice_after_error
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
intrinsic fs.close(%f), ok -> @closed, err -> @retry
closed:
ret
retry(%e2: io_error):
intrinsic fs.close(%f), ok -> @closed, err -> @gone
gone(%e3: io_error):
ret
fail(%e: io_error):
ret
@@ -0,0 +1,24 @@
; The file is closed while a borrow of it is live.
; expect: reject E2101
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.close_while_borrowed
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
%m = borrow.mut %f
intrinsic fs.close(%f), ok -> @closed, err -> @cfail
closed:
borrow.end %m
ret
cfail(%e2: io_error):
borrow.end %m
ret
fail(%e: io_error):
ret
@@ -0,0 +1,22 @@
; Resources are linear and cannot be copied.
; expect: reject E1001
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.copy_resource
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
%g = copy %f
intrinsic fs.close(%f), ok -> @x, err -> @xf
x:
ret
xf(%e2: io_error):
ret
fail(%e: io_error):
ret
@@ -0,0 +1,14 @@
; fs.open_read is fallible and needs ok/err targets.
; expect: reject E1001
; phase: 2
; spec: docs/reference/intrinsics.md
module test.fallible_without_targets
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p)
ret
@@ -0,0 +1,19 @@
; The caller does not declare the effect of the intrinsic.
; expect: reject E3101
; phase: 2
; spec: docs/reference/intrinsics.md
module test.intrinsic_effect
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects []
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
intrinsic fs.close(%f), ok -> @x, err -> @fail
x:
ret
fail(%e: io_error):
ret
@@ -0,0 +1,17 @@
; The ok target of fs.open_read takes exactly one parameter.
; expect: reject E5002
; phase: 2
; spec: docs/reference/intrinsics.md
module test.ok_arity
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened:
ret
fail(%e: io_error):
ret
@@ -0,0 +1,15 @@
; Resources in aggregates need the reserved feature linear_aggregates.
; expect: reject E0006
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.resource_in_struct
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
type @Log = struct { f: file<append> }
fn @f() -> void
effects []
entry:
ret
@@ -0,0 +1,25 @@
; The file is closed on one path into the join but still owned on the other.
; expect: reject E3002
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.resource_join_mismatch
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>, %b: bool) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
cbr %b, @close(), @keep()
close:
intrinsic fs.close(%f), ok -> @join, err -> @cf
keep:
br @join()
join:
trap
cf(%e2: io_error):
trap
fail(%e: io_error):
ret
@@ -0,0 +1,17 @@
; The opened file is never closed.
; expect: reject E3002
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.resource_leak
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
ret
fail(%e: io_error):
ret
@@ -0,0 +1,23 @@
; The file is borrowed after it was closed.
; expect: reject E3001
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.use_after_close
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
intrinsic fs.close(%f), ok -> @closed, err -> @cfail
closed:
%m = borrow.mut %f
borrow.end %m
ret
cfail(%e2: io_error):
ret
fail(%e: io_error):
ret
@@ -1,16 +1,29 @@
; %p is moved into %q and then used again. ; The file is moved into a callee and then borrowed.
; expect: reject E2001 ; expect: reject E2001
; phase: 2 ; phase: 2
; spec: docs/spec/03-memory-model.md ; spec: docs/spec/06-resources-and-errors.md
module test.use_after_move module test.use_after_move
air 0 air 0
lang 0.1 lang 0.1
features [capabilities, effects, heap, ownership] features [arrays, capabilities, effects, ownership, resources]
fn @f(%p: Own<u64>) -> Own<u64>
effects []
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry: entry:
%q = move %p intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
%r = move %p opened(%f: file<read>):
ret %r call @take(%f)
%m = borrow.mut %f
borrow.end %m
ret
fail(%e: io_error):
ret
fn @take(%f: file<read>) -> void
effects []
entry:
intrinsic fs.close(%f), ok -> @a, err -> @b
a:
ret
b(%e: io_error):
ret
@@ -0,0 +1,19 @@
; fs.create needs cap<fs.write>, not cap<fs.read>.
; expect: reject E3201
; phase: 2
; spec: docs/reference/intrinsics.md
module test.wrong_capability_kind
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.write]
entry:
intrinsic fs.create(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<write>):
intrinsic fs.close(%f), ok -> @x, err -> @fail
x:
ret
fail(%e: io_error):
ret
@@ -0,0 +1,28 @@
; Writing through a file opened for reading is rejected by the verifier.
; expect: reject E1001
; phase: 2
; spec: docs/spec/06-resources-and-errors.md
module test.wrong_file_mode
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @f(%c: cap<fs.read>, %p: slice<u8>) -> void
effects [fs.read]
entry:
intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail
opened(%f: file<read>):
%m = borrow.mut %f
intrinsic fs.write_all(%m, %p), ok -> @w, err -> @wf
w:
borrow.end %m
intrinsic fs.close(%f), ok -> @x, err -> @xf
x:
ret
xf(%e3: io_error):
ret
wf(%e2: io_error):
borrow.end %m
intrinsic fs.close(%f), ok -> @x, err -> @xf
fail(%e: io_error):
ret
@@ -0,0 +1,85 @@
; accept with no pending connection and no other execution unit: the run is blocked, not an io_error.
; expect: run
; grant: listen=net.listen
; blocked: no_future_event
; phase: 2
; spec: docs/spec/11-determinism-and-replay.md
module test.accept_blocks
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%listen: cap<net.listen>) -> void
effects [net.listen]
entry:
%addr = local.alloc array<u8, 11>
local.zero %addr
%addr_m = borrow.mut %addr
%addr_i0 = const.usize 0
%addr_c0 = const.u8 49
%addr_e0 = borrow.index %addr_m, %addr_i0
store %addr_e0, %addr_c0
borrow.end %addr_e0
%addr_i1 = const.usize 1
%addr_c1 = const.u8 50
%addr_e1 = borrow.index %addr_m, %addr_i1
store %addr_e1, %addr_c1
borrow.end %addr_e1
%addr_i2 = const.usize 2
%addr_c2 = const.u8 55
%addr_e2 = borrow.index %addr_m, %addr_i2
store %addr_e2, %addr_c2
borrow.end %addr_e2
%addr_i3 = const.usize 3
%addr_c3 = const.u8 46
%addr_e3 = borrow.index %addr_m, %addr_i3
store %addr_e3, %addr_c3
borrow.end %addr_e3
%addr_i4 = const.usize 4
%addr_c4 = const.u8 48
%addr_e4 = borrow.index %addr_m, %addr_i4
store %addr_e4, %addr_c4
borrow.end %addr_e4
%addr_i5 = const.usize 5
%addr_c5 = const.u8 46
%addr_e5 = borrow.index %addr_m, %addr_i5
store %addr_e5, %addr_c5
borrow.end %addr_e5
%addr_i6 = const.usize 6
%addr_c6 = const.u8 48
%addr_e6 = borrow.index %addr_m, %addr_i6
store %addr_e6, %addr_c6
borrow.end %addr_e6
%addr_i7 = const.usize 7
%addr_c7 = const.u8 46
%addr_e7 = borrow.index %addr_m, %addr_i7
store %addr_e7, %addr_c7
borrow.end %addr_e7
%addr_i8 = const.usize 8
%addr_c8 = const.u8 49
%addr_e8 = borrow.index %addr_m, %addr_i8
store %addr_e8, %addr_c8
borrow.end %addr_e8
%addr_i9 = const.usize 9
%addr_c9 = const.u8 58
%addr_e9 = borrow.index %addr_m, %addr_i9
store %addr_e9, %addr_c9
borrow.end %addr_e9
%addr_i10 = const.usize 10
%addr_c10 = const.u8 57
%addr_e10 = borrow.index %addr_m, %addr_i10
store %addr_e10, %addr_c10
borrow.end %addr_e10
borrow.end %addr_m
%addr_r = borrow.ref %addr
%addr_s = slice.make %addr_r
intrinsic net.listen(%listen, %addr_s), ok -> @listening, err -> @fail
listening(%l: listener):
%lm = borrow.mut %l
intrinsic net.accept(%lm), ok -> @accepted, err -> @fail2
accepted(%s: stream):
trap
fail(%e: io_error):
trap
fail2(%e2: io_error):
trap
@@ -0,0 +1,37 @@
; stdin is read from the run inputs and echoed to stdout.
; expect: run
; grant: in=io.read
; grant: out=io.write
; stdin: echo me
; result: null
; stdout: echo me
; phase: 2
; spec: docs/reference/intrinsics.md
module test.echo_stdin
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%in: cap<io.read>, %out: cap<io.write>) -> void
effects [io.read, io.write]
entry:
%b = local.alloc array<u8, 16>
local.zero %b
%m = borrow.mut %b
%s = slice.make %m
intrinsic io.stdin_read(%in, %s), ok -> @got, err -> @fail
got(%n: usize):
%z = const.usize 0
%part = slice.sub %s, %z, %n
%pr = borrow.ref %part
intrinsic io.stdout_write(%out, %pr), ok -> @done, err -> @fail2
done:
borrow.end %pr
borrow.end %part
borrow.end %s
borrow.end %m
ret
fail(%e: io_error):
trap
fail2(%e2: io_error):
trap
+205
View File
@@ -0,0 +1,205 @@
; Phase 2 exit program: copy /in/data.txt to /out/copy.txt through scoped capabilities.
; 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
; phase: 2
; spec: docs/reference/intrinsics.md
module test.file_copy
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:
%ip = local.alloc array<u8, 12>
local.zero %ip
%ip_m = borrow.mut %ip
%ip_i0 = const.usize 0
%ip_c0 = const.u8 47
%ip_e0 = borrow.index %ip_m, %ip_i0
store %ip_e0, %ip_c0
borrow.end %ip_e0
%ip_i1 = const.usize 1
%ip_c1 = const.u8 105
%ip_e1 = borrow.index %ip_m, %ip_i1
store %ip_e1, %ip_c1
borrow.end %ip_e1
%ip_i2 = const.usize 2
%ip_c2 = const.u8 110
%ip_e2 = borrow.index %ip_m, %ip_i2
store %ip_e2, %ip_c2
borrow.end %ip_e2
%ip_i3 = const.usize 3
%ip_c3 = const.u8 47
%ip_e3 = borrow.index %ip_m, %ip_i3
store %ip_e3, %ip_c3
borrow.end %ip_e3
%ip_i4 = const.usize 4
%ip_c4 = const.u8 100
%ip_e4 = borrow.index %ip_m, %ip_i4
store %ip_e4, %ip_c4
borrow.end %ip_e4
%ip_i5 = const.usize 5
%ip_c5 = const.u8 97
%ip_e5 = borrow.index %ip_m, %ip_i5
store %ip_e5, %ip_c5
borrow.end %ip_e5
%ip_i6 = const.usize 6
%ip_c6 = const.u8 116
%ip_e6 = borrow.index %ip_m, %ip_i6
store %ip_e6, %ip_c6
borrow.end %ip_e6
%ip_i7 = const.usize 7
%ip_c7 = const.u8 97
%ip_e7 = borrow.index %ip_m, %ip_i7
store %ip_e7, %ip_c7
borrow.end %ip_e7
%ip_i8 = const.usize 8
%ip_c8 = const.u8 46
%ip_e8 = borrow.index %ip_m, %ip_i8
store %ip_e8, %ip_c8
borrow.end %ip_e8
%ip_i9 = const.usize 9
%ip_c9 = const.u8 116
%ip_e9 = borrow.index %ip_m, %ip_i9
store %ip_e9, %ip_c9
borrow.end %ip_e9
%ip_i10 = const.usize 10
%ip_c10 = const.u8 120
%ip_e10 = borrow.index %ip_m, %ip_i10
store %ip_e10, %ip_c10
borrow.end %ip_e10
%ip_i11 = const.usize 11
%ip_c11 = const.u8 116
%ip_e11 = borrow.index %ip_m, %ip_i11
store %ip_e11, %ip_c11
borrow.end %ip_e11
borrow.end %ip_m
%ip_r = borrow.ref %ip
%ip_s = slice.make %ip_r
%op = local.alloc array<u8, 13>
local.zero %op
%op_m = borrow.mut %op
%op_i0 = const.usize 0
%op_c0 = const.u8 47
%op_e0 = borrow.index %op_m, %op_i0
store %op_e0, %op_c0
borrow.end %op_e0
%op_i1 = const.usize 1
%op_c1 = const.u8 111
%op_e1 = borrow.index %op_m, %op_i1
store %op_e1, %op_c1
borrow.end %op_e1
%op_i2 = const.usize 2
%op_c2 = const.u8 117
%op_e2 = borrow.index %op_m, %op_i2
store %op_e2, %op_c2
borrow.end %op_e2
%op_i3 = const.usize 3
%op_c3 = const.u8 116
%op_e3 = borrow.index %op_m, %op_i3
store %op_e3, %op_c3
borrow.end %op_e3
%op_i4 = const.usize 4
%op_c4 = const.u8 47
%op_e4 = borrow.index %op_m, %op_i4
store %op_e4, %op_c4
borrow.end %op_e4
%op_i5 = const.usize 5
%op_c5 = const.u8 99
%op_e5 = borrow.index %op_m, %op_i5
store %op_e5, %op_c5
borrow.end %op_e5
%op_i6 = const.usize 6
%op_c6 = const.u8 111
%op_e6 = borrow.index %op_m, %op_i6
store %op_e6, %op_c6
borrow.end %op_e6
%op_i7 = const.usize 7
%op_c7 = const.u8 112
%op_e7 = borrow.index %op_m, %op_i7
store %op_e7, %op_c7
borrow.end %op_e7
%op_i8 = const.usize 8
%op_c8 = const.u8 121
%op_e8 = borrow.index %op_m, %op_i8
store %op_e8, %op_c8
borrow.end %op_e8
%op_i9 = const.usize 9
%op_c9 = const.u8 46
%op_e9 = borrow.index %op_m, %op_i9
store %op_e9, %op_c9
borrow.end %op_e9
%op_i10 = const.usize 10
%op_c10 = const.u8 116
%op_e10 = borrow.index %op_m, %op_i10
store %op_e10, %op_c10
borrow.end %op_e10
%op_i11 = const.usize 11
%op_c11 = const.u8 120
%op_e11 = borrow.index %op_m, %op_i11
store %op_e11, %op_c11
borrow.end %op_e11
%op_i12 = const.usize 12
%op_c12 = const.u8 116
%op_e12 = borrow.index %op_m, %op_i12
store %op_e12, %op_c12
borrow.end %op_e12
borrow.end %op_m
%op_r = borrow.ref %op
%op_s = slice.make %op_r
%buf = local.alloc array<u8, 4>
local.zero %buf
intrinsic fs.open_read(%src, %ip_s), ok -> @opened_in, err -> @fail
opened_in(%in: file<read>):
intrinsic fs.create(%dst, %op_s), ok -> @opened_out, err -> @fail_in
opened_out(%out: file<write>):
%bm = borrow.mut %buf
%bs = slice.make %bm
%fi = borrow.mut %in
%fo = borrow.mut %out
br @loop()
loop:
intrinsic fs.read(%fi, %bs), ok -> @got, err -> @fail_loop
got(%n: usize):
%z = const.usize 0
%eof = eq.usize %n, %z
cbr %eof, @finish(), @write()
write:
%chunk = slice.sub %bs, %z, %n
%cr = borrow.ref %chunk
intrinsic fs.write_all(%fo, %cr), ok -> @wrote, err -> @fail_write
wrote:
borrow.end %cr
borrow.end %chunk
br @loop()
finish:
borrow.end %fo
borrow.end %fi
borrow.end %bs
borrow.end %bm
intrinsic fs.close(%in), ok -> @closed_in, err -> @fail_close_in
closed_in:
intrinsic fs.close(%out), ok -> @done, err -> @fail_close_out
done:
borrow.end %op_s
borrow.end %op_r
borrow.end %ip_s
borrow.end %ip_r
ret
fail(%e: io_error):
trap
fail_in(%e2: io_error):
trap
fail_loop(%e3: io_error):
trap
fail_write(%e4: io_error):
trap
fail_close_in(%e5: io_error):
trap
fail_close_out(%e6: io_error):
trap
+83
View File
@@ -0,0 +1,83 @@
; Hello world: the first Aji program that writes to stdout.
; expect: run
; grant: out=io.write
; result: null
; stdout: hello, aji\n
; phase: 2
; spec: docs/reference/intrinsics.md
module test.hello
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%out: cap<io.write>) -> void
effects [io.write]
entry:
%msg = local.alloc array<u8, 11>
local.zero %msg
%msg_m = borrow.mut %msg
%msg_i0 = const.usize 0
%msg_c0 = const.u8 104
%msg_e0 = borrow.index %msg_m, %msg_i0
store %msg_e0, %msg_c0
borrow.end %msg_e0
%msg_i1 = const.usize 1
%msg_c1 = const.u8 101
%msg_e1 = borrow.index %msg_m, %msg_i1
store %msg_e1, %msg_c1
borrow.end %msg_e1
%msg_i2 = const.usize 2
%msg_c2 = const.u8 108
%msg_e2 = borrow.index %msg_m, %msg_i2
store %msg_e2, %msg_c2
borrow.end %msg_e2
%msg_i3 = const.usize 3
%msg_c3 = const.u8 108
%msg_e3 = borrow.index %msg_m, %msg_i3
store %msg_e3, %msg_c3
borrow.end %msg_e3
%msg_i4 = const.usize 4
%msg_c4 = const.u8 111
%msg_e4 = borrow.index %msg_m, %msg_i4
store %msg_e4, %msg_c4
borrow.end %msg_e4
%msg_i5 = const.usize 5
%msg_c5 = const.u8 44
%msg_e5 = borrow.index %msg_m, %msg_i5
store %msg_e5, %msg_c5
borrow.end %msg_e5
%msg_i6 = const.usize 6
%msg_c6 = const.u8 32
%msg_e6 = borrow.index %msg_m, %msg_i6
store %msg_e6, %msg_c6
borrow.end %msg_e6
%msg_i7 = const.usize 7
%msg_c7 = const.u8 97
%msg_e7 = borrow.index %msg_m, %msg_i7
store %msg_e7, %msg_c7
borrow.end %msg_e7
%msg_i8 = const.usize 8
%msg_c8 = const.u8 106
%msg_e8 = borrow.index %msg_m, %msg_i8
store %msg_e8, %msg_c8
borrow.end %msg_e8
%msg_i9 = const.usize 9
%msg_c9 = const.u8 105
%msg_e9 = borrow.index %msg_m, %msg_i9
store %msg_e9, %msg_c9
borrow.end %msg_e9
%msg_i10 = const.usize 10
%msg_c10 = const.u8 10
%msg_e10 = borrow.index %msg_m, %msg_i10
store %msg_e10, %msg_c10
borrow.end %msg_e10
borrow.end %msg_m
%msg_r = borrow.ref %msg
%msg_s = slice.make %msg_r
intrinsic io.stdout_write(%out, %msg_s), ok -> @done, err -> @failed
done:
borrow.end %msg_s
borrow.end %msg_r
ret
failed(%e: io_error):
trap
@@ -0,0 +1,99 @@
; cap.narrow.prefix to /data/../etc under scope /data.
; expect: run
; grant: fs=fs.read:/data
; result: 1
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.narrow_invalid
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%fs: cap<fs.read>) -> u8
effects []
entry:
%p = local.alloc array<u8, 12>
local.zero %p
%p_m = borrow.mut %p
%p_i0 = const.usize 0
%p_c0 = const.u8 47
%p_e0 = borrow.index %p_m, %p_i0
store %p_e0, %p_c0
borrow.end %p_e0
%p_i1 = const.usize 1
%p_c1 = const.u8 100
%p_e1 = borrow.index %p_m, %p_i1
store %p_e1, %p_c1
borrow.end %p_e1
%p_i2 = const.usize 2
%p_c2 = const.u8 97
%p_e2 = borrow.index %p_m, %p_i2
store %p_e2, %p_c2
borrow.end %p_e2
%p_i3 = const.usize 3
%p_c3 = const.u8 116
%p_e3 = borrow.index %p_m, %p_i3
store %p_e3, %p_c3
borrow.end %p_e3
%p_i4 = const.usize 4
%p_c4 = const.u8 97
%p_e4 = borrow.index %p_m, %p_i4
store %p_e4, %p_c4
borrow.end %p_e4
%p_i5 = const.usize 5
%p_c5 = const.u8 47
%p_e5 = borrow.index %p_m, %p_i5
store %p_e5, %p_c5
borrow.end %p_e5
%p_i6 = const.usize 6
%p_c6 = const.u8 46
%p_e6 = borrow.index %p_m, %p_i6
store %p_e6, %p_c6
borrow.end %p_e6
%p_i7 = const.usize 7
%p_c7 = const.u8 46
%p_e7 = borrow.index %p_m, %p_i7
store %p_e7, %p_c7
borrow.end %p_e7
%p_i8 = const.usize 8
%p_c8 = const.u8 47
%p_e8 = borrow.index %p_m, %p_i8
store %p_e8, %p_c8
borrow.end %p_e8
%p_i9 = const.usize 9
%p_c9 = const.u8 101
%p_e9 = borrow.index %p_m, %p_i9
store %p_e9, %p_c9
borrow.end %p_e9
%p_i10 = const.usize 10
%p_c10 = const.u8 116
%p_e10 = borrow.index %p_m, %p_i10
store %p_e10, %p_c10
borrow.end %p_e10
%p_i11 = const.usize 11
%p_c11 = const.u8 99
%p_e11 = borrow.index %p_m, %p_i11
store %p_e11, %p_c11
borrow.end %p_e11
borrow.end %p_m
%p_r = borrow.ref %p
%p_s = slice.make %p_r
cap.narrow.prefix %fs, %p_s, ok -> @ok, err -> @err
ok(%n: cap<fs.read>):
borrow.end %p_s
borrow.end %p_r
%zero = const.u8 0
ret %zero
err(%e: cap_error):
borrow.end %p_s
borrow.end %p_r
enum.switch cap_error %e, invalid_restriction -> @inv, not_subset -> @ns, unsupported_restriction -> @uns
inv:
%one = const.u8 1
ret %one
ns:
%two = const.u8 2
ret %two
uns:
%three = const.u8 3
ret %three
@@ -0,0 +1,59 @@
; cap.narrow.prefix to /etc under scope /data.
; expect: run
; grant: fs=fs.read:/data
; result: 2
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.narrow_not_subset
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%fs: cap<fs.read>) -> u8
effects []
entry:
%p = local.alloc array<u8, 4>
local.zero %p
%p_m = borrow.mut %p
%p_i0 = const.usize 0
%p_c0 = const.u8 47
%p_e0 = borrow.index %p_m, %p_i0
store %p_e0, %p_c0
borrow.end %p_e0
%p_i1 = const.usize 1
%p_c1 = const.u8 101
%p_e1 = borrow.index %p_m, %p_i1
store %p_e1, %p_c1
borrow.end %p_e1
%p_i2 = const.usize 2
%p_c2 = const.u8 116
%p_e2 = borrow.index %p_m, %p_i2
store %p_e2, %p_c2
borrow.end %p_e2
%p_i3 = const.usize 3
%p_c3 = const.u8 99
%p_e3 = borrow.index %p_m, %p_i3
store %p_e3, %p_c3
borrow.end %p_e3
borrow.end %p_m
%p_r = borrow.ref %p
%p_s = slice.make %p_r
cap.narrow.prefix %fs, %p_s, ok -> @ok, err -> @err
ok(%n: cap<fs.read>):
borrow.end %p_s
borrow.end %p_r
%zero = const.u8 0
ret %zero
err(%e: cap_error):
borrow.end %p_s
borrow.end %p_r
enum.switch cap_error %e, invalid_restriction -> @inv, not_subset -> @ns, unsupported_restriction -> @uns
inv:
%one = const.u8 1
ret %one
ns:
%two = const.u8 2
ret %two
uns:
%three = const.u8 3
ret %three
@@ -0,0 +1,89 @@
; cap.narrow.prefix to /data/logs under scope /data.
; expect: run
; grant: fs=fs.read:/data
; result: 0
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.narrow_ok
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%fs: cap<fs.read>) -> u8
effects []
entry:
%p = local.alloc array<u8, 10>
local.zero %p
%p_m = borrow.mut %p
%p_i0 = const.usize 0
%p_c0 = const.u8 47
%p_e0 = borrow.index %p_m, %p_i0
store %p_e0, %p_c0
borrow.end %p_e0
%p_i1 = const.usize 1
%p_c1 = const.u8 100
%p_e1 = borrow.index %p_m, %p_i1
store %p_e1, %p_c1
borrow.end %p_e1
%p_i2 = const.usize 2
%p_c2 = const.u8 97
%p_e2 = borrow.index %p_m, %p_i2
store %p_e2, %p_c2
borrow.end %p_e2
%p_i3 = const.usize 3
%p_c3 = const.u8 116
%p_e3 = borrow.index %p_m, %p_i3
store %p_e3, %p_c3
borrow.end %p_e3
%p_i4 = const.usize 4
%p_c4 = const.u8 97
%p_e4 = borrow.index %p_m, %p_i4
store %p_e4, %p_c4
borrow.end %p_e4
%p_i5 = const.usize 5
%p_c5 = const.u8 47
%p_e5 = borrow.index %p_m, %p_i5
store %p_e5, %p_c5
borrow.end %p_e5
%p_i6 = const.usize 6
%p_c6 = const.u8 108
%p_e6 = borrow.index %p_m, %p_i6
store %p_e6, %p_c6
borrow.end %p_e6
%p_i7 = const.usize 7
%p_c7 = const.u8 111
%p_e7 = borrow.index %p_m, %p_i7
store %p_e7, %p_c7
borrow.end %p_e7
%p_i8 = const.usize 8
%p_c8 = const.u8 103
%p_e8 = borrow.index %p_m, %p_i8
store %p_e8, %p_c8
borrow.end %p_e8
%p_i9 = const.usize 9
%p_c9 = const.u8 115
%p_e9 = borrow.index %p_m, %p_i9
store %p_e9, %p_c9
borrow.end %p_e9
borrow.end %p_m
%p_r = borrow.ref %p
%p_s = slice.make %p_r
cap.narrow.prefix %fs, %p_s, ok -> @ok, err -> @err
ok(%n: cap<fs.read>):
borrow.end %p_s
borrow.end %p_r
%zero = const.u8 0
ret %zero
err(%e: cap_error):
borrow.end %p_s
borrow.end %p_r
enum.switch cap_error %e, invalid_restriction -> @inv, not_subset -> @ns, unsupported_restriction -> @uns
inv:
%one = const.u8 1
ret %one
ns:
%two = const.u8 2
ret %two
uns:
%three = const.u8 3
ret %three
@@ -0,0 +1,58 @@
; Opening a missing file delivers io_error.not_found to the err target.
; expect: run
; grant: src=fs.read
; result: 1
; phase: 2
; spec: docs/reference/intrinsics.md
module test.open_missing
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%src: cap<fs.read>) -> u8
effects [fs.read]
entry:
%p = local.alloc array<u8, 5>
local.zero %p
%p_m = borrow.mut %p
%p_i0 = const.usize 0
%p_c0 = const.u8 47
%p_e0 = borrow.index %p_m, %p_i0
store %p_e0, %p_c0
borrow.end %p_e0
%p_i1 = const.usize 1
%p_c1 = const.u8 110
%p_e1 = borrow.index %p_m, %p_i1
store %p_e1, %p_c1
borrow.end %p_e1
%p_i2 = const.usize 2
%p_c2 = const.u8 111
%p_e2 = borrow.index %p_m, %p_i2
store %p_e2, %p_c2
borrow.end %p_e2
%p_i3 = const.usize 3
%p_c3 = const.u8 112
%p_e3 = borrow.index %p_m, %p_i3
store %p_e3, %p_c3
borrow.end %p_e3
%p_i4 = const.usize 4
%p_c4 = const.u8 101
%p_e4 = borrow.index %p_m, %p_i4
store %p_e4, %p_c4
borrow.end %p_e4
borrow.end %p_m
%p_r = borrow.ref %p
%p_s = slice.make %p_r
intrinsic fs.open_read(%src, %p_s), ok -> @opened, err -> @failed
opened(%f: file<read>):
trap
failed(%e: io_error):
borrow.end %p_s
borrow.end %p_r
enum.switch io_error %e, not_found -> @nf, default -> @other()
nf:
%one = const.u8 1
ret %one
other:
%two = const.u8 2
ret %two
@@ -0,0 +1,89 @@
; A path outside the capability scope is permission_denied.
; expect: run
; grant: src=fs.read:/data
; vfs: /etc/passwd=root
; result: 1
; phase: 2
; spec: docs/reference/intrinsics.md
module test.outside_scope
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%src: cap<fs.read>) -> u8
effects [fs.read]
entry:
%p = local.alloc array<u8, 11>
local.zero %p
%p_m = borrow.mut %p
%p_i0 = const.usize 0
%p_c0 = const.u8 47
%p_e0 = borrow.index %p_m, %p_i0
store %p_e0, %p_c0
borrow.end %p_e0
%p_i1 = const.usize 1
%p_c1 = const.u8 101
%p_e1 = borrow.index %p_m, %p_i1
store %p_e1, %p_c1
borrow.end %p_e1
%p_i2 = const.usize 2
%p_c2 = const.u8 116
%p_e2 = borrow.index %p_m, %p_i2
store %p_e2, %p_c2
borrow.end %p_e2
%p_i3 = const.usize 3
%p_c3 = const.u8 99
%p_e3 = borrow.index %p_m, %p_i3
store %p_e3, %p_c3
borrow.end %p_e3
%p_i4 = const.usize 4
%p_c4 = const.u8 47
%p_e4 = borrow.index %p_m, %p_i4
store %p_e4, %p_c4
borrow.end %p_e4
%p_i5 = const.usize 5
%p_c5 = const.u8 112
%p_e5 = borrow.index %p_m, %p_i5
store %p_e5, %p_c5
borrow.end %p_e5
%p_i6 = const.usize 6
%p_c6 = const.u8 97
%p_e6 = borrow.index %p_m, %p_i6
store %p_e6, %p_c6
borrow.end %p_e6
%p_i7 = const.usize 7
%p_c7 = const.u8 115
%p_e7 = borrow.index %p_m, %p_i7
store %p_e7, %p_c7
borrow.end %p_e7
%p_i8 = const.usize 8
%p_c8 = const.u8 115
%p_e8 = borrow.index %p_m, %p_i8
store %p_e8, %p_c8
borrow.end %p_e8
%p_i9 = const.usize 9
%p_c9 = const.u8 119
%p_e9 = borrow.index %p_m, %p_i9
store %p_e9, %p_c9
borrow.end %p_e9
%p_i10 = const.usize 10
%p_c10 = const.u8 100
%p_e10 = borrow.index %p_m, %p_i10
store %p_e10, %p_c10
borrow.end %p_e10
borrow.end %p_m
%p_r = borrow.ref %p
%p_s = slice.make %p_r
intrinsic fs.open_read(%src, %p_s), ok -> @opened, err -> @failed
opened(%f: file<read>):
trap
failed(%e: io_error):
borrow.end %p_s
borrow.end %p_r
enum.switch io_error %e, permission_denied -> @denied, default -> @other()
denied:
%one = const.u8 1
ret %one
other:
%two = const.u8 2
ret %two
@@ -0,0 +1,24 @@
; random.fill is deterministic for a given seed.
; expect: run
; grant: rng=random.read
; seed: 7
; result: [61,145,174,42]
; phase: 2
; spec: docs/reference/intrinsics.md
module test.random_seeded
air 0
lang 0.1
features [arrays, capabilities, effects, ownership, resources]
fn @main(%rng: cap<random.read>) -> array<u8, 4>
effects [random.read]
entry:
%b = local.alloc array<u8, 4>
local.zero %b
%m = borrow.mut %b
%s = slice.make %m
intrinsic random.fill(%rng, %s)
borrow.end %s
borrow.end %m
%r = local.load %b
ret %r
+171
View File
@@ -0,0 +1,171 @@
; Phase 2 exit program: TCP echo over the deterministic loopback.
; expect: run
; grant: listen=net.listen
; grant: connect=net.connect
; result: [112,105,110,103]
; phase: 2
; spec: docs/reference/intrinsics.md
module test.tcp_echo
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:
%addr = local.alloc array<u8, 11>
local.zero %addr
%addr_m = borrow.mut %addr
%addr_i0 = const.usize 0
%addr_c0 = const.u8 49
%addr_e0 = borrow.index %addr_m, %addr_i0
store %addr_e0, %addr_c0
borrow.end %addr_e0
%addr_i1 = const.usize 1
%addr_c1 = const.u8 50
%addr_e1 = borrow.index %addr_m, %addr_i1
store %addr_e1, %addr_c1
borrow.end %addr_e1
%addr_i2 = const.usize 2
%addr_c2 = const.u8 55
%addr_e2 = borrow.index %addr_m, %addr_i2
store %addr_e2, %addr_c2
borrow.end %addr_e2
%addr_i3 = const.usize 3
%addr_c3 = const.u8 46
%addr_e3 = borrow.index %addr_m, %addr_i3
store %addr_e3, %addr_c3
borrow.end %addr_e3
%addr_i4 = const.usize 4
%addr_c4 = const.u8 48
%addr_e4 = borrow.index %addr_m, %addr_i4
store %addr_e4, %addr_c4
borrow.end %addr_e4
%addr_i5 = const.usize 5
%addr_c5 = const.u8 46
%addr_e5 = borrow.index %addr_m, %addr_i5
store %addr_e5, %addr_c5
borrow.end %addr_e5
%addr_i6 = const.usize 6
%addr_c6 = const.u8 48
%addr_e6 = borrow.index %addr_m, %addr_i6
store %addr_e6, %addr_c6
borrow.end %addr_e6
%addr_i7 = const.usize 7
%addr_c7 = const.u8 46
%addr_e7 = borrow.index %addr_m, %addr_i7
store %addr_e7, %addr_c7
borrow.end %addr_e7
%addr_i8 = const.usize 8
%addr_c8 = const.u8 49
%addr_e8 = borrow.index %addr_m, %addr_i8
store %addr_e8, %addr_c8
borrow.end %addr_e8
%addr_i9 = const.usize 9
%addr_c9 = const.u8 58
%addr_e9 = borrow.index %addr_m, %addr_i9
store %addr_e9, %addr_c9
borrow.end %addr_e9
%addr_i10 = const.usize 10
%addr_c10 = const.u8 55
%addr_e10 = borrow.index %addr_m, %addr_i10
store %addr_e10, %addr_c10
borrow.end %addr_e10
borrow.end %addr_m
%addr_r = borrow.ref %addr
%addr_s = slice.make %addr_r
%ping = local.alloc array<u8, 4>
local.zero %ping
%ping_m = borrow.mut %ping
%ping_i0 = const.usize 0
%ping_c0 = const.u8 112
%ping_e0 = borrow.index %ping_m, %ping_i0
store %ping_e0, %ping_c0
borrow.end %ping_e0
%ping_i1 = const.usize 1
%ping_c1 = const.u8 105
%ping_e1 = borrow.index %ping_m, %ping_i1
store %ping_e1, %ping_c1
borrow.end %ping_e1
%ping_i2 = const.usize 2
%ping_c2 = const.u8 110
%ping_e2 = borrow.index %ping_m, %ping_i2
store %ping_e2, %ping_c2
borrow.end %ping_e2
%ping_i3 = const.usize 3
%ping_c3 = const.u8 103
%ping_e3 = borrow.index %ping_m, %ping_i3
store %ping_e3, %ping_c3
borrow.end %ping_e3
borrow.end %ping_m
%ping_r = borrow.ref %ping
%ping_s = slice.make %ping_r
%buf = local.alloc array<u8, 4>
local.zero %buf
%back = local.alloc array<u8, 4>
local.zero %back
intrinsic net.listen(%listen, %addr_s), ok -> @listening, err -> @fail
listening(%l: listener):
intrinsic net.connect(%connect, %addr_s), ok -> @connected, err -> @fail1
connected(%client: stream):
%lm = borrow.mut %l
intrinsic net.accept(%lm), ok -> @accepted, err -> @fail2
accepted(%server: stream):
borrow.end %lm
%cm = borrow.mut %client
intrinsic net.send_all(%cm, %ping_s), ok -> @sent, err -> @fail3
sent:
%sm = borrow.mut %server
%bm = borrow.mut %buf
%bs = slice.make %bm
intrinsic net.recv(%sm, %bs), ok -> @received, err -> @fail4
received(%n: usize):
%z = const.usize 0
%got = slice.sub %bs, %z, %n
%gr = borrow.ref %got
intrinsic net.send_all(%sm, %gr), ok -> @echoed, err -> @fail5
echoed:
borrow.end %gr
borrow.end %got
borrow.end %bs
borrow.end %bm
borrow.end %sm
%km = borrow.mut %back
%ks = slice.make %km
intrinsic net.recv(%cm, %ks), ok -> @answer, err -> @fail6
answer(%m: usize):
borrow.end %ks
borrow.end %km
borrow.end %cm
intrinsic net.close_stream(%server), ok -> @c1, err -> @fail7
c1:
intrinsic net.close_stream(%client), ok -> @c2, err -> @fail8
c2:
intrinsic net.close_listener(%l), ok -> @c3, err -> @fail9
c3:
borrow.end %ping_s
borrow.end %ping_r
borrow.end %addr_s
borrow.end %addr_r
%r = local.load %back
ret %r
fail(%e0: io_error):
trap
fail1(%e1: io_error):
trap
fail2(%e2: io_error):
trap
fail3(%e3: io_error):
trap
fail4(%e4: io_error):
trap
fail5(%e5: io_error):
trap
fail6(%e6: io_error):
trap
fail7(%e7: io_error):
trap
fail8(%e8: io_error):
trap
fail9(%e9: io_error):
trap
+77 -2
View File
@@ -22,6 +22,8 @@ const Expect = union(enum) {
trap: []const u8, trap: []const u8,
/// Expected `reason` of a `not_instantiated` record. /// Expected `reason` of a `not_instantiated` record.
not_instantiated: []const u8, not_instantiated: []const u8,
/// Expected `blocked` outcome (spec 11 §8).
blocked,
}; };
}; };
@@ -35,6 +37,11 @@ const Header = struct {
expect: Expect, expect: Expect,
fuel: u64, fuel: u64,
grants: []const aji.interp.Grant, grants: []const aji.interp.Grant,
world: aji.interp.WorldOptions,
/// Expected captured output and written files (all optional).
stdout: ?[]const u8,
stderr: ?[]const u8,
files: []const struct { []const u8, []const u8 },
phase: u8, phase: u8,
spec: []const u8, spec: []const u8,
}; };
@@ -164,14 +171,15 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul
fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header) !Result { fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header) !Result {
var records: [2][]const u8 = undefined; var records: [2][]const u8 = undefined;
var outcome: aji.interp.Outcome = undefined; var outcome: aji.interp.Outcome = undefined;
var output: aji.interp.Output = undefined;
for (&records) |*rec| { for (&records) |*rec| {
outcome = aji.interp.run(arena, module, "main", .{ .fuel = header.fuel, .grants = header.grants }) catch |err| switch (err) { outcome = aji.interp.run(arena, module, "main", .{ .fuel = header.fuel, .grants = header.grants, .world = header.world, .output = &output }) catch |err| switch (err) {
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" }, error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" },
error.DuplicateGrant => return .{ .outcome = .fail, .detail = "a parameter is granted more than once" }, error.DuplicateGrant => return .{ .outcome = .fail, .detail = "a parameter is granted more than once" },
else => |e| return e, else => |e| return e,
}; };
var w: std.Io.Writer.Allocating = .init(arena); var w: std.Io.Writer.Allocating = .init(arena);
try aji.interp.writeOutcome(module, outcome, &w.writer); try aji.interp.writeOutcome(module, outcome, output, &w.writer);
rec.* = w.written(); rec.* = w.written();
} }
if (!std.mem.eql(u8, records[0], records[1])) if (!std.mem.eql(u8, records[0], records[1]))
@@ -181,7 +189,21 @@ fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run,
.trap => |code| outcome == .trapped and std.mem.eql(u8, outcome.trapped.code.id, code), .trap => |code| outcome == .trapped and std.mem.eql(u8, outcome.trapped.code.id, code),
.result => |json| outcome == .returned and std.mem.eql(u8, json, try valueJson(arena, module, outcome.returned)), .result => |json| outcome == .returned and std.mem.eql(u8, json, try valueJson(arena, module, outcome.returned)),
.not_instantiated => |reason| outcome == .not_instantiated and std.mem.eql(u8, outcome.not_instantiated.reason, reason), .not_instantiated => |reason| outcome == .not_instantiated and std.mem.eql(u8, outcome.not_instantiated.reason, reason),
.blocked => outcome == .blocked,
}; };
if (ok) {
if (header.stdout) |expected| if (!std.mem.eql(u8, expected, output.stdout))
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "stdout differs: {s}", .{records[0]}) };
if (header.stderr) |expected| if (!std.mem.eql(u8, expected, output.stderr))
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "stderr differs: {s}", .{records[0]}) };
for (header.files) |expected| {
const got = for (output.files) |f| {
if (std.mem.eql(u8, f[0], expected[0])) break f[1];
} else null;
if (got == null or !std.mem.eql(u8, got.?, expected[1]))
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "file {s} differs: {s}", .{ expected[0], records[0] }) };
}
}
if (ok) return .{ .outcome = .pass }; if (ok) return .{ .outcome = .pass };
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "got {s}", .{records[0]}) }; return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "got {s}", .{records[0]}) };
} }
@@ -211,6 +233,31 @@ fn unsupportedFeature(source: []const u8) ?[]const u8 {
return null; return null;
} }
/// Header values are single lines: `\n`, `\t`, `\\` and `\xHH` escapes.
fn unescape(arena: std.mem.Allocator, s: []const u8) ![]const u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) : (i += 1) {
if (s[i] != '\\' or i + 1 == s.len) {
try out.append(arena, s[i]);
continue;
}
i += 1;
switch (s[i]) {
'n' => try out.append(arena, '\n'),
't' => try out.append(arena, '\t'),
'\\' => try out.append(arena, '\\'),
'x' => {
if (i + 2 >= s.len) return error.BadExpect;
try out.append(arena, std.fmt.parseInt(u8, s[i + 1 .. i + 3], 16) catch return error.BadExpect);
i += 2;
},
else => return error.BadExpect,
}
}
return out.items;
}
fn isKey(s: []const u8) bool { fn isKey(s: []const u8) bool {
if (s.len == 0) return false; if (s.len == 0) return false;
for (s) |ch| if (!std.ascii.isLower(ch) and ch != '_') return false; for (s) |ch| if (!std.ascii.isLower(ch) and ch != '_') return false;
@@ -238,6 +285,7 @@ fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void {
.result => |j| try w.print("run returning {s}", .{j}), .result => |j| try w.print("run returning {s}", .{j}),
.trap => |c| try w.print("run trapping {s}", .{c}), .trap => |c| try w.print("run trapping {s}", .{c}),
.not_instantiated => |reason| try w.print("not_instantiated ({s})", .{reason}), .not_instantiated => |reason| try w.print("not_instantiated ({s})", .{reason}),
.blocked => try w.writeAll("blocked"),
}, },
} }
} }
@@ -250,6 +298,11 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
var phase: ?u8 = null; var phase: ?u8 = null;
var fuel: u64 = default_fuel; var fuel: u64 = default_fuel;
var grants: std.ArrayList(aji.interp.Grant) = .empty; var grants: std.ArrayList(aji.interp.Grant) = .empty;
var world: aji.interp.WorldOptions = .{};
var vfs: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
var want_files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
var want_stdout: ?[]const u8 = null;
var want_stderr: ?[]const u8 = null;
var spec: ?[]const u8 = null; var spec: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, source, '\n'); var lines = std.mem.splitScalar(u8, source, '\n');
@@ -290,6 +343,21 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
} else if (std.mem.eql(u8, key, "not_instantiated")) { } else if (std.mem.eql(u8, key, "not_instantiated")) {
if (run_result != null) return error.BadExpect; if (run_result != null) return error.BadExpect;
run_result = .{ .not_instantiated = value }; run_result = .{ .not_instantiated = value };
} else if (std.mem.eql(u8, key, "blocked")) {
if (run_result != null) return error.BadExpect;
run_result = .blocked;
} else if (std.mem.eql(u8, key, "stdin")) {
world.stdin = try unescape(arena, value);
} else if (std.mem.eql(u8, key, "seed")) {
world.seed = try std.fmt.parseInt(u64, value, 10);
} else if (std.mem.eql(u8, key, "stdout")) {
want_stdout = try unescape(arena, value);
} else if (std.mem.eql(u8, key, "stderr")) {
want_stderr = try unescape(arena, value);
} else if (std.mem.eql(u8, key, "vfs") or std.mem.eql(u8, key, "file")) {
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadExpect;
const entry: struct { []const u8, []const u8 } = .{ value[0..eq], try unescape(arena, value[eq + 1 ..]) };
try (if (std.mem.eql(u8, key, "vfs")) &vfs else &want_files).append(arena, entry);
} else if (std.mem.eql(u8, key, "grant")) { } else if (std.mem.eql(u8, key, "grant")) {
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadGrant; const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadGrant;
const rest = value[eq + 1 ..]; const rest = value[eq + 1 ..];
@@ -315,6 +383,13 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
.expect = expect orelse return error.MissingExpect, .expect = expect orelse return error.MissingExpect,
.fuel = fuel, .fuel = fuel,
.grants = grants.items, .grants = grants.items,
.world = blk: {
world.files = vfs.items;
break :blk world;
},
.stdout = want_stdout,
.stderr = want_stderr,
.files = want_files.items,
.phase = phase orelse return error.MissingPhase, .phase = phase orelse return error.MissingPhase,
.spec = spec orelse return error.MissingSpec, .spec = spec orelse return error.MissingSpec,
}; };