Phase 2: manifest grants (P2-9) and exit review (P2-12)
- src/manifest.zig: strict aji.toml subset ([package], [capabilities], [metadata]); errors with line numbers - aji run --manifest: entry relative to the manifest, manifest grants replaced per parameter by --grant; usage error on manifest problems - examples/packages/hello as a runnable package, checked in CI - implemented_phase = 2; Phase 2 exit review; README and AGENTS updated
This commit is contained in:
1 parent
0948eb7347
commit
778d563182
10 files changed
+332
-15
No files matched your search
@@ -19,3 +19,4 @@ jobs:
|
|||||||
- run: zig build test --summary all
|
- run: zig build test --summary all
|
||||||
- run: zig build conformance
|
- run: zig build conformance
|
||||||
- run: zig build && python3 tests/hosted/smoke.py
|
- run: zig build && python3 tests/hosted/smoke.py
|
||||||
|
- run: zig-out/bin/aji run --manifest examples/packages/hello/aji.toml | grep -q '"stdout":"hello, aji\\n"'
|
||||||
@@ -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, 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` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `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` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. `aji run --manifest aji.toml` runs a package with the grants its manifest requests (`--grant` replaces one per parameter; spec 12 §1). `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `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
|
||||||
|
|
||||||
|
|||||||
@@ -70,11 +70,12 @@ zig build test # unit tests
|
|||||||
zig build conformance # conformance suite
|
zig build conformance # conformance suite
|
||||||
```
|
```
|
||||||
|
|
||||||
Current state: Phases 0 and 1 are complete. `aji check` parses and verifies text AIR format 0 with the features `ownership` (frame storage, second-class borrows) and `arrays` (arrays, slices, bounds proofs); `aji run` executes it deterministically. Phase 2 (effects, capabilities, heap, regions) is next; see [`docs/plan/README.md`](docs/plan/README.md).
|
Current state: Phases 0–2 are complete. AIR format 0 has frame storage and second-class borrows, arrays and slices with bounds proofs, flat effects and unforgeable capabilities, linear I/O resources (files, TCP), heap owners and regions with allocation budgets, and explicit unsafe boundaries. `aji run` executes programs in a reproducible deterministic world by default and against the real OS with `--profile hosted`. Phase 3 (structured concurrency) is next; see [`docs/plan/README.md`](docs/plan/README.md).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
zig build run -- run tests/conformance/phase0/run/fibonacci.air
|
zig build
|
||||||
# {"status":"returned","value":2880067194370816120}
|
zig-out/bin/aji run --manifest examples/packages/hello/aji.toml
|
||||||
|
# {"status":"returned","value":null,"stdout":"hello, aji\n","stderr":"","files":{}}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Where to start
|
## Where to start
|
||||||
|
|||||||
+3
-2
@@ -99,5 +99,6 @@ 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: RFCs 0006 (effects, capabilities), 0007 (I/O, resources, deterministic profile) and 0008 (heap, regions, budgets) implemented; next unsafe boundaries, hosted profile, audit reports, `aji.toml` grants |
|
| P2 | done (exit review in the phase file) |
|
||||||
| P3–P8 | not started |
|
| P3 | next |
|
||||||
|
| P4–P8 | not started |
|
||||||
@@ -33,11 +33,11 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
|
|||||||
| 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-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 | done | Unsafe boundary verifier (RFC 0009: assume, borrow.index.unchecked, trusted, unsafe report) | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject |
|
| P2-7 | done | Unsafe boundary verifier (RFC 0009: assume, borrow.index.unchecked, trusted, unsafe report) | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject |
|
||||||
| P2-8 | done | 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 | done | 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 | done | Entry-point capability instantiation (`--grant` and `aji run --manifest`, RFC 0010) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) |
|
||||||
| P2-10 | done | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
|
| P2-10 | done | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
|
||||||
| 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-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 | done | 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-8a | done | 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 | done | Phase exit review | all | plan status | exit criterion passes |
|
||||||
|
|
||||||
## Conformance tests to add
|
## Conformance tests to add
|
||||||
|
|
||||||
@@ -46,3 +46,13 @@ Negative corpus entries owned by this phase: missing capability, undeclared effe
|
|||||||
## Remaining order (owner decision)
|
## Remaining order (owner decision)
|
||||||
|
|
||||||
RFC 0008 heap and regions → implementation and conformance → unsafe boundaries (P2-7) → hosted profile (P2-8a) → audit reports (P2-10) → `aji.toml` grants (P2-9). The memory model is completed in the deterministic world before the real OS widens the bug surface.
|
RFC 0008 heap and regions → implementation and conformance → unsafe boundaries (P2-7) → hosted profile (P2-8a) → audit reports (P2-10) → `aji.toml` grants (P2-9). The memory model is completed in the deterministic world before the real OS widens the bug surface.
|
||||||
|
|
||||||
|
## Exit review
|
||||||
|
|
||||||
|
- Exit criterion met: the safe file copy (`phase2/run/file_copy.air`, and `region_file_copy.air` with a 64 KiB region buffer) and the TCP echo (`phase2/run/tcp_echo.air`) run in the deterministic profile; `tests/hosted/smoke.py` runs file copy, scope denial, stdin → stdout and TCP echo against the real OS in CI.
|
||||||
|
- Decision records accepted and integrated: RFC 0006 (effects, capabilities), RFC 0007 (I/O, linear resources, profiles), RFC 0008 (heap, regions, budgets), RFC 0009 (unsafe boundaries), RFC 0010 (manifest grants).
|
||||||
|
- Features published and supported: `effects`, `capabilities`, `resources`, `heap`, `regions`, `unsafe`. Reserved for later: `linear_aggregates`, `resource_joins`, `borrow_joins`, `tasks`, `channels`, `sync`, `atomics`, `islands`.
|
||||||
|
- Conformance: 157 tests across phases 0–2 pass; every Phase 2 code (E3001, E3002, E3101, E3201, E3202, E2001, E2002, E2104, E6001) and trap (T0009) has tests; the PRNG has a golden vector.
|
||||||
|
- Tooling: `aji features`, `aji report` (audit), `aji check --report unsafe`, `aji run --manifest`, `--profile hosted` with `--result-file`.
|
||||||
|
- Fuzzing: mutation runs over each new corpus (resources, heap/regions, unsafe) found no crash.
|
||||||
|
- Known limitations: the hosted profile has been exercised on Linux only (the macOS CI job is configured but not yet observed); Zig 0.17's `net.Stream.read` does not compile and is worked around with `readWithControl`.
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Hello world as a package. Run with:
|
||||||
|
# aji run --manifest examples/packages/hello/aji.toml
|
||||||
|
# The manifest requests io.write for @main's parameter `out`; running it
|
||||||
|
# with --manifest is the operator's decision to grant it (spec 12 §1).
|
||||||
|
|
||||||
|
[package]
|
||||||
|
name = "hello"
|
||||||
|
version = "0.1.0"
|
||||||
|
entry = "main.air"
|
||||||
|
|
||||||
|
[capabilities]
|
||||||
|
out = "io.write"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
module examples.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
|
||||||
+42
-6
@@ -20,10 +20,11 @@ const usage =
|
|||||||
\\ check [--report unsafe] <file.air>
|
\\ check [--report unsafe] <file.air>
|
||||||
\\ parse and verify a text AIR module; the unsafe report
|
\\ parse and verify a text AIR module; the unsafe report
|
||||||
\\ lists trusted boundaries and unsafe operations
|
\\ lists trusted boundaries and unsafe operations
|
||||||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air>
|
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air | --manifest aji.toml>
|
||||||
\\ 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
|
||||||
|
\\ (and replaces the manifest's grant for P);
|
||||||
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
|
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
|
||||||
\\ --seed N; --profile hosted uses the real OS and
|
\\ --seed N; --profile hosted uses the real OS and
|
||||||
\\ writes the record only to --result-file PATH
|
\\ writes the record only to --result-file PATH
|
||||||
@@ -113,7 +114,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
|||||||
unsafe_report = true;
|
unsafe_report = true;
|
||||||
rest = rest[2..];
|
rest = rest[2..];
|
||||||
}
|
}
|
||||||
while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) {
|
var manifest_path: ?[]const u8 = null;
|
||||||
|
while (std.mem.eql(u8, cmd, "run") and rest.len >= 2) {
|
||||||
const flag = rest[0];
|
const flag = rest[0];
|
||||||
const value = rest[1];
|
const value = rest[1];
|
||||||
if (std.mem.eql(u8, flag, "--fuel")) {
|
if (std.mem.eql(u8, flag, "--fuel")) {
|
||||||
@@ -133,13 +135,47 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
|||||||
options.world.seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--seed takes a non-negative integer");
|
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")) {
|
} else if (std.mem.eql(u8, flag, "--result-file")) {
|
||||||
result_file = value;
|
result_file = value;
|
||||||
|
} else if (std.mem.eql(u8, flag, "--manifest")) {
|
||||||
|
manifest_path = value;
|
||||||
} else break;
|
} else break;
|
||||||
rest = rest[2..];
|
rest = rest[2..];
|
||||||
}
|
}
|
||||||
options.grants = grants.items;
|
|
||||||
options.world.files = files.items;
|
options.world.files = files.items;
|
||||||
if (rest.len != 1) return usageError("check and run take exactly one file");
|
var path: []const u8 = undefined;
|
||||||
const path = rest[0];
|
if (manifest_path) |mp| {
|
||||||
|
// spec 12 §1.2: the module is the manifest's entry; its grants
|
||||||
|
// are applied, each replaced by a --grant for the same parameter.
|
||||||
|
if (rest.len != 0) return usageError("a file argument cannot be combined with --manifest");
|
||||||
|
const text = std.Io.Dir.cwd().readFileAlloc(io, mp, arena, .limited(1 << 20)) catch |err| {
|
||||||
|
std.debug.print("aji: cannot read {s}: {t}\n", .{ mp, err });
|
||||||
|
return .usage;
|
||||||
|
};
|
||||||
|
const m = switch (try aji.manifest.parse(arena, text)) {
|
||||||
|
.ok => |m| m,
|
||||||
|
.err => |e| {
|
||||||
|
std.debug.print("aji: manifest {s}:{d}: {s}\n", .{ mp, e.line, e.message });
|
||||||
|
return .usage;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const entry = m.entry orelse {
|
||||||
|
std.debug.print("aji: manifest {s}: [package] entry is required for aji run\n", .{mp});
|
||||||
|
return .usage;
|
||||||
|
};
|
||||||
|
path = try std.fs.path.join(arena, &.{ std.fs.path.dirname(mp) orelse ".", entry });
|
||||||
|
var merged: std.ArrayList(aji.interp.Grant) = .empty;
|
||||||
|
for (m.grants) |g| {
|
||||||
|
const overridden = for (grants.items) |cg| {
|
||||||
|
if (std.mem.eql(u8, cg.parameter, g.parameter)) break true;
|
||||||
|
} else false;
|
||||||
|
if (!overridden) try merged.append(arena, .{ .parameter = g.parameter, .kind = g.kind, .scope = g.scope });
|
||||||
|
}
|
||||||
|
try merged.appendSlice(arena, grants.items);
|
||||||
|
options.grants = merged.items;
|
||||||
|
} else {
|
||||||
|
if (rest.len != 1) return usageError("check and run take exactly one file");
|
||||||
|
path = rest[0];
|
||||||
|
options.grants = grants.items;
|
||||||
|
}
|
||||||
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| {
|
||||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||||
return .usage;
|
return .usage;
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
//! `aji.toml` package manifest (spec 12 §1, RFC 0010).
|
||||||
|
//!
|
||||||
|
//! A strict TOML subset: comments with `#`, `[section]` headers and
|
||||||
|
//! `key = "string"` lines. Unknown sections, unknown keys, duplicate keys
|
||||||
|
//! and anything outside the subset are errors, so a typo cannot silently
|
||||||
|
//! drop or misplace authority.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
pub const Grant = struct { parameter: []const u8, kind: []const u8, scope: ?[]const u8 };
|
||||||
|
|
||||||
|
pub const Manifest = struct {
|
||||||
|
name: []const u8,
|
||||||
|
version: []const u8,
|
||||||
|
entry: ?[]const u8,
|
||||||
|
/// `[capabilities]` in file order.
|
||||||
|
grants: []const Grant,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Error = struct {
|
||||||
|
line: u32,
|
||||||
|
message: []const u8,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Result = union(enum) { ok: Manifest, err: Error };
|
||||||
|
|
||||||
|
fn fail(arena: std.mem.Allocator, line: u32, comptime fmt: []const u8, args: anytype) !Result {
|
||||||
|
return .{ .err = .{ .line = line, .message = try std.fmt.allocPrint(arena, fmt, args) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `kind[:scope]`, the same form as `--grant` after the `=`.
|
||||||
|
pub fn parseGrantValue(parameter: []const u8, value: []const u8) ?Grant {
|
||||||
|
const colon = std.mem.indexOfScalar(u8, value, ':');
|
||||||
|
const g: Grant = .{
|
||||||
|
.parameter = parameter,
|
||||||
|
.kind = if (colon) |c| value[0..c] else value,
|
||||||
|
.scope = if (colon) |c| value[c + 1 ..] else null,
|
||||||
|
};
|
||||||
|
if (g.kind.len == 0) return null;
|
||||||
|
return g;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isKey(s: []const u8) bool {
|
||||||
|
if (s.len == 0) return false;
|
||||||
|
for (s) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '_' and ch != '-') return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||||
|
const Section = enum { none, package, capabilities, metadata };
|
||||||
|
var section: Section = .none;
|
||||||
|
var seen_sections: [3]bool = .{ false, false, false };
|
||||||
|
var name: ?[]const u8 = null;
|
||||||
|
var version: ?[]const u8 = null;
|
||||||
|
var entry: ?[]const u8 = null;
|
||||||
|
var grants: std.ArrayList(Grant) = .empty;
|
||||||
|
var keys: std.StringHashMapUnmanaged(void) = .empty;
|
||||||
|
|
||||||
|
var lines = std.mem.splitScalar(u8, text, '\n');
|
||||||
|
var line_no: u32 = 0;
|
||||||
|
while (lines.next()) |raw| {
|
||||||
|
line_no += 1;
|
||||||
|
const line = std.mem.trim(u8, raw, " \t\r");
|
||||||
|
if (line.len == 0 or line[0] == '#') continue;
|
||||||
|
if (line[0] == '[') {
|
||||||
|
if (line[line.len - 1] != ']') return fail(arena, line_no, "malformed section header", .{});
|
||||||
|
const sname = std.mem.trim(u8, line[1 .. line.len - 1], " ");
|
||||||
|
section = std.meta.stringToEnum(Section, sname) orelse return fail(arena, line_no, "unknown section [{s}]", .{sname});
|
||||||
|
if (section == .none) return fail(arena, line_no, "unknown section [{s}]", .{sname});
|
||||||
|
const idx = @backingInt(section) - 1;
|
||||||
|
if (seen_sections[idx]) return fail(arena, line_no, "duplicate section [{s}]", .{sname});
|
||||||
|
seen_sections[idx] = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const eq = std.mem.indexOfScalar(u8, line, '=') orelse return fail(arena, line_no, "expected key = \"value\"", .{});
|
||||||
|
const key = std.mem.trim(u8, line[0..eq], " \t");
|
||||||
|
if (!isKey(key)) return fail(arena, line_no, "malformed key", .{});
|
||||||
|
const value = (try parseString(arena, std.mem.trim(u8, line[eq + 1 ..], " \t"))) orelse
|
||||||
|
return fail(arena, line_no, "value of {s} must be a string \"...\" (escapes \\\", \\\\, \\n), optionally followed by a # comment", .{key});
|
||||||
|
if (section == .none) return fail(arena, line_no, "key {s} outside a section", .{key});
|
||||||
|
const full = try std.fmt.allocPrint(arena, "{t}.{s}", .{ section, key });
|
||||||
|
const gop = try keys.getOrPut(arena, full);
|
||||||
|
if (gop.found_existing) return fail(arena, line_no, "duplicate key {s}", .{key});
|
||||||
|
switch (section) {
|
||||||
|
.package => {
|
||||||
|
if (std.mem.eql(u8, key, "name")) {
|
||||||
|
name = value;
|
||||||
|
} else if (std.mem.eql(u8, key, "version")) {
|
||||||
|
version = value;
|
||||||
|
} else if (std.mem.eql(u8, key, "entry")) {
|
||||||
|
entry = value;
|
||||||
|
} else return fail(arena, line_no, "unknown key {s} in [package]", .{key});
|
||||||
|
},
|
||||||
|
.capabilities => try grants.append(arena, parseGrantValue(key, value) orelse
|
||||||
|
return fail(arena, line_no, "grant {s} must be \"kind[:scope]\"", .{key})),
|
||||||
|
.metadata => {},
|
||||||
|
.none => unreachable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return .{ .ok = .{
|
||||||
|
.name = name orelse return fail(arena, line_no, "[package] name is required", .{}),
|
||||||
|
.version = version orelse return fail(arena, line_no, "[package] version is required", .{}),
|
||||||
|
.entry = entry,
|
||||||
|
.grants = grants.items,
|
||||||
|
} };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `"..."` with the escapes `\"`, `\\`, `\n`, optionally followed by a comment.
|
||||||
|
fn parseString(arena: std.mem.Allocator, s: []const u8) !?[]const u8 {
|
||||||
|
if (s.len < 2 or s[0] != '"') return null;
|
||||||
|
var out: std.ArrayList(u8) = .empty;
|
||||||
|
var i: usize = 1;
|
||||||
|
while (i < s.len) : (i += 1) {
|
||||||
|
switch (s[i]) {
|
||||||
|
'"' => {
|
||||||
|
const rest = std.mem.trim(u8, s[i + 1 ..], " \t");
|
||||||
|
if (rest.len != 0 and rest[0] != '#') return null;
|
||||||
|
return out.items;
|
||||||
|
},
|
||||||
|
'\\' => {
|
||||||
|
i += 1;
|
||||||
|
if (i >= s.len) return null;
|
||||||
|
try out.append(arena, switch (s[i]) {
|
||||||
|
'"' => '"',
|
||||||
|
'\\' => '\\',
|
||||||
|
'n' => '\n',
|
||||||
|
else => return null,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
else => try out.append(arena, s[i]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expectErr(text: []const u8, line: u32) !void {
|
||||||
|
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||||
|
defer arena_state.deinit();
|
||||||
|
const r = try parse(arena_state.allocator(), text);
|
||||||
|
try std.testing.expect(r == .err);
|
||||||
|
try std.testing.expectEqual(line, r.err.line);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "manifest with grants" {
|
||||||
|
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||||
|
defer arena_state.deinit();
|
||||||
|
const r = try parse(arena_state.allocator(),
|
||||||
|
\\# a package
|
||||||
|
\\[package]
|
||||||
|
\\name = "file-copy"
|
||||||
|
\\version = "0.1.0"
|
||||||
|
\\entry = "src/main.air" # relative to the manifest
|
||||||
|
\\
|
||||||
|
\\[capabilities]
|
||||||
|
\\src = "fs.read:/var/data"
|
||||||
|
\\heap = "mem.alloc:67108864"
|
||||||
|
\\out = "io.write"
|
||||||
|
\\
|
||||||
|
\\[metadata]
|
||||||
|
\\purpose = "example"
|
||||||
|
\\
|
||||||
|
);
|
||||||
|
const m = r.ok;
|
||||||
|
try std.testing.expectEqualStrings("file-copy", m.name);
|
||||||
|
try std.testing.expectEqualStrings("src/main.air", m.entry.?);
|
||||||
|
try std.testing.expectEqual(@as(usize, 3), m.grants.len);
|
||||||
|
try std.testing.expectEqualStrings("fs.read", m.grants[0].kind);
|
||||||
|
try std.testing.expectEqualStrings("/var/data", m.grants[0].scope.?);
|
||||||
|
try std.testing.expect(m.grants[2].scope == null);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "strict parsing" {
|
||||||
|
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\n[capabilites]\n", 4); // typo in section
|
||||||
|
try expectErr("[package]\nname = \"a\"\nnmae = \"b\"\n", 3); // unknown key
|
||||||
|
try expectErr("[package]\nname = \"a\"\nname = \"b\"\n", 3); // duplicate key
|
||||||
|
try expectErr("[package]\nname = \"a\"\nversion = 1\n", 3); // not a string
|
||||||
|
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\n[capabilities]\nout = \":x\"\n", 5); // empty kind
|
||||||
|
try expectErr("[package]\nname = \"a\"\n", 3); // missing version: reported at the end of the file
|
||||||
|
}
|
||||||
+2
-1
@@ -8,7 +8,7 @@ pub const version = "0.0.0-dev";
|
|||||||
|
|
||||||
/// Highest plan phase (docs/plan/README.md) whose features are implemented.
|
/// Highest plan phase (docs/plan/README.md) whose features are implemented.
|
||||||
/// Conformance tests for later phases are reported as PENDING.
|
/// Conformance tests for later phases are reported as PENDING.
|
||||||
pub const implemented_phase: u8 = 1;
|
pub const implemented_phase: u8 = 2;
|
||||||
|
|
||||||
pub const diag = @import("diag.zig");
|
pub const diag = @import("diag.zig");
|
||||||
pub const air = @import("air.zig");
|
pub const air = @import("air.zig");
|
||||||
@@ -16,6 +16,7 @@ pub const verifier = @import("verifier.zig");
|
|||||||
pub const interp = @import("interp.zig");
|
pub const interp = @import("interp.zig");
|
||||||
pub const check = @import("check.zig");
|
pub const check = @import("check.zig");
|
||||||
pub const report = @import("report.zig");
|
pub const report = @import("report.zig");
|
||||||
|
pub const manifest = @import("manifest.zig");
|
||||||
|
|
||||||
test {
|
test {
|
||||||
@import("std").testing.refAllDecls(@This());
|
@import("std").testing.refAllDecls(@This());
|
||||||
|
|||||||
Reference in new issue
Block a user