diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3cc31c..577d8c7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,8 @@ jobs: - run: zig build && python3 tests/hosted/smoke.py - run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air - run: zig build agent-reference + - name: Source construct coverage (Phase 6A) + run: python3 tools/source_coverage.py - name: Evaluation harness self-tests run: cd tools/eval && python3 -m unittest discover tests - name: Agent Reference Bundle tokens (non-blocking) diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index b3abbf3..4b112d8 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -29,7 +29,7 @@ Targets and the evaluation order are in `README.md`. Phase 6A is specified by RF | P6A-4 | doing | Lowering: control flow, variables → SSA/block parameters, frame storage, lexical borrow ends, outcome matches, block forms (`scope`, `shield`, `lock`), `select`, byte literals, feature closure | P6A-3 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function | | P6A-5 | done | Source spans on lowered AIR; verifier diagnostics and trap records carry `source_location` and `air_location` | P6A-4 | `src/frontend/spans.zig`, `src/diag.zig` | every diagnostic of a `.aji` file points at source | | P6A-6 | done | CLI: `aji check/run/lower file.aji` | P6A-4 | `src/main.zig` | same flags and run record as for `.air` | -| P6A-7 | todo | `.aji` twins for the Phase 0–3 conformance tests (same outcome or code) and the reference programs | P6A-5 | `tests/conformance/*/source/` | twins pass; the reference programs in `.aji` pass `--stress` | +| P6A-7 | doing | `.aji` twins for the Phase 0–3 conformance tests (same outcome or code) and the reference programs | P6A-5 | `tests/conformance/source/` | **for the freeze (owner decision):** the three reference programs (`programs/parallel_map`, `channel_transfer`, `tcp_echo_tasks`) pass with AIR equivalence on every schedule seed, and every source construct has a run/accept and, where it rejects, a reject test (`tools/source_coverage.py`, 56/56). Further twins are added gradually | | P6A-8 | done | Source Reference Bundle (directory, `QUICK.md` front door, AIR reference only under `air/`), harness profile `aji_source` with per-group documentation metrics, Quick Reference examples checked against conformance programs, raw and normalized size metrics | P6A-6 | `docs/agent/source-bundle.txt`, `tools/eval/languages/aji_source.json` | bundle measured; every Quick Reference example is an excerpt of a checked program | | P6A-9 | todo | Dev regression on tasks M and C: the frozen `Aji/AIR` runs vs new `Aji/source` runs, same agents (all three native agents) | P6A-8 | results note | criteria below reported | | P6A-10 | todo | Phase 6A exit review | all | plan status | targets reported | diff --git a/tests/conformance/source/layer1/reject/break_outside_loop.aji b/tests/conformance/source/layer1/reject/break_outside_loop.aji new file mode 100644 index 0000000..f5972a7 --- /dev/null +++ b/tests/conformance/source/layer1/reject/break_outside_loop.aji @@ -0,0 +1,12 @@ +// `break` outside a loop has no target. +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.breakoutside + +fn main() -> u64 +effects [] +{ + break; + 0 +} diff --git a/tests/conformance/source/layer1/wrapping.aji b/tests/conformance/source/layer1/wrapping.aji new file mode 100644 index 0000000..29ae522 --- /dev/null +++ b/tests/conformance/source/layer1/wrapping.aji @@ -0,0 +1,16 @@ +// Wrapping arithmetic `+% -% *%` wraps instead of trapping. +// expect: run +// result: 9 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.wrapping + +fn main() -> u8 +effects [] +{ + let a = 250u8; + let b = a +% 10; + let c = b -% 6; + let d = c *% 255; + d -% 249 +} diff --git a/tests/conformance/source/layer7/reject/close_receiver_missing_pending.aji b/tests/conformance/source/layer7/reject/close_receiver_missing_pending.aji new file mode 100644 index 0000000..56e3b08 --- /dev/null +++ b/tests/conformance/source/layer7/reject/close_receiver_missing_pending.aji @@ -0,0 +1,20 @@ +// channel.close_receiver can hand the receiver back on `pending`: the match handles it. +// expect: reject E7004 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.closemissingpending + +fn main(heap: cap) -> u64 +effects [mem.alloc] +{ + match channel.make(1, heap) { + ok(tx, rx) => { + channel.close_sender(move tx); + match channel.close_receiver(move rx) { + ok => {} + } + 0 + } + err(e) => { trap; } + } +} diff --git a/tests/conformance/source/programs/channel_transfer.aji b/tests/conformance/source/programs/channel_transfer.aji new file mode 100644 index 0000000..69e9a82 --- /dev/null +++ b/tests/conformance/source/programs/channel_transfer.aji @@ -0,0 +1,78 @@ +// Reference program (Phase 3 exit, in source): ownership transfer through a bounded +// channel. The producer allocates each message on the heap and moves the owner into +// the channel; the consumer takes it. The budget (64 bytes) only fits the channel and +// three live messages: bounded capacity bounds memory. 10 + 20 + 30 = 60. +// expect: run +// grant: heap=mem.alloc:64 +// schedules: 30 +// quantum: 2 +// result: 60 +// equivalent: phase3/run/program_channel_transfer.air +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.channeltransfer + +struct Message { + id: u64, + size: u64, +} + +fn producer(tx: sender>, heap: cap) -> u8 +effects [mem.alloc, task.wait] +{ + var id: u64 = 10; + while id != 40 { + let o = own.new(Message { id: id, size: 16 }, heap) or trap; + match channel.send(tx, move o) { + ok => {} + closed(back) => { + own.free(move back); + break; + } + cancelled(back) => { + own.free(move back); + break; + } + } + id = id + 10; + } + channel.close_sender(move tx); + 0 +} + +fn main(heap: cap) -> u64 +effects [mem.alloc, task.spawn, task.wait] +{ + match channel.make>(2, heap) { + ok(tx, rx) => { + var acc: u64 = 0; + scope sc { + let p = task.spawn(sc, producer, move tx, heap); + var r: receiver> = move rx; + loop { + match channel.recv(r) { + ok(o) => { + let msg = own.take(move o); + acc = acc + msg.id; + } + closed => { + match channel.close_receiver(move r) { + ok => { break; } + pending(r) => {} + } + } + cancelled => { + match channel.close_receiver(move r) { + ok => { break; } + pending(r) => {} + } + } + } + } + let x = task.join(move p); + } + acc + } + err(e) => { trap; } + } +} diff --git a/tests/conformance/source/programs/parallel_map.aji b/tests/conformance/source/programs/parallel_map.aji new file mode 100644 index 0000000..cd2907f --- /dev/null +++ b/tests/conformance/source/programs/parallel_map.aji @@ -0,0 +1,50 @@ +// Reference program (Phase 3 exit, in source): parallel map. One buffer is split into +// four disjoint quarters; four tasks square their quarter in place through exclusive +// loans; the parent sums the result after joining. 1² + … + 8² = 204. +// expect: run +// schedules: 30 +// quantum: 3 +// result: 204 +// equivalent: phase3/run/program_parallel_map.air +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.parallelmap + +fn square(q: slice_mut) -> u8 +effects [] +{ + for i in 0..q.len { + q[i] = q[i] * q[i]; + } + 0 +} + +fn main() -> u64 +effects [task.spawn] +{ + var buf: [u64; 8] = zero; + mut s = buf; + for i in 0..s.len { + s[i] = i as! u64 + 1; + } + { + let (l, r) = s.split_at(4); + let (a, b) = l.split_at(2); + let (c, d) = r.split_at(2); + scope sc { + let ta = task.spawn(sc, square, a); + let tb = task.spawn(sc, square, b); + let tc = task.spawn(sc, square, c); + let td = task.spawn(sc, square, d); + task.join(move ta); + task.join(move tb); + task.join(move tc); + task.join(move td); + } + } + var acc: u64 = 0; + for k in 0..s.len { + acc = acc + s[k]; + } + acc +} diff --git a/tests/conformance/source/programs/tcp_echo_tasks.aji b/tests/conformance/source/programs/tcp_echo_tasks.aji new file mode 100644 index 0000000..0ade34a --- /dev/null +++ b/tests/conformance/source/programs/tcp_echo_tasks.aji @@ -0,0 +1,78 @@ +// Reference program (Phase 3 exit, in source): TCP echo with tasks over the +// deterministic loopback. A server task accepts two connections and spawns one echo +// task per connection; two client tasks share the address and the message through +// shared loans. The bytes echoed to both clients: 2 × (112+105+110+103) = 860. +// expect: run +// grant: listen=net.listen +// grant: connect=net.connect +// schedules: 30 +// quantum: 5 +// result: 860 +// equivalent: phase3/run/program_tcp_echo_tasks.air +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.tcpechotasks + +// Receives up to 4 bytes and sends them back, then closes the stream. +fn echo(s: stream) -> u8 +effects [net.read, net.write] +{ + var buf: [u8; 4] = zero; + let n = net.recv(s, mut buf) or trap; + net.send_all(s, ref buf[0..n]) or trap; + net.close_stream(move s) or trap; + 0 +} + +// Accepts two connections; each is moved into its own echo task. +fn serve(l: listener) -> u8 +effects [net.listen, net.read, net.write, task.spawn] +{ + scope sc { + let s1 = net.accept(l) or trap; + let t1 = task.spawn(sc, echo, move s1); + let s2 = net.accept(l) or trap; + let t2 = task.spawn(sc, echo, move s2); + task.join(move t1); + task.join(move t2); + } + net.close_listener(move l) or trap; + 0 +} + +// Connects, sends the message, and returns the sum of the bytes echoed back. +fn client(connect: cap, addr: slice, msg: slice) -> u64 +effects [net.connect, net.read, net.write] +{ + var back: [u8; 4] = zero; + let c = net.connect(connect, addr) or trap; + net.send_all(c, msg) or trap; + let n = net.recv(c, mut back) or trap; + net.close_stream(move c) or trap; + var acc: u64 = 0; + for i in 0..n { + acc = acc + back[i] as u64; + } + acc +} + +fn main(listen: cap, connect: cap) -> u64 +effects [net.listen, net.connect, net.read, net.write, task.spawn] +{ + let addr_bytes = b"127.0.0.1:7"; + let ping_bytes = b"ping"; + ref addr = addr_bytes; + ref ping = ping_bytes; + let l = net.listen(listen, addr) or trap; + var sum: u64 = 0; + scope sc { + let srv = task.spawn(sc, serve, move l); + let c1 = task.spawn(sc, client, connect, addr, ping); + let c2 = task.spawn(sc, client, connect, addr, ping); + task.join(move srv); + let a = task.join(move c1); + let b = task.join(move c2); + sum = a + b; + } + sum +} diff --git a/tools/source_coverage.py b/tools/source_coverage.py new file mode 100644 index 0000000..9715859 --- /dev/null +++ b/tools/source_coverage.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Source construct coverage (Phase 6A freeze criterion). + +Every construct of `.aji` 0.1 (spec 15) must appear in at least one `.aji` +conformance test that is accepted or run, and, where the construct has +rules that reject programs, in at least one reject test. The checklist is +below; each construct is a regular expression over the test's source (header +comments removed). + + python3 tools/source_coverage.py # table; exit 1 if a row fails +""" + +import glob +import os +import re +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TESTS = os.path.join(ROOT, "tests", "conformance", "source") + +# (area, construct, regex, needs a reject test) +CHECKLIST = [ + ("scalars", "checked arithmetic", r"[^%]\+ [a-z0-9]", False), + ("scalars", "wrapping arithmetic `+%`", r"\+%", False), + ("scalars", "`as` (lossless widening)", r"\bas [ui]\d", True), + ("scalars", "`as!` (checked conversion)", r"\bas! ", False), + ("scalars", "`as%` (wrapping conversion)", r"\bas% ", False), + ("scalars", "bitwise and shifts", r"<<|>>| & | \^ ", False), + ("control flow", "`let`", r"\blet ", False), + ("control flow", "`var`", r"\bvar ", False), + ("control flow", "assignment", r"^\s*[a-z_][a-z0-9_]* = ", False), + ("control flow", "`if`/`else`", r"\bif .*\{.*\belse\b|\} else \{", False), + ("control flow", "`while`", r"\bwhile ", False), + ("control flow", "`for … in a..b`", r"\bfor \w+ in ", False), + ("control flow", "`loop`", r"\bloop \{", False), + ("control flow", "`break` / `continue`", r"\bbreak;|\bcontinue;", True), + ("control flow", "`return`", r"\breturn\b", True), + ("control flow", "`assert`", r"\bassert\(", False), + ("struct/enum/match", "struct declaration and literal", r"\bstruct \w+ \{", True), + ("struct/enum/match", "enum declaration and `Enum::Variant`", r"\w+::\w+", True), + ("struct/enum/match", "enum `match`", r"match .*\{[^}]*\w+::\w+", True), + ("struct/enum/match", "integer `match` with `_`", r"\b_ =>", True), + ("struct/enum/match", "`match` as an expression", r"= match ", False), + ("arrays/slices", "`[e; N]`", r"\[[^\]]+; \d+\]", False), + ("arrays/slices", "indexing `s[i]`", r"\w\[[a-z0-9_]+\]", True), + ("arrays/slices", "ranges `s[a..b]`", r"\[[^\]]*\.\.[^\]]*\]", False), + ("arrays/slices", "`split_at`", r"\.split_at\(", False), + ("arrays/slices", "`slice.copy`", r"slice\.copy\(", True), + ("arrays/slices", "byte strings", r'b"', False), + ("borrow/move", "`ref r = …;` / `mut r = …;`", r"^\s*(ref|mut) \w+ = ", True), + ("borrow/move", "`ref`/`mut` arguments", r"\((ref|mut) \w+|, (ref|mut) \w+", True), + ("borrow/move", "`*r` load and store", r"\*\w+ = |= \*\w+", True), + ("borrow/move", "`move`", r"\bmove \w+", True), + ("own/region", "`own.new` / `own.take` / `own.free`", r"own\.(new|take|free)\(", True), + ("own/region", "`own.array`", r"own\.array\(", False), + ("own/region", "regions", r"region\.(create|new|array|reset|destroy)\(", True), + ("own/region", "`cap.narrow.budget`", r"cap\.narrow\.budget\(", False), + ("failure", "outcome `match`", r"\bok\(\w*\)? =>|\bok =>", True), + ("failure", "`or trap`", r"\bor trap\b", False), + ("failure", "built-in error enums", r"(alloc_error|io_error|cap_error)::", False), + ("resources/I/O", "stdin/stdout", r"io\.(stdin_read|stdout_write)\(", True), + ("resources/I/O", "files", r"fs\.(open_read|create|read|write_all|close)\(", True), + ("resources/I/O", "TCP", r"net\.(listen|connect|accept|recv|send_all)\(", False), + ("resources/I/O", "`clock`/`random`", r"(clock\.monotonic|random\.fill)\(", True), + ("resources/I/O", "`cap.narrow.prefix`", r"cap\.narrow\.prefix\(", False), + ("tasks/channels", "`scope` and `task.spawn`/`join`", r"\bscope \w+ \{", True), + ("tasks/channels", "`task.cancel` / `task.cancelled`", r"task\.cancel(led)?\(", False), + ("tasks/channels", "`channel.make` / `send` / `recv`", r"channel\.(make|send|recv)", True), + ("tasks/channels", "`channel.dup`", r"channel\.dup\(", False), + ("tasks/channels", "`close_receiver` and `pending`", r"close_receiver\(", True), + ("mutex/select", "`lock … cancelled`", r"\block ref \w+ as \w+", True), + ("mutex/select", "`mutex.make` / `mutex.take`", r"mutex\.(make|take)\(", True), + ("mutex/select", "`select`", r"\bselect \{", True), + ("cancellation", "`shield`", r"\bshield \{", False), + ("cancellation", "`task.check_cancel`", r"task\.check_cancel\(", False), + ("cancellation", "`task.join_cancel`", r"task\.join_cancel\(", True), + ("unsafe", "`ref unchecked` / `assume`", r"\bunchecked\b|\bassume\(", True), + ("unsafe", "`trusted` rejected", r"\btrusted\b", True), +] + + +def load(): + runs, rejects = [], [] + for path in sorted(glob.glob(os.path.join(TESTS, "**", "*.aji"), recursive=True)): + with open(path, encoding="utf-8") as f: + text = f.read() + m = re.search(r"^// expect: (\w+)", text, re.M) + if not m: + continue + body = "\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//")) + (rejects if m.group(1) == "reject" else runs).append((os.path.relpath(path, TESTS), body)) + return runs, rejects + + +def main(): + runs, rejects = load() + failed = 0 + print("| area | construct | run/accept tests | reject tests | status |") + print("|---|---|---:|---:|---|") + for area, name, rx, need_reject in CHECKLIST: + pat = re.compile(rx, re.M) + nr = sum(1 for _, b in runs if pat.search(b)) + nj = sum(1 for _, b in rejects if pat.search(b)) + ok = nr > 0 and (nj > 0 or not need_reject) + if name == "`trusted` rejected": + ok = nj > 0 + failed += not ok + print(f"| {area} | {name} | {nr} | {nj}{'' if need_reject else ' (not required)'} | {'covered' if ok else 'MISSING'} |") + print(f"\n{len(CHECKLIST) - failed}/{len(CHECKLIST)} constructs covered " + f"({len(runs)} run/accept and {len(rejects)} reject `.aji` tests)") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main()