From 17a55a7fef43715cc7a9ca7638f73ae93eccc619 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 11:59:13 +0300 Subject: [PATCH] Initial import: Aji 0.1 draft spec and Zig scaffolding Draft specification, RFCs, reference registries and examples, plus the reference-implementation skeleton: build.zig, diagnostic envelope with error-code registry synced to docs, aji CLI, conformance runner with seed tests, CI and contributor docs. --- .editorconfig | 15 + .gitattributes | 3 + .github/pull_request_template.md | 22 ++ .github/workflows/ci.yml | 20 ++ .gitignore | 2 + AGENTS.md | 144 ++++++++ CLAUDE.md | 1 + CONTRIBUTING.md | 64 ++++ README.md | 120 +++++++ SPEC.md | 45 +++ aji.toml | 7 + build.zig | 56 +++ build.zig.zon | 14 + docs/README.md | 19 + docs/reference/concurrency-litmus.md | 59 +++ docs/reference/design-decisions.md | 41 +++ docs/reference/error-codes.md | 61 ++++ docs/reference/glossary.md | 23 ++ docs/reference/grammar.ebnf | 51 +++ docs/reference/intrinsics.md | 93 +++++ docs/reference/type-properties.md | 37 ++ docs/rfcs/0000-template.md | 56 +++ .../0001-memory-regions-islands-frozen.md | 110 ++++++ docs/rfcs/0002-structured-concurrency.md | 65 ++++ docs/rfcs/0003-aji-memory-model.md | 61 ++++ docs/rfcs/0004-air-instruction-set.md | 90 +++++ docs/rfcs/README.md | 23 ++ docs/roadmap/conformance-suite.md | 112 ++++++ docs/roadmap/implementation-plan.md | 118 ++++++ docs/roadmap/phase-0.md | 25 ++ docs/spec/00-status-and-conformance.md | 75 ++++ docs/spec/01-language-overview.md | 105 ++++++ docs/spec/02-types-and-values.md | 146 ++++++++ docs/spec/03-memory-model.md | 283 +++++++++++++++ docs/spec/04-concurrency-and-atomics.md | 340 ++++++++++++++++++ docs/spec/05-effects-and-capabilities.md | 101 ++++++ docs/spec/06-resources-and-errors.md | 60 ++++ docs/spec/07-air.md | 184 ++++++++++ docs/spec/08-verifier.md | 119 ++++++ docs/spec/09-runtime-and-abi.md | 72 ++++ .../spec/10-diagnostics-and-agent-protocol.md | 97 +++++ docs/spec/11-determinism-and-replay.md | 63 ++++ docs/spec/12-packages-and-build.md | 45 +++ docs/spec/13-contracts-and-unsafe.md | 86 +++++ docs/spec/INDEX.md | 18 + examples/append_log.aji | 52 +++ examples/atomic_publish.aji | 25 ++ examples/channel_transfer.aji | 23 ++ examples/file_copy.aji | 32 ++ examples/hello.aji | 10 + examples/parallel_map.aji | 26 ++ mise.toml | 2 + src/air.zig | 12 + src/check.zig | 30 ++ src/diag.zig | 179 +++++++++ src/interp.zig | 6 + src/main.zig | 95 +++++ src/root.zig | 17 + src/verifier.zig | 8 + tests/conformance/README.md | 42 +++ .../phase0/accept/loop_block_params.air | 22 ++ tests/conformance/phase0/accept/sum.air | 10 + .../phase0/reject/missing_terminator.air | 9 + .../phase0/reject/operand_type_mismatch.air | 10 + .../phase0/reject/undefined_value.air | 10 + .../phase1/reject/use_after_move.air | 11 + tools/conformance.zig | 215 +++++++++++ 67 files changed, 4197 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md create mode 100644 README.md create mode 100644 SPEC.md create mode 100644 aji.toml create mode 100644 build.zig create mode 100644 build.zig.zon create mode 100644 docs/README.md create mode 100644 docs/reference/concurrency-litmus.md create mode 100644 docs/reference/design-decisions.md create mode 100644 docs/reference/error-codes.md create mode 100644 docs/reference/glossary.md create mode 100644 docs/reference/grammar.ebnf create mode 100644 docs/reference/intrinsics.md create mode 100644 docs/reference/type-properties.md create mode 100644 docs/rfcs/0000-template.md create mode 100644 docs/rfcs/0001-memory-regions-islands-frozen.md create mode 100644 docs/rfcs/0002-structured-concurrency.md create mode 100644 docs/rfcs/0003-aji-memory-model.md create mode 100644 docs/rfcs/0004-air-instruction-set.md create mode 100644 docs/rfcs/README.md create mode 100644 docs/roadmap/conformance-suite.md create mode 100644 docs/roadmap/implementation-plan.md create mode 100644 docs/roadmap/phase-0.md create mode 100644 docs/spec/00-status-and-conformance.md create mode 100644 docs/spec/01-language-overview.md create mode 100644 docs/spec/02-types-and-values.md create mode 100644 docs/spec/03-memory-model.md create mode 100644 docs/spec/04-concurrency-and-atomics.md create mode 100644 docs/spec/05-effects-and-capabilities.md create mode 100644 docs/spec/06-resources-and-errors.md create mode 100644 docs/spec/07-air.md create mode 100644 docs/spec/08-verifier.md create mode 100644 docs/spec/09-runtime-and-abi.md create mode 100644 docs/spec/10-diagnostics-and-agent-protocol.md create mode 100644 docs/spec/11-determinism-and-replay.md create mode 100644 docs/spec/12-packages-and-build.md create mode 100644 docs/spec/13-contracts-and-unsafe.md create mode 100644 docs/spec/INDEX.md create mode 100644 examples/append_log.aji create mode 100644 examples/atomic_publish.aji create mode 100644 examples/channel_transfer.aji create mode 100644 examples/file_copy.aji create mode 100644 examples/hello.aji create mode 100644 examples/parallel_map.aji create mode 100644 mise.toml create mode 100644 src/air.zig create mode 100644 src/check.zig create mode 100644 src/diag.zig create mode 100644 src/interp.zig create mode 100644 src/main.zig create mode 100644 src/root.zig create mode 100644 src/verifier.zig create mode 100644 tests/conformance/README.md create mode 100644 tests/conformance/phase0/accept/loop_block_params.air create mode 100644 tests/conformance/phase0/accept/sum.air create mode 100644 tests/conformance/phase0/reject/missing_terminator.air create mode 100644 tests/conformance/phase0/reject/operand_type_mismatch.air create mode 100644 tests/conformance/phase0/reject/undefined_value.air create mode 100644 tests/conformance/phase1/reject/use_after_move.air create mode 100644 tools/conformance.zig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c744d60 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{md,yml,yaml,toml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f5fc17a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto eol=lf +*.aji linguist-language=Rust +*.air linguist-language=LLVM diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..efc1311 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,22 @@ +## Summary + + + +## Checklist + +- [ ] Spec/reference updated or confirmed unchanged +- [ ] Positive and negative conformance tests +- [ ] Stable diagnostic code for every new rejection (`error-codes.md` + `src/diag.zig`) +- [ ] Interpreter test if observable at runtime +- [ ] `zig fmt --check`, `zig build test`, `zig build conformance` pass + +### Memory / concurrency / FFI / unsafe changes only + +1. Invariant preserved: +2. Verifier rule: +3. Runtime rule: +4. Valid example: +5. Rejected example: +6. Diagnostic impact: +7. Deterministic interpreter behavior: +8. Backward-compatibility impact: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6b1f3b5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: ci + +on: + push: + pull_request: + +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: mlugg/setup-zig@v2 + with: + version: 0.17.0 + - run: zig fmt --check build.zig build.zig.zon src tools + - run: zig build test --summary all + - run: zig build conformance diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3389c86 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.zig-cache/ +zig-out/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6a97e41 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,144 @@ +# AGENTS.md + +This repository defines the Aji programming language. + +## Mission + +Aji is a small, typed, verifiable systems language intended primarily for AI-generated software. Any design or implementation change should improve at least one of: + +- semantic explicitness; +- verifier strength; +- deterministic behavior; +- machine repairability; +- memory/concurrency safety; +- implementation simplicity; +- auditability. + +Human ergonomics matter, but they are secondary to verifier clarity and agent reliability. + +## Non-negotiable principles + +Do not introduce: + +- implicit heap allocation; +- implicit reference counting; +- exceptions or stack unwinding; +- hidden destructors; +- unrestricted detached tasks; +- raw-pointer operations in safe code; +- default atomic memory orderings; +- compiler flags that change language semantics; +- arbitrary build scripts with host authority; +- effects or capabilities that are inferred away from the public contract. + +Safe Aji must not permit use-after-free, double-free, out-of-bounds reads/writes, uninitialized reads, invalid mutable aliasing, dangling borrows or unsynchronized data races. + +## Central abstractions + +Memory: + +```text +Own individually owned allocation +Region bulk lifetime and bulk deallocation +Island uniquely owned closed mutable object graph +Frozen deeply immutable graph +Arc explicit shared ownership for Share values +ref immutable borrow +mut exclusive mutable borrow +``` + +Concurrency preference: + +```text +ownership transfer +→ shared immutable data +→ synchronized shared state +→ atomics +→ unsafe raw concurrency +``` + +## Source of truth + +When documents disagree, use this precedence order: + +1. accepted RFCs; +2. files in `docs/spec/`; +3. files in `docs/reference/`; +4. examples; +5. README prose. + +Until an RFC is explicitly marked Accepted, the spec remains authoritative. + +## Normative language + +Use RFC-style terminology: + +- MUST / MUST NOT: mandatory for conformance; +- SHOULD / SHOULD NOT: strong recommendation with documented exceptions; +- MAY: optional behavior. + +## Implementation constraints + +Reference implementation target: Zig. + +Keep the trusted computing base small: + +- verifier; +- AIR interpreter semantics; +- backend; +- unsafe runtime modules; +- ABI/platform descriptions. + +Prefer verifier-visible primitives over opaque library magic. + +## Changes to memory or concurrency + +Any change involving ownership, aliasing, atomics, tasks, cancellation, resource lifetime, FFI or unsafe code MUST include: + +1. invariant being preserved; +2. verifier rule; +3. runtime rule if any; +4. at least one valid example; +5. at least one rejected example; +6. diagnostic/error code impact; +7. deterministic interpreter behavior; +8. backward-compatibility impact. + +## Changes to AIR + +AIR instructions must have explicit: + +- operand types; +- result types; +- ownership effects; +- memory effects; +- concurrency effects; +- capability/effect requirements; +- trap behavior; +- verifier transfer function. + +Do not add an AIR instruction solely as syntax sugar. + +## Commands + +```sh +zig build # build ./zig-out/bin/aji +zig build test # unit tests; fails if src/diag.zig drifts from docs/reference/error-codes.md +zig build conformance # tests/conformance; add `-- --json` for machine-readable results +zig fmt --check build.zig build.zig.zon src tools +``` + +Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Current phase task list: `docs/roadmap/phase-0.md`. + +`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted, 1 rejected, 2 usage/I/O error, 3 not yet implemented. + +## Testing policy + +Every verifier rule should have: + +- positive conformance test; +- negative conformance test; +- stable diagnostic code; +- interpreter test if observable at runtime. + +Concurrency features additionally need deterministic scheduler tests and randomized schedule stress tests. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..fc8c129 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,64 @@ +# Contributing + +Read `AGENTS.md` first. It holds the non-negotiable principles and the checklists every change must satisfy. This file covers the mechanics. + +## Toolchain + +- Zig **0.17.0** (pinned in `mise.toml` and `build.zig.zon`). With mise: `mise install`. + +## Commands + +```sh +zig build # build ./zig-out/bin/aji +zig build test # unit tests (includes registry ↔ docs sync check) +zig build conformance # conformance suite, see tests/conformance/README.md +zig build run -- check f.air # run the CLI +zig fmt --check build.zig src tools +``` + +CI runs `zig fmt --check`, `zig build test` and `zig build conformance` on every push and pull request. + +## Repository layout + +```text +docs/spec/ normative specification +docs/rfcs/ design RFCs (template: 0000-template.md) +docs/reference/ grammar, error codes, intrinsics, glossary +docs/roadmap/ implementation plan, phase task breakdowns +src/ reference implementation (Zig) + root.zig library root + diag.zig diagnostic envelope + error-code registry + air.zig AIR data model, text parser/serializer + verifier.zig verifier passes + interp.zig deterministic AIR interpreter + check.zig parse → verify pipeline used by CLI and tools + main.zig `aji` CLI +tools/conformance.zig conformance runner +tests/conformance/ .air conformance tests +examples/ illustrative Aji source programs +``` + +Everything under `src/` except `main.zig` is part of the trusted computing base or feeds it. Keep it small and free of heuristics. + +## Workflow for a change + +1. **Find the governing text.** Precedence: accepted RFCs → `docs/spec/` → `docs/reference/` → examples → README. +2. **Spec first.** If the behavior is not specified, change the spec (or write an RFC for major changes) before code. Never let the implementation define semantics silently. +3. **Tests first.** Add conformance tests (`accept` and `reject`) for every verifier rule touched. +4. **Implement.** +5. **Diagnostics.** A new rejection needs a code in `docs/reference/error-codes.md` *and* `src/diag.zig`; the unit test fails if they drift. +6. **Run** `zig fmt`, `zig build test`, `zig build conformance`. + +## Definition of done + +- [ ] Spec/reference updated or confirmed unchanged. +- [ ] Positive and negative conformance tests. +- [ ] Stable diagnostic code for every new rejection. +- [ ] Interpreter test if observable at runtime. +- [ ] Memory/concurrency/FFI/unsafe changes: the 8-point checklist from `AGENTS.md`. +- [ ] AIR changes: the instruction contract from `AGENTS.md` / spec 07 §4. +- [ ] Concurrency changes: deterministic scheduler tests and randomized schedule stress tests. + +## Commits + +One logical change per commit. Prefix the subject with the area: `spec:`, `rfc:`, `air:`, `verifier:`, `interp:`, `diag:`, `cli:`, `tests:`, `build:`, `docs:`. diff --git a/README.md b/README.md new file mode 100644 index 0000000..edd6e74 --- /dev/null +++ b/README.md @@ -0,0 +1,120 @@ +# Aji + +**Aji** is an experimental systems programming language designed primarily for software generated and maintained by AI agents. + +Aji optimizes for explicit semantics, machine verification, predictable execution, memory safety without garbage collection, structured concurrency, explicit capabilities, and machine-readable diagnostics. + +> Aji is not "assembly for agents". It is a small, typed, verifiable systems language whose canonical semantic representation is AIR (Aji Intermediate Representation). + +## Status + +Specification status: **Draft 0.1**. + +Nothing in this repository should yet be treated as a stable compatibility promise. + +## Core model + +```text +human specification + ↓ + AI agent + ↓ + Aji + ↓ + compiler + verifier + ↓ + AIR + ↓ + interpreter / backend + ↓ + native executable +``` + +The central language ideas are: + +- explicit ownership rather than implicit GC; +- `Region` for bounded-lifetime bulk allocation; +- `Island` for uniquely owned mutable object graphs; +- `Frozen` for deeply immutable shared graphs; +- structured tasks that cannot silently outlive their scopes; +- ownership transfer as the preferred concurrency mechanism; +- `Mutex`, channels and atomics only when sharing is required; +- explicit effects and capabilities for external authority; +- stable machine-readable verifier diagnostics; +- deterministic execution and replay as first-class tooling. + +## Repository map + +```text +docs/spec/ Normative language specification +docs/rfcs/ Major design RFCs and rationale +docs/reference/ Grammar, error codes, intrinsics, glossary +docs/roadmap/ Implementation and conformance plans +src/ Reference implementation (Zig): diagnostics, AIR, verifier, interpreter +tools/ Conformance runner +tests/ Conformance suite (.air accept/reject tests) +examples/ Illustrative Aji programs +AGENTS.md Instructions for AI coding agents +CONTRIBUTING.md Toolchain, commands, workflow, definition of done +``` + +## Building + +Requires Zig 0.17.0 (`mise install` picks it up from `mise.toml`). + +```sh +zig build # ./zig-out/bin/aji +zig build test # unit tests +zig build conformance # conformance suite +``` + +Current state: Phase 0 has not started. `aji check` reports every input as not yet decidable; see [`docs/roadmap/phase-0.md`](docs/roadmap/phase-0.md) for the task breakdown. + +Start with [`SPEC.md`](SPEC.md), then: + +1. `docs/spec/00-status-and-conformance.md` +2. `docs/spec/01-language-overview.md` +3. `docs/spec/03-memory-model.md` +4. `docs/spec/04-concurrency-and-atomics.md` +5. `docs/spec/07-air.md` +6. `docs/spec/08-verifier.md` + +## Design thesis + +Traditional systems languages mainly optimize the interface: + +```text +human → source code +``` + +Aji instead optimizes: + +```text +AI agent → verified executable system +``` + +The source representation therefore prioritizes semantic explicitness, bounded complexity, deterministic repair loops and mechanically enforceable invariants over convenience features designed primarily for manual authoring. + +## Reference implementation direction + +The proposed reference implementation is written primarily in Zig and should be implemented in this order: + +```text +AIR data model +→ AIR parser/serializer +→ interpreter +→ ownership verifier +→ borrow/region verifier +→ structured concurrency verifier +→ deterministic scheduler +→ Aji source parser +→ standard library +→ LLVM lowering +→ native runtime +``` + +Do not start by writing a native code generator. The interpreter and verifier define the semantics. + +## License + +No license has been selected yet. Add one before public distribution. diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..de1bfb3 --- /dev/null +++ b/SPEC.md @@ -0,0 +1,45 @@ +# Aji Specification 0.1 — Entry Point + +This repository intentionally splits the language specification by semantic domain. + +Normative specification: [`docs/spec/INDEX.md`](docs/spec/INDEX.md). + +The most important documents are: + +1. [`03-memory-model.md`](docs/spec/03-memory-model.md) +2. [`04-concurrency-and-atomics.md`](docs/spec/04-concurrency-and-atomics.md) +3. [`05-effects-and-capabilities.md`](docs/spec/05-effects-and-capabilities.md) +4. [`07-air.md`](docs/spec/07-air.md) +5. [`08-verifier.md`](docs/spec/08-verifier.md) +6. [`11-determinism-and-replay.md`](docs/spec/11-determinism-and-replay.md) +7. [`13-contracts-and-unsafe.md`](docs/spec/13-contracts-and-unsafe.md) + +Major rationale documents are under [`docs/rfcs/`](docs/rfcs/). + +The current draft's central semantic model is: + +```text +local value + │ + ├── ref / mut borrows + │ + ├── Own per-object ownership + │ + ├── Region bulk lifetime + │ │ + │ └── Island closed movable mutable graph + │ │ + │ └── freeze → Frozen + │ + └── synchronized sharing → Mutex/RwLock/Atomic/Channel +``` + +Concurrency is deliberately ordered by preference: + +```text +ownership transfer +→ shared immutable data +→ synchronized shared state +→ atomics +→ unsafe raw concurrency +``` diff --git a/aji.toml b/aji.toml new file mode 100644 index 0000000..e72cdb9 --- /dev/null +++ b/aji.toml @@ -0,0 +1,7 @@ +[package] +name = "aji-spec" +version = "0.1.0-draft" + +[metadata] +purpose = "Aji language specification and reference examples" +status = "draft" diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..2ec2c1a --- /dev/null +++ b/build.zig @@ -0,0 +1,56 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + // Library: verifier, AIR, interpreter. Everything the TCB contains lives here. + const mod = b.addModule("aji", .{ + .root_source_file = b.path("src/root.zig"), + .target = target, + .optimize = optimize, + }); + // The error-code registry in docs/ is the source of truth; a test keeps + // src/diag.zig in sync with it. + mod.addAnonymousImport("error_codes_md", .{ + .root_source_file = b.path("docs/reference/error-codes.md"), + }); + + // CLI: `aji`. + const exe = b.addExecutable(.{ + .name = "aji", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "aji", .module = mod }}, + }), + }); + b.installArtifact(exe); + + const run_cmd = b.addRunArtifact(exe); + run_cmd.step.dependOn(b.getInstallStep()); + run_cmd.addPassthruArgs(); + b.step("run", "Run the aji CLI").dependOn(&run_cmd.step); + + // Unit tests. + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = exe.root_module })).step); + + // Conformance suite runner (tests/conformance). + const conformance = b.addExecutable(.{ + .name = "aji-conformance", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/conformance.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "aji", .module = mod }}, + }), + }); + const run_conformance = b.addRunArtifact(conformance); + run_conformance.addArg("tests/conformance"); + run_conformance.addPassthruArgs(); + b.step("conformance", "Run the conformance suite").dependOn(&run_conformance.step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = conformance.root_module })).step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..44d75ae --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,14 @@ +.{ + .name = .aji, + .version = "0.0.0", + .fingerprint = 0x1d2822d436c7a09e, // Changing this has security and trust implications. + .minimum_zig_version = "0.17.0", + .dependencies = .{}, + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + "tools", + "docs/reference/error-codes.md", + }, +} diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..24fc5b6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,19 @@ +# Documentation + +- `spec/` contains the normative draft specification. +- `rfcs/` contains proposed major design decisions and rationale. +- `reference/` contains compact registries and lookup material. +- `roadmap/` contains implementation and conformance plans, including per-phase task breakdowns (`roadmap/phase-0.md`). +- `rfcs/0000-template.md` is the template for new RFCs. + +Suggested reading order: + +```text +spec/00-status-and-conformance.md +spec/01-language-overview.md +spec/03-memory-model.md +spec/04-concurrency-and-atomics.md +spec/07-air.md +spec/08-verifier.md +spec/13-contracts-and-unsafe.md +``` diff --git a/docs/reference/concurrency-litmus.md b/docs/reference/concurrency-litmus.md new file mode 100644 index 0000000..7dad0e8 --- /dev/null +++ b/docs/reference/concurrency-litmus.md @@ -0,0 +1,59 @@ +# Concurrency Litmus Tests + +These are semantic tests for the interpreter, verifier and native backend. Syntax is illustrative. + +## MP — message publication + +Writer: + +```aji +atomic.store(ref value, 42, relaxed); +atomic.store(ref ready, true, release); +``` + +Reader: + +```aji +if atomic.load(ref ready, acquire) { + let v = atomic.load(ref value, relaxed); + assert v == 42; +} +``` + +If the reader observes the release publication, observing the prior value store must be consistent with the happens-before relation. + +## SB — store buffering + +Initially `x = 0`, `y = 0`, both atomic. + +Task A: + +```text +store x=1 relaxed +r1 = load y relaxed +``` + +Task B: + +```text +store y=1 relaxed +r2 = load x relaxed +``` + +Outcome `r1=0, r2=0` is permitted under relaxed ordering. The interpreter's weak-memory test mode must not incorrectly forbid it. + +## Mutex handoff + +Writes performed while holding a mutex before unlock must be visible to a later holder after successful lock acquisition. + +## Channel handoff + +Writes sequenced before successful `channel.send` are visible after the matching receive. Ownership of the moved message belongs only to the receiver after transfer. + +## Spawn/join + +Parent operations sequenced before spawn happen-before child start. Child operations happen-before successful join return. + +## Invalid ordinary race + +Two tasks writing the same ordinary `u64` through overlapping unsynchronized aliases must be rejected before execution. diff --git a/docs/reference/design-decisions.md b/docs/reference/design-decisions.md new file mode 100644 index 0000000..a279b2d --- /dev/null +++ b/docs/reference/design-decisions.md @@ -0,0 +1,41 @@ +# Design Decisions + +This file records short decisions whose rationale does not yet justify a standalone RFC. + +## DD-001 — Checked arithmetic by default + +Normal integer arithmetic traps on overflow. Wrapping/saturating arithmetic is explicit. + +Reason: release/debug behavior must not diverge, and arithmetic assumptions should remain visible to agents/verifier. + +## DD-002 — No exceptions + +Errors are values. No stack unwinding. + +Reason: explicit CFG and resource cleanup are easier to verify and replay. + +## DD-003 — No hidden destructors + +Cleanup constructs lower to explicit AIR edges. + +Reason: hidden control flow harms auditability and agent repair. + +## DD-004 — Bounded channels by default + +Unbounded queues require explicit library choice. + +Reason: memory growth must not be implicit. + +## DD-005 — No default atomic ordering + +Every atomic operation states its order. + +Reason: the compiler must not hide one of the most consequential concurrency choices. + +## DD-006 — No arbitrary safe atomic pointer type initially + +Reason: reclamation cannot be separated from safe publication. + +## DD-007 — Interpreter before optimizer/backend + +Reason: executable semantics and verifier behavior must stabilize before native-code complexity is introduced. diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md new file mode 100644 index 0000000..2aa159e --- /dev/null +++ b/docs/reference/error-codes.md @@ -0,0 +1,61 @@ +# Error Code Registry + +Draft registry. Codes are stable once released in a tagged compiler version. + +## E1xxx — Types and values + +| Code | Kind | Meaning | +|---|---|---| +| E1001 | type.mismatch | Operand/result type mismatch | +| E1002 | type.invalid_cast | Cast not permitted by safe semantics | +| E1010 | init.read_uninitialized | Read from uninitialized storage | + +## E2xxx — Memory and ownership + +| Code | Kind | Meaning | +|---|---|---| +| E2001 | ownership.use_after_move | Value used after ownership transfer | +| E2002 | ownership.double_consume | Linear value consumed twice | +| E2101 | borrow.mutable_alias | Overlapping exclusive/shared borrow violation | +| E2102 | borrow.outlives_owner | Borrow may outlive backing storage | +| E2103 | memory.out_of_bounds | Access not proven in bounds | +| E2104 | memory.region_generation | Reference belongs to invalidated region generation | +| E2110 | island.escape | Island-internal reference escapes island | +| E2111 | island.foreign_mutable_edge | Island graph points to forbidden foreign mutable storage | + +## E3xxx — Resources/capabilities/effects + +| Code | Kind | Meaning | +|---|---|---| +| E3001 | resource.use_after_consume | Closed/joined/released resource reused | +| E3002 | resource.leak | Linear resource has no terminal consumption path | +| E3101 | effect.undeclared | Callee effect absent from caller contract | +| E3201 | capability.missing | Required authority unavailable | +| E3202 | capability.widen | Attempt to widen delegated authority | + +## E4xxx — Concurrency + +| Code | Kind | Meaning | +|---|---|---| +| E4001 | concurrency.not_send | Non-Send value moved to migratable task/thread | +| E4002 | concurrency.not_share | Non-Share value concurrently shared | +| E4101 | concurrency.possible_data_race | Conflicting ordinary access not ordered/synchronized | +| E4201 | atomic.invalid_order | Memory ordering invalid for atomic operation | +| E4301 | task.live_child_escape | Scope exits with live child task | +| E4302 | task.borrow_escape | Child task borrow can outlive parent storage | +| E4303 | io.buffer_in_flight | Buffer accessed while async operation owns/borrows it | + +## E5xxx — AIR/verifier + +| Code | Kind | Meaning | +|---|---|---| +| E5001 | air.invalid_ssa | SSA definition/dominance failure | +| E5002 | air.invalid_cfg | Invalid block/terminator structure | +| E5101 | verifier.resource_limit | Deterministic verifier resource limit exceeded | + +## E6xxx — Unsafe/ABI + +| Code | Kind | Meaning | +|---|---|---| +| E6001 | unsafe.required | Operation requires explicit unsafe boundary | +| E6101 | abi.unaligned_reference | Normal reference requested from insufficiently aligned storage | diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md new file mode 100644 index 0000000..b33b75a --- /dev/null +++ b/docs/reference/glossary.md @@ -0,0 +1,23 @@ +# Glossary + +**AIR** — Aji Intermediate Representation, the canonical semantic representation. + +**Borrow** — temporary access to storage without ownership transfer. + +**Capability** — unforgeable authority required to perform selected external operations. + +**Effect** — declared category of externally observable or privileged behavior. + +**Frozen graph** — deeply immutable graph produced by irreversible freeze. + +**Island** — uniquely owned closed graph of mutable memory that can be transferred as one ownership unit. + +**Linear resource** — value that must be consumed exactly once. + +**Provenance** — logical origin/bounds/lifetime identity attached to a safe reference. + +**Region** — owner of many allocations sharing a collective reset/destroy lifetime. + +**Structured concurrency** — model in which child execution is bounded by an explicit parent scope. + +**Undefined Aji Behavior** — behavior resulting only from violation of documented unsafe preconditions. diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf new file mode 100644 index 0000000..d0b0110 --- /dev/null +++ b/docs/reference/grammar.ebnf @@ -0,0 +1,51 @@ +(* Aji draft grammar sketch. This is intentionally incomplete until syntax stabilizes. *) + +program = { module_decl | import_decl | type_decl | function_decl } ; + +module_decl = "module" qualified_name ";" ; +import_decl = "use" qualified_name [ "as" identifier ] ";" ; + +function_decl = [ "pub" ] [ "unsafe" ] "fn" identifier + [ generic_params ] + "(" [ parameter_list ] ")" + [ "->" type ] + effect_decl + [ contract_block ] + block ; + +effect_decl = "effects" "[" [ effect_list ] "]" ; + +parameter_list = parameter { "," parameter } ; +parameter = identifier ":" param_type ; +param_type = [ "move" ] type + | "ref" "<" type ">" + | "mut" "<" type ">" ; + +type = primitive_type + | qualified_name + | "Option" "<" type ">" + | "Result" "<" type "," type ">" + | "Own" "<" type ">" + | "Island" "<" type ">" + | "Frozen" "<" type ">" + | "Arc" "<" type ">" + | "slice" "<" type ">" + | "slice_mut" "<" type ">" + | "ref" "<" type ">" + | "mut" "<" type ">" + | "[" type ";" integer_literal "]" ; + +primitive_type = "bool" | "byte" | "void" | "never" + | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" + | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" + | "f32" | "f64" ; + +block = "{" { statement } "}" ; +statement = let_stmt | var_stmt | return_stmt | expr_stmt | block ; +let_stmt = "let" identifier [ ":" type ] "=" expression ";" ; +var_stmt = "var" identifier [ ":" type ] "=" expression ";" ; +return_stmt = "return" [ expression ] ";" ; +expr_stmt = expression ";" ; + +qualified_name = identifier { "." identifier } ; +identifier = letter { letter | digit | "_" } ; diff --git a/docs/reference/intrinsics.md b/docs/reference/intrinsics.md new file mode 100644 index 0000000..9a0c9cd --- /dev/null +++ b/docs/reference/intrinsics.md @@ -0,0 +1,93 @@ +# Intrinsic Registry (Draft) + +Intrinsics are verifier-known platform/runtime operations. Each intrinsic requires a formal signature, effects, capabilities, ownership behavior and failure model. + +## Filesystem + +```text +fs.open_read +fs.open_write +fs.read +fs.write +fs.write_all +fs.sync +fs.close +``` + +## Console / generic I/O + +```text +io.stdout_write +io.stderr_write +``` + +## Network + +```text +net.socket +net.bind +net.listen +net.accept +net.connect +net.recv +net.send +net.close +``` + +## Time/random + +```text +clock.monotonic +clock.wall +random.fill +``` + +## Task/thread + +```text +task.spawn +task.join +task.cancel +thread.spawn +thread.join +``` + +## Synchronization + +```text +mutex.create +mutex.lock +mutex.unlock +rwlock.create +rwlock.read +rwlock.write +channel.create +channel.send +channel.recv +``` + +## Atomics + +```text +atomic.load +atomic.store +atomic.exchange +atomic.fetch_add +atomic.fetch_sub +atomic.compare_exchange +atomic.fence +``` + +## Memory + +```text +heap.alloc +heap.free +region.create +region.alloc +region.reset +region.destroy +island.create +island.alloc +island.freeze +``` diff --git a/docs/reference/type-properties.md b/docs/reference/type-properties.md new file mode 100644 index 0000000..e81c8c2 --- /dev/null +++ b/docs/reference/type-properties.md @@ -0,0 +1,37 @@ +# Type Properties + +Aji 0.1 uses compiler-known structural properties rather than a user-defined trait system. + +## Copy + +A `Copy` value may be duplicated without changing ownership semantics. + +Typical examples: integers, booleans, small aggregates containing only `Copy` fields. + +Not `Copy`: `Own`, `Region`, `Island`, `File`, `Socket`, task/thread handles. + +## Send + +A `Send` value may move to another concurrent execution context. + +A type becomes non-`Send` if it contains thread-affine/local state. + +## Share + +A `Share` value may be observed concurrently through immutable access. + +Deeply immutable values are normally `Share`. + +Interior-mutability wrappers must establish their own synchronization semantics to qualify. + +## Freeze + +A `Freeze` type may participate in deep immutable conversion. + +External resources that remain operational/mutable may prevent `Freeze`. + +## Local + +A `Local` value is tied to its current execution context and prevents migration/transfer. + +Examples may include thread-local handles, event-loop-local registrations or platform UI objects. diff --git a/docs/rfcs/0000-template.md b/docs/rfcs/0000-template.md new file mode 100644 index 0000000..ad5bf83 --- /dev/null +++ b/docs/rfcs/0000-template.md @@ -0,0 +1,56 @@ +# RFC NNNN: Title + +Status: Draft +Target: Aji 0.x +Supersedes: — + + + +## Motivation + +Which of the mission goals (AGENTS.md) does this improve, and what fails today without it? + +## Precise invariant + +The property preserved or established, stated so that a verifier could check it. + +## Normative rule changes + +Exact MUST/SHOULD/MAY text to add to or replace in `docs/spec/`, with file and section. + +## Verifier implications + +New abstract state, transfer functions, and complexity bound. + +## Interpreter / runtime implications + +Runtime rule, if any. Deterministic interpreter behavior. + +## AIR changes + +For each new or changed instruction: operand types, result types, ownership effects, memory effects, concurrency effects, capability/effect requirements, trap behavior, verifier transfer function. Explain why it is not syntax sugar. + +## Valid example + +```text +``` + +## Rejected example + +```text +``` + +Expected diagnostic: + +```json +``` + +## Diagnostics impact + +New or changed codes in `docs/reference/error-codes.md`. + +## Compatibility and migration + +## Alternatives considered + +## Unresolved questions diff --git a/docs/rfcs/0001-memory-regions-islands-frozen.md b/docs/rfcs/0001-memory-regions-islands-frozen.md new file mode 100644 index 0000000..1c93ce4 --- /dev/null +++ b/docs/rfcs/0001-memory-regions-islands-frozen.md @@ -0,0 +1,110 @@ +# RFC 0001: Regions, Islands and Frozen Graphs + +Status: Proposed +Target: Aji 0.1 + +## Summary + +Aji uses four complementary ownership mechanisms: + +```text +Own single object ownership +Region bulk lifetime +Island closed uniquely owned mutable graph +Frozen deeply immutable shared graph +``` + +The intent is to avoid forcing all systems programming into one ownership abstraction. + +## Motivation + +Traditional per-object ownership works well for trees and many local structures, but becomes awkward for: + +- cyclic graphs; +- object arenas; +- parsers with many related nodes; +- message graphs transferred between tasks; +- storage-engine request contexts; +- actor-like state. + +A tracing GC solves graph lifetime at runtime but introduces runtime tracing and weakens explicit lifetime control. + +Regions solve bulk lifetime but by themselves do not solve safe concurrent transfer of arbitrary mutable graphs. + +`Island` combines region-owned storage with unique graph ownership. + +## Invariant + +For a live island `I`: + +```text +outside mutable aliases into I = 0 +mutable references from I into ordinary foreign mutable memory = 0 +``` + +Internal `iref` edges may be cyclic but are scoped to the island. + +## Transfer + +Ownership of `Island` may move between tasks, channels and threads if the contained external resources satisfy transfer requirements. + +Transfer invalidates sender ownership. + +No deep copy is required. + +## Freeze + +`island.freeze` consumes the mutable island and produces `Frozen`. + +The conversion is irreversible in safe Aji. + +This allows a large graph to move from: + +```text +single-writer mutable state +``` + +into: + +```text +concurrently shared immutable state +``` + +without copying. + +## Rejected alternatives + +### Everything is Own + +Rejected because cyclic/arena-style graphs become unnecessarily complex. + +### Garbage collection + +Rejected as a core requirement because Aji targets kernels, runtimes and storage systems where deterministic lifetime and bounded runtime behavior are important. + +### Implicit reference counting + +Rejected because hidden atomic increments/decrements are poor fits for transparent cost and agent reasoning. + +### Shared mutable regions + +Rejected as a default model because it makes the verifier's alias and race problem substantially harder. + +## Verifier rules + +The verifier must track: + +- island owner; +- internal allocation membership; +- escaping references; +- `iref` island identity; +- mutable borrow exclusivity; +- freeze transition; +- transfer transition. + +## Open questions + +- whether islands may contain multiple physical regions; +- exact representation of `iref`; +- whether sub-islands can be detached in O(1); +- interaction with memory-mapped files. diff --git a/docs/rfcs/0002-structured-concurrency.md b/docs/rfcs/0002-structured-concurrency.md new file mode 100644 index 0000000..2dfc344 --- /dev/null +++ b/docs/rfcs/0002-structured-concurrency.md @@ -0,0 +1,65 @@ +# RFC 0002: Structured Concurrency + +Status: Proposed +Target: Aji 0.1 + +## Summary + +Aji makes structured task scopes the default concurrency primitive. + +A child task cannot silently outlive the scope that created it. + +## Motivation + +Unstructured task spawning complicates: + +- lifetime reasoning; +- cancellation; +- resource cleanup; +- borrowed data; +- error propagation; +- deterministic replay. + +A language designed for machine verification should make the lifetime tree explicit. + +## Rule + +Every normal task belongs to a task scope. + +```aji +task.scope s { + let a = task.spawn(s, worker_a, move input_a)?; + let b = task.spawn(s, worker_b, move input_b)?; + + let ra = task.join(move a)?; + let rb = task.join(move b)?; +} +``` + +Leaving the scope with live children is a verifier error. + +## Borrowing + +Because child lifetime is bounded by the scope, scoped tasks may borrow parent storage when the verifier proves the storage outlives all child uses. + +This enables zero-copy parallel algorithms. + +## Cancellation + +Cancellation propagates downward through the task tree but is observed only at explicit cancellation points. + +Aji intentionally rejects arbitrary asynchronous interruption because it can break invariants between instructions. + +## Detached tasks + +Detached tasks require an explicit capability and fully owned `Send` state. + +Long-lived services should normally be expressed using supervisors rather than detached background work. + +## Failure policy + +The language does not hard-code fail-fast semantics. Libraries may implement supervision policies. + +## Determinism + +Structured task topology gives the deterministic runtime a bounded set of live tasks and parent/child relationships, simplifying replay and schedule exploration. diff --git a/docs/rfcs/0003-aji-memory-model.md b/docs/rfcs/0003-aji-memory-model.md new file mode 100644 index 0000000..c250563 --- /dev/null +++ b/docs/rfcs/0003-aji-memory-model.md @@ -0,0 +1,61 @@ +# RFC 0003: Concurrency Memory Model + +Status: Proposed +Target: Aji 0.1 + +## Summary + +Aji adopts a data-race-free model for ordinary memory and explicit C/C++/Rust-style atomic ordering for low-level synchronization. + +The intended user-level guarantee is DRF-SC: + +> If a safe program has no data race, ordinary memory behaves as though operations occurred in some sequentially consistent interleaving consistent with happens-before. + +## Relations + +The model defines: + +- sequenced-before; +- synchronizes-with; +- happens-before; +- atomic modification order. + +## Synchronization examples + +- operations before task spawn happen-before child start; +- child completion happens-before successful join return; +- channel send synchronizes with the matching receive; +- mutex unlock synchronizes with a later successful lock acquisition; +- release atomic operation synchronizes with an acquire operation that observes the release according to atomic semantics. + +## Ordinary memory + +Safe Aji rejects possible unsynchronized conflicting ordinary accesses. + +The compiler may therefore optimize ordinary memory under the assumption that safe programs are race-free. + +## Atomics + +Orders: + +```text +relaxed +acquire +release +acq_rel +seq_cst +``` + +No default order and no `consume`. + +## Why no safe Atomic> initially + +Publishing an address atomically does not solve reclamation. A verifier would need to reason about when pointed-to storage can be freed. + +Therefore lock-free pointer structures should first exist behind audited library abstractions using epoch/hazard/RCU mechanisms. + +## Weak-memory audit marker + +Use of relaxed atomics should be visible in the effect/audit system as `atomic.weak`. + +This has no runtime meaning; it is an auditability requirement. diff --git a/docs/rfcs/0004-air-instruction-set.md b/docs/rfcs/0004-air-instruction-set.md new file mode 100644 index 0000000..5a984cf --- /dev/null +++ b/docs/rfcs/0004-air-instruction-set.md @@ -0,0 +1,90 @@ +# RFC 0004: AIR Instruction Set + +Status: Proposed +Target: Aji 0.1 + +## Goal + +AIR should be small enough for complete semantic definitions to fit in an agent context while remaining expressive enough for systems software. + +## Principle + +Do not add instructions because they make source syntax convenient. Add an AIR instruction only when it represents a distinct semantic/verifier operation. + +## Initial instruction families + +### Pure values + +```text +const copy move +integer arithmetic +bitwise operations +comparisons +casts with explicit failure/semantics +``` + +### Control + +```text +br cbr switch ret trap guard assert +``` + +### Memory + +```text +borrow.ref borrow.mut borrow.end +load store +slice.make slice.sub +mem.copy mem.zero +``` + +### Ownership + +```text +own.alloc own.free +region.create region.alloc region.reset region.destroy +island.create island.alloc island.freeze +arc.clone arc.release +``` + +### Resources and calls + +```text +call call.indirect intrinsic.call +resource.consume +``` + +### Concurrency + +```text +task.scope.begin task.scope.end +task.spawn task.join task.cancel +thread.spawn thread.join +channel.send channel.recv +mutex.lock mutex.unlock +rwlock.read rwlock.write +atomic.load atomic.store atomic.rmw atomic.cmpxchg atomic.fence +``` + +## Required metadata + +Each opcode definition must declare: + +```text +syntax +operand types +result types +ownership transfer +borrow transfer +memory read/write set +sync relation +required effect +required capability +trap cases +verifier transfer function +interpreter behavior +``` + +## Binary stability + +AIR opcodes should receive stable numeric IDs only after the semantics of v0.1 freeze. Before then, text AIR is the safer canonical interchange for development. diff --git a/docs/rfcs/README.md b/docs/rfcs/README.md new file mode 100644 index 0000000..d24ffed --- /dev/null +++ b/docs/rfcs/README.md @@ -0,0 +1,23 @@ +# RFC Process + +RFC status values: + +```text +Draft → Proposed → Accepted → Implemented + ↘ Rejected +``` + +An RFC that changes memory safety, concurrency, effects/capabilities, AIR or unsafe semantics must include: + +- motivation; +- precise invariant; +- normative rule changes; +- verifier implications; +- interpreter/runtime implications; +- valid example; +- rejected example; +- diagnostics impact; +- migration/compatibility notes; +- alternatives considered. + +Until an RFC is marked Accepted, the normative files under `docs/spec/` remain authoritative. diff --git a/docs/roadmap/conformance-suite.md b/docs/roadmap/conformance-suite.md new file mode 100644 index 0000000..27966f7 --- /dev/null +++ b/docs/roadmap/conformance-suite.md @@ -0,0 +1,112 @@ +# Conformance Suite + +## Reference programs + +### 1. hello + +Tests compiler/interpreter/runtime bootstrap. + +### 2. file-copy + +Tests: + +- file resources; +- regions; +- slices; +- fallible I/O; +- cleanup paths. + +### 3. tcp-echo + +Tests: + +- socket typestate; +- tasks; +- cancellation; +- resource transfer. + +### 4. append-log + +Tests: + +- checksums; +- bounded memory; +- crash/recovery behavior; +- explicit fsync; +- serialization; +- resource safety. + +### 5. parallel-map + +Tests: + +- slice partition proof; +- scoped mutable borrows; +- task join; +- cancellation. + +### 6. island-pipeline + +Tests: + +- cyclic mutable graph; +- channel transfer; +- sender invalidation; +- receiver ownership; +- freeze and concurrent reads. + +## Negative verifier corpus + +Must include: + +- use after move; +- overlapping mutable borrows; +- region reset with live reference; +- use of prior region generation; +- island internal reference escape; +- non-Send transfer; +- non-Share concurrent read; +- task escape; +- async buffer use while in flight; +- invalid atomic ordering; +- missing capability; +- undeclared effect; +- linear resource leak. + +## Concurrency stress modes + +Run concurrency tests with: + +```text +1 worker +2 workers +N workers +deterministic schedule +randomized schedule +forced yield at synchronization points +slow consumer +cancellation during waits +I/O completion reordering +``` + +## Agent benchmark + +Compare Aji, Zig, Rust and C under the same task specifications and agent model. + +Primary metric: + +```text +P(correct program | one generation/repair iteration) +``` + +Secondary metrics: + +- iterations to verified solution; +- tokens consumed; +- verifier/compiler repair loops; +- runtime defects; +- memory/concurrency bugs; +- regression rate after change; +- context required to modify the system; +- runtime speed; +- binary size. diff --git a/docs/roadmap/implementation-plan.md b/docs/roadmap/implementation-plan.md new file mode 100644 index 0000000..e6e0705 --- /dev/null +++ b/docs/roadmap/implementation-plan.md @@ -0,0 +1,118 @@ +# Implementation Plan + +## Phase 0 — Semantic skeleton + +Deliver: + +- AIR value/type model; +- text AIR parser and serializer; +- basic blocks and SSA validation; +- integer operations; +- structs/enums; +- interpreter; +- stable diagnostic envelope. + +Exit criterion: AIR `hello` and arithmetic tests execute identically across runs. + +## Phase 1 — Ownership and memory + +Deliver: + +- `Own`; +- `ref` / `mut`; +- slices; +- initialization tracking; +- `Region` and generation semantics; +- bounds/range facts; +- ownership/borrow diagnostics. + +Exit criterion: file-copy can be implemented and verifier rejects representative UAF/alias/OOB cases. + +## Phase 2 — Effects, capabilities and resources + +Deliver: + +- effects; +- capability values; +- linear File/Socket resources; +- runtime intrinsics; +- explicit cleanup lowering. + +Exit criterion: safe file-copy and basic TCP echo. + +## Phase 3 — Structured concurrency + +Deliver: + +- task scopes; +- spawn/join; +- `Send` / `Share` derivation; +- scoped borrowing; +- bounded channels; +- mutex; +- cancellation; +- deterministic scheduler. + +Exit criterion: parallel-map and channel ownership-transfer examples. + +## Phase 4 — Islands + +Deliver: + +- island allocator; +- `iref`; +- closure verification; +- move/transfer; +- freeze; +- `Frozen`. + +Exit criterion: cyclic graph can move between tasks with no deep copy and no shared mutation. + +## Phase 5 — Atomics and memory model + +Deliver: + +- atomic scalar types; +- all five orderings; +- fences; +- happens-before model in interpreter/testing tools; +- weak-atomic audit marking; +- schedule exploration. + +Exit criterion: atomic publication litmus/conformance tests. + +## Phase 6 — Source language + +Deliver: + +- source parser; +- source-to-AIR lowering; +- generics/monomorphization; +- contracts syntax; +- formatter. + +Exit criterion: all reference programs authored primarily as `.aji`. + +## Phase 7 — Native backend + +Deliver: + +- LLVM lowering; +- Linux x86_64; +- Linux aarch64; +- macOS aarch64; +- ABI tests. + +Exit criterion: interpreted and native executions pass the same conformance corpus. + +## Phase 8 — Agent protocol + +Deliver: + +- `ajid`; +- structured diagnostics; +- inspect/trace endpoints; +- machine-readable verifier state summaries; +- benchmark protocol. + +Exit criterion: an external coding agent can implement/repair a reference task using only the protocol and repository spec. diff --git a/docs/roadmap/phase-0.md b/docs/roadmap/phase-0.md new file mode 100644 index 0000000..b083b0b --- /dev/null +++ b/docs/roadmap/phase-0.md @@ -0,0 +1,25 @@ +# Phase 0 — Semantic skeleton: task breakdown + +Non-normative. Breaks Phase 0 of `implementation-plan.md` into tasks small enough for one agent session each. + +Exit criterion (from the plan): AIR `hello` and arithmetic tests execute identically across runs. + +| ID | Task | Depends on | Output | Done when | +|---|---|---|---|---| +| P0-1 | Specify text AIR grammar | — | `docs/reference/air-text.ebnf`, updates to `docs/spec/07-air.md` | grammar covers module header, functions, `effects`, blocks with parameters, instructions, comments; seed tests in `tests/conformance/phase0` match it | +| P0-2 | AIR data model | P0-1 | `src/air.zig` (types, values, instructions, blocks, functions, module) | round-trips through P0-4 | +| P0-3 | Text AIR lexer + parser | P0-1, P0-2 | `src/air/parse.zig` | parse errors are diagnostics with spans; new parse codes registered in `error-codes.md` | +| P0-4 | Canonical serializer | P0-2 | `src/air/print.zig` | `parse ∘ print` is identity on the data model; output is byte-stable | +| P0-5 | CFG verifier | P0-3 | `src/verifier/cfg.zig` | `E5002` accept/reject tests pass | +| P0-6 | SSA/dominance verifier | P0-5 | `src/verifier/ssa.zig` | `E5001` accept/reject tests pass | +| P0-7 | Type verifier for integer ops, structs, enums | P0-3 | `src/verifier/types.zig` | `E1001` accept/reject tests pass | +| P0-8 | Verifier resource budget | P0-5 | budget in `src/verifier.zig` | `E5101` emitted deterministically; budget documented in spec 08 | +| P0-9 | Interpreter core | P0-6, P0-7 | `src/interp.zig` | arithmetic programs run; checked overflow traps per spec | +| P0-10 | `aji run` + run tests in conformance runner | P0-9 | `expect: run` header with expected stdout/trap | `hello` and arithmetic tests pass, output identical across 100 runs | + +## Open questions to resolve in P0-1 + +- Comment syntax in text AIR (the conformance runner currently strips leading `;` lines itself). +- Spelling of constants (`const.u64 0` is provisional) and comparison results (`bool` vs `u1`). +- How `hello` reaches stdout before Phase 2 capabilities exist: a test-only intrinsic, or Phase 2 `io.write` brought forward. +- Whether parse errors get their own `E0xxx` range or join `E5xxx`. diff --git a/docs/spec/00-status-and-conformance.md b/docs/spec/00-status-and-conformance.md new file mode 100644 index 0000000..b73a34e --- /dev/null +++ b/docs/spec/00-status-and-conformance.md @@ -0,0 +1,75 @@ +# 00. Status and Conformance + +Status: Draft 0.1 +Audience: compiler, verifier, runtime and tooling implementers + +## 1. Normative terminology + +The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT and MAY are normative requirements. + +## 2. Conforming implementation + +A conforming Aji implementation consists of: + +- a source frontend or another mechanism that produces valid AIR; +- an AIR verifier; +- either an AIR interpreter or backend whose observable behavior follows the specification; +- the required runtime profile definitions; +- stable machine-readable diagnostics for normative verifier failures. + +A source compiler that emits AIR without running the normative verifier is not a conforming safe Aji implementation. + +## 3. Safe and unsafe Aji + +Safe Aji is code that uses no unsafe operation and depends only on safe public interfaces. + +Safe Aji MUST NOT exhibit, assuming a conforming implementation and correct hardware: + +- use-after-free; +- double-free; +- dangling safe references; +- out-of-bounds memory access; +- uninitialized reads; +- invalid mutable aliasing; +- null dereference through safe references; +- data races involving ordinary memory; +- use of a consumed linear resource; +- forged capabilities. + +Undefined Aji Behavior is restricted to violation of documented unsafe preconditions. + +## 4. Profiles + +A conforming implementation MAY support one or more profiles: + +- `hosted`: operating system, runtime scheduler, I/O and allocator; +- `threaded`: OS threads without the Aji task scheduler; +- `freestanding`: no mandatory OS, heap, task or I/O facilities; +- `deterministic`: runtime-controlled nondeterminism and replay; +- `high-assurance`: rejects unsafe code and optionally rejects runtime-only contract checks. + +Profiles MUST NOT silently change core language semantics. + +## 5. Compatibility + +Version 0.x is experimental. AIR binary formats, source syntax and verifier rules MAY change incompatibly between minor releases. + +Every AIR module MUST encode: + +- AIR format version; +- required feature bits; +- target-independent semantic version; +- optional target requirements. + +## 6. Observable behavior + +The implementation MUST preserve: + +- specified integer overflow behavior; +- specified trap points, except when a proof eliminates an impossible trap; +- synchronization semantics; +- effect/capability checks; +- resource linearity; +- safe memory behavior. + +Optimization MAY remove checks only when their failure is provably impossible. diff --git a/docs/spec/01-language-overview.md b/docs/spec/01-language-overview.md new file mode 100644 index 0000000..a48fb04 --- /dev/null +++ b/docs/spec/01-language-overview.md @@ -0,0 +1,105 @@ +# 01. Language Overview + +## 1. Purpose + +Aji is a low-level systems language optimized for generation, verification and repair by AI agents. + +The language intentionally has a smaller semantic surface than conventional general-purpose systems languages. + +## 2. Explicit by default + +Aji has no implicit: + +- heap allocation; +- reference counting; +- exception propagation; +- destructor execution; +- network/filesystem authority; +- dynamic dispatch; +- integer conversion; +- thread detachment. + +The compiler MAY provide source syntax that lowers to explicit AIR, but the semantic operation MUST remain visible in AIR. + +## 3. Program structure + +Illustrative source: + +```aji +module example; + +fn add(a: u64, b: u64) -> u64 +effects [] +{ + return a + b; +} +``` + +A program is composed of: + +- modules; +- type declarations; +- constants; +- function declarations; +- explicit imports; +- optional contracts; +- explicit effect declarations. + +## 4. Control flow + +Core structured source constructs are: + +- `if` / `else`; +- `while`; +- `for` over verifier-recognized ranges/iterators; +- `match`; +- `break`; +- `continue`; +- `return`. + +AIR lowers these constructs to basic blocks, branches, block parameters and terminators. + +## 5. Error handling + +Aji has no exceptions. + +Fallible operations return `Result`. + +```aji +match fs.read(file, buffer) { + Ok(n) => consume(n), + Err(e) => return Err(e), +} +``` + +Stack unwinding is not part of the language. + +## 6. Trap + +A trap is a defined abnormal termination of the current execution context according to runtime policy. + +Common trap sources: + +- checked arithmetic overflow; +- failed assertion; +- impossible match state in unsafe code; +- bounds failure in trapping indexing; +- explicit `trap`. + +Safe programs SHOULD prefer `Result` for expected failures. + +## 7. Generics + +Aji supports monomorphized generics. + +```aji +fn swap(a: mut, b: mut) { ... } +``` + +Version 0.1 does not require user-defined traits/typeclasses. Generic constraints use compiler-known structural properties such as `Copy`, `Send`, `Share`, `Freeze` and `Local`. + +## 8. Compilation principle + +Aji source is not the normative execution format. AIR is. + +A source feature is acceptable only if its lowering to AIR is deterministic, explicit and mechanically verifiable. diff --git a/docs/spec/02-types-and-values.md b/docs/spec/02-types-and-values.md new file mode 100644 index 0000000..d075802 --- /dev/null +++ b/docs/spec/02-types-and-values.md @@ -0,0 +1,146 @@ +# 02. Types and Values + +## 1. Primitive types + +Unsigned integers: + +```text +u8 u16 u32 u64 u128 usize +``` + +Signed integers: + +```text +i8 i16 i32 i64 i128 isize +``` + +Floating point: + +```text +f32 f64 +``` + +Other primitives: + +```text +bool byte void never +``` + +`byte` is an alias of `u8`. + +`usize` and `isize` match the target pointer width. + +## 2. Integer semantics + +Normal arithmetic is checked. + +```aji +let c = a + b; +``` + +Overflow traps unless the compiler proves it impossible. + +Explicit alternatives: + +```aji +wrap_add(a, b) +saturating_add(a, b) +checked_add(a, b) // Option +``` + +Release/debug modes MUST NOT change these semantics. + +## 3. Composite types + +```aji +[u8; 4096] +slice +slice_mut +(u32, u64) +Option +Result +``` + +Structures: + +```aji +struct Header { + len: u32, + crc: u32, + sequence: u64, +} +``` + +Enums: + +```aji +enum State { + Ready, + Running, + Failed(Error), +} +``` + +## 4. Nullability + +Safe references cannot be null. + +Nullable references use: + +```text +Option> +Option> +``` + +Raw nullable addresses are unsafe-only. + +## 5. Value ownership categories + +A value is one of: + +- copyable value; +- move-only value; +- linear resource; +- borrow. + +Linear resources must be consumed exactly once. + +## 6. Structural properties + +The compiler derives: + +- `Copy`: may be duplicated without changing semantics; +- `Send`: may be moved to another concurrent execution context; +- `Share`: may be observed concurrently through immutable access; +- `Freeze`: can be converted to deeply immutable state; +- `Local`: tied to its current execution context. + +These are semantic properties, not user-extensible traits in v0.1. + +Manual unsafe declarations MAY exist only for FFI/runtime wrappers and MUST state proof obligations. + +## 7. Layout + +Default struct layout is implementation-defined and must not be used for external ABI assumptions. + +ABI-sensitive declarations use explicit representation attributes such as: + +```aji +@repr(C) +struct PacketHeader { ... } +``` + +`@repr(packed)` and `@align(N)` MAY be supported. + +Packed fields do not yield normal aligned references unless alignment is established. + +## 8. Endianness + +Serialization must be explicit: + +```aji +u32.from_le(...) +u32.from_be(...) +u32.to_le(...) +u32.to_be(...) +``` diff --git a/docs/spec/03-memory-model.md b/docs/spec/03-memory-model.md new file mode 100644 index 0000000..174c055 --- /dev/null +++ b/docs/spec/03-memory-model.md @@ -0,0 +1,283 @@ +# 03. Memory and Ownership Model + +This file is normative. Rationale is in RFC 0001. + +## 1. Goals + +Aji memory management must provide: + +- memory safety without tracing GC; +- no implicit allocation; +- stable, inspectable ownership transitions; +- efficient bulk allocation; +- efficient transfer of complex mutable graphs between tasks; +- verifier-friendly alias rules; +- explicit boundaries for unsafe pointer work. + +## 2. Core forms + +```text +Own individually owned dynamic allocation +Region bulk allocation/lifetime domain +Island uniquely owned closed mutable graph +Frozen deeply immutable graph +Arc explicit shared ownership of Share data +ref immutable borrow +mut exclusive mutable borrow +Uninit allocated but not yet initialized +addr unsafe raw address +``` + +## 3. Safe-reference aliasing rule + +For overlapping storage, safe code permits either: + +```text +N immutable borrows: ref +``` + +or: + +```text +1 exclusive mutable borrow: mut +``` + +but never both at the same time. + +The verifier enforces the rule across control flow and task scopes. + +## 4. Borrow lifetime + +A borrow cannot outlive the storage from which it was derived. + +Source syntax may infer local borrow lifetimes. Public APIs whose output lifetime depends on input lifetime must express the relationship. + +Conceptually: + +```aji +fn first<'a, T>(values: slice<'a, T>) -> Option> +``` + +## 5. Provenance + +Every safe reference has logical provenance including: + +- originating allocation or region allocation; +- region generation if applicable; +- byte bounds; +- alignment guarantee; +- access mode. + +Safe code cannot create a reference from an integer. + +Safe pointer arithmetic cannot create a reference outside the originating allocation. + +## 6. Stack storage + +Normal locals live in the current activation frame. + +Their references cannot escape the frame unless the language proves that the target execution context completes before the frame ends, as with structured child tasks. + +## 7. Own + +`Own` is a move-only handle to an individually allocated object. + +```aji +let node: Own = heap.alloc(alloc_cap)?; +``` + +Allocation MUST be explicit and fallible unless an explicitly trapping allocation primitive is used. + +Access occurs through borrows: + +```aji +borrow node as ref n { inspect(n); } +borrow node as mut n { n.value = 42; } +``` + +Deallocation consumes the owner: + +```aji +heap.free(move node); +``` + +## 8. Regions + +A `Region` owns many allocations and releases them collectively. + +```aji +let r = region.create(allocator, limit = 16 MiB)?; +let n = region.alloc(mut r)?; +``` + +Individual region allocations are not freed separately. + +A region may be reset or destroyed. + +```aji +region.reset(mut r); +region.destroy(move r); +``` + +### 8.1 Region generations + +A reset logically increments the region generation. + +Any borrow or reference associated with a prior generation becomes invalid. + +Optimized builds may remove generation checks when statically proven unnecessary. + +### 8.2 Reset precondition + +Reset MUST be rejected when an externally usable safe reference to the current generation remains live. + +## 9. Slices + +A safe slice logically contains: + +```text +provenance + base + length +``` + +Immutable slice: + +```text +slice +``` + +Exclusive mutable slice: + +```text +slice_mut +``` + +Indexing is bounds checked unless eliminated by proof. + +Non-trapping access returns `Option`. + +### 9.1 Disjoint partitioning + +Verifier-recognized operations such as: + +```aji +let (left, right) = slice.split_mut(data, mid); +``` + +establish that the output regions do not overlap. This fact may justify concurrent mutable access. + +## 10. Initialization policy + +Allocation does not imply initialization unless the operation says so. + +Examples: + +```text +region.alloc_uninit uninitialized +region.alloc_zeroed byte-zero initialized where valid for T +region.alloc_value(value) initialized from explicit value +``` + +Zeroing is never silently inserted as a consequence of allocation. + +## 11. Uninitialized memory + +Uninitialized storage has type `Uninit`. + +It cannot be read. + +A write that fully initializes storage changes its verifier state to initialized storage. + +For arrays/buffers the verifier may track initialized prefixes or ranges. + +## 12. Island + +An `Island` is a uniquely owned, closed, transferable graph of mutable memory. + +An island consists of: + +- a root object of type `T`; +- one or more private allocation regions; +- internal references between island objects. + +Properties: + +- move-only ownership; +- mutable by the current owner; +- no external mutable aliases; +- no references from the island into ordinary foreign mutable memory, except explicitly modeled transferable capabilities; +- transferable between tasks without deep copy. + +### 12.1 Internal references + +Island graphs use verifier-recognized `iref` handles for graph edges. + +`iref`: + +- may point only inside the same island; +- may represent cycles; +- cannot be dereferenced without access to the owning island; +- cannot escape as a standalone safe reference. + +### 12.2 Transfer + +Moving an island into a channel or task transfers graph ownership. + +After successful transfer the sender cannot access the island. + +The operation is intended to be O(1) with respect to graph size. + +## 13. Frozen + +`Frozen` is a deeply immutable graph. + +An island may be irreversibly frozen: + +```aji +let immutable = island.freeze(move mutable_graph); +``` + +After freeze, no mutable reference may ever be obtained through safe Aji. + +`Frozen` is `Share` and `Send` when contained external resources permit sharing. + +## 14. Arc + +`Arc` provides explicit shared ownership for `Share` values. + +Reference-count manipulation is explicit: + +```aji +let another = arc.clone(config); +``` + +No operation silently increments a reference count. + +Aji does not recommend `Arc` for arbitrary cyclic object graphs. Cycles should normally be represented inside an `Island` or through stable handles/indices. + +## 15. Stable addresses and pinning + +Region and island allocations are address-stable until reset/destruction. + +For individually owned objects that require address stability, Aji may provide `Pin`. + +Pinning is required for selected FFI, DMA and self-referential runtime structures. + +## 16. Raw addresses + +`addr` is unsafe-only. + +Raw addresses may be null, outlive safe lifetimes, perform arithmetic and cross FFI boundaries. + +Dereference requires unsafe code and documented proof obligations. + +## 17. Unsafe memory obligations + +Unsafe code is responsible for establishing: + +- allocation validity; +- alignment; +- initialization; +- lifetime; +- provenance assumptions required by the backend; +- aliasing discipline; +- synchronization where memory is shared concurrently. diff --git a/docs/spec/04-concurrency-and-atomics.md b/docs/spec/04-concurrency-and-atomics.md new file mode 100644 index 0000000..2c6fde1 --- /dev/null +++ b/docs/spec/04-concurrency-and-atomics.md @@ -0,0 +1,340 @@ +# 04. Concurrency and Atomics + +This file is normative. Rationale is in RFCs 0002 and 0003. + +## 1. Design hierarchy + +Safe Aji SHOULD solve concurrency in this order: + +```text +1. ownership transfer +2. shared immutable data +3. synchronized shared mutable state +4. atomics +5. unsafe raw concurrency +``` + +The language makes weaker, more error-prone mechanisms increasingly explicit. + +## 2. Execution units + +Aji distinguishes: + +- `Task`: runtime-scheduled unit that may migrate between scheduler workers; +- `LocalTask`: task pinned to a scheduler worker because captured state is `Local`; +- `Thread`: operating-system thread handle. + +## 3. Structured task scopes + +Tasks are created inside a lexical/dynamic task scope: + +```aji +task.scope s { + let t = task.spawn(s, worker, move input)?; + let result = task.join(move t)?; +} +``` + +A child task MUST NOT outlive its scope. + +A scope cannot complete while live child handles exist unless they have been explicitly joined, cancel-joined or transferred to a permitted supervisor abstraction. + +Silent detachment is prohibited. + +## 4. Detached execution + +Detached tasks require explicit authority such as `cap`. + +Captured values must be owned, `Send`, and independent of the parent lifetime. + +General application code SHOULD prefer supervisors or structured scopes. + +## 5. Send and Share + +A value moved into a migratable task or thread must satisfy `Send`. + +A value observed concurrently through immutable borrows must satisfy `Share`. + +Thread-affine resources are `Local` and therefore cannot enter migratable tasks. + +## 6. Borrowing into scoped tasks + +A structured child task may borrow parent data if the verifier proves the child completes before the borrowed storage expires. + +Mutable data may be borrowed into multiple child tasks only when the borrowed regions are proven disjoint. + +## 7. Shared mutable state + +Ordinary `mut` may not be concurrently shared. + +Safe shared mutation uses approved synchronization types: + +```text +Mutex +RwLock +Atomic* +Channel +``` + +## 8. Verified interior mutability + +Synchronization wrappers such as `Mutex`, `RwLock` and atomic types are verifier-known interior-mutability abstractions. + +Their internal mutable storage is not directly reachable through ordinary `ref` or `mut` operations. Mutation is exposed only through operations whose synchronization semantics are known to the verifier. + +Ordinary user-defined structs cannot obtain shared interior mutation merely by hiding a mutable field behind a method. Equivalent abstractions require an audited unsafe implementation or a verifier-known intrinsic. + +A synchronization wrapper may therefore be `Share` even though it internally changes state. Its `Share` implementation is defined by the wrapper's synchronization contract, not by ordinary field immutability. + +## 9. Mutex + +A mutex guard is linear and provides exclusive `mut` access. + +```aji +let g = mutex.lock(ref m)?; +modify(g); +mutex.unlock(move g); +``` + +A successful lock has acquire semantics. Unlock has release semantics. + +Mutex guards are not `Send` by default. + +Core mutexes do not automatically implement poisoning because Aji has no exception unwinding. + +## 10. Ordered mutex profile + +Aji MAY provide `OrderedMutex`. + +While holding rank `R`, acquiring a lower/equal forbidden rank is rejected according to profile rules. + +This profile can eliminate a class of lock-order deadlocks but is not required for all programs. + +## 11. RwLock + +`RwLock` permits: + +- multiple read guards yielding `ref`; +- exactly one write guard yielding `mut`. + +Fairness is runtime-specific unless a runtime profile promises otherwise. + +## 12. Channels + +Channels transfer ownership. + +```aji +let (tx, rx) = channel.create(capacity = 1024)?; +channel.send(ref tx, move message)?; +let message = channel.recv(ref rx)?; +``` + +Channels are bounded by default. + +Capacity `0` denotes a rendezvous channel. + +Unbounded queues are library constructs whose allocation behavior must be explicit. + +A successful send synchronizes with the receive that obtains the transferred value. + +## 13. Island messaging + +`Island` is the preferred representation for large mutable messages and object graphs. + +Sending an island transfers ownership without exposing shared mutation. + +## 14. select + +Aji may wait on multiple events: + +```aji +select { + recv(rx1) => ... + recv(rx2) => ... + timer(deadline) => ... + cancelled(token) => ... +} +``` + +When multiple branches are ready, normal mode does not promise source-order selection. Deterministic mode must define a stable choice. + +## 15. Cancellation + +Cancellation is cooperative. + +A task is not asynchronously interrupted at arbitrary instructions. + +Cancellation is observed only at explicit cancellation points, including selected waits, channel operations, timer operations and `task.check_cancel`. + +Structured cancellation propagates from parent to descendants. + +## 16. Cancellation shielding + +A bounded scope may defer cancellation observation: + +```aji +task.cancel_shield { + commit_metadata(); +} +``` + +The cancellation request remains pending and is observed after leaving the shield. + +## 17. Task failure + +Task functions return normal values or `Result`. + +A failing task does not implicitly terminate siblings. Supervision policy is explicit and may implement fail-fast, collect-all, first-success or restart semantics. + +## 18. Blocking + +Operations that block an OS thread declare `thread.block` in their effects. + +A cooperative scheduler may reject direct blocking calls from ordinary tasks and require a blocking pool or dedicated thread. + +## 19. Asynchronous I/O + +An asynchronous operation retains ownership/borrow claims over its buffers until completion. + +```aji +let op = io.read_start(file, borrow mut buffer)?; +// buffer unavailable +let n = io.wait(move op)?; +// buffer available again +``` + +This prevents use or mutation while the OS/runtime may access the buffer. + +## 20. Memory model relations + +Aji defines: + +- `sequenced-before` within one execution unit; +- `synchronizes-with` edges from synchronization operations; +- `happens-before` as the transitive closure of those relations; +- per-atomic-object modification order. + +## 21. Data race + +Two accesses conflict when they overlap and at least one writes. + +A data race exists when conflicting ordinary accesses occur concurrently without a happens-before ordering. + +Safe Aji must reject programs in which such a race is possible under its verified alias/synchronization model. + +## 22. DRF-SC guarantee + +Programs that use only safe synchronization and contain no ordinary-memory data races receive the following guarantee: + +> ordinary-memory observations are explainable by a sequentially consistent interleaving consistent with happens-before. + +Explicit weak atomics may produce weaker observations for atomic coordination. + +## 23. Atomic types + +Initial types: + +```text +AtomicBool +AtomicU8 AtomicU16 AtomicU32 AtomicU64 AtomicUsize +AtomicI8 AtomicI16 AtomicI32 AtomicI64 AtomicIsize +``` + +Support depends on target capabilities. Unsupported widths must be rejected or lowered through a conforming library abstraction with equivalent semantics. + +## 24. Atomic ordering + +Exactly these memory orders are defined: + +```text +relaxed +acquire +release +acq_rel +seq_cst +``` + +There is no `consume`. + +No atomic operation has a default ordering. + +### 24.1 Load + +Allowed: + +```text +relaxed acquire seq_cst +``` + +### 24.2 Store + +Allowed: + +```text +relaxed release seq_cst +``` + +### 24.3 Read-modify-write + +Allowed: + +```text +relaxed acquire release acq_rel seq_cst +``` + +### 24.4 Compare exchange + +Compare exchange declares success and failure orderings separately. Failure ordering cannot be `release` or `acq_rel`. + +## 25. Weak atomics + +Functions that use relaxed atomics SHOULD expose an `atomic.weak` effect or equivalent verifier-visible marker. + +This makes weak-memory code easy to find during audits. + +## 26. Sequential consistency + +`seq_cst` operations participate in a single global total order consistent with each execution unit's sequenced-before relation for those operations. + +## 27. Fences + +Aji supports: + +```text +atomic.fence(acquire) +atomic.fence(release) +atomic.fence(acq_rel) +atomic.fence(seq_cst) +``` + +There is no relaxed fence. + +## 28. Mixing atomic and ordinary access + +Safe code cannot directly access atomic storage as ordinary storage. + +Unsafe code that mixes conflicting atomic and non-atomic accesses must independently satisfy the memory model. Violating those unsafe preconditions is Undefined Aji Behavior. + +## 29. Atomic pointers and reclamation + +Safe v0.1 does not expose arbitrary atomic safe-reference manipulation because publication and reclamation are inseparable problems. + +Lock-free pointer structures should use audited standard-library facilities such as epoch reclamation, hazard pointers or RCU-like mechanisms. + +## 30. ABA + +The verifier does not claim to prove general ABA absence. + +Low-level algorithms must use explicit countermeasures such as generations, tagged values, hazard pointers or epoch reclamation. + +## 31. Progress guarantees + +Aji does not infer lock-free/wait-free guarantees in v0.1. + +Libraries may document an implementation as blocking, obstruction-free, lock-free or wait-free. + +## 32. Deadlock and liveness + +Core Aji does not guarantee deadlock freedom, livelock freedom, starvation freedom or scheduler fairness. + +Optional verification profiles may establish stronger properties for restricted programs. diff --git a/docs/spec/05-effects-and-capabilities.md b/docs/spec/05-effects-and-capabilities.md new file mode 100644 index 0000000..d73f5a9 --- /dev/null +++ b/docs/spec/05-effects-and-capabilities.md @@ -0,0 +1,101 @@ +# 05. Effects and Capabilities + +## 1. Rationale + +Effects answer: **what can this function do?** + +Capabilities answer: **what authority does this invocation possess?** + +Both are part of the program contract. + +## 2. Effects + +Every function has an effect set. + +Pure example: + +```aji +fn checksum(data: slice) -> u32 +effects [] +``` + +Representative effects: + +```text +mem.alloc +mem.map +fs.read +fs.write +io.read +io.write +net.connect +net.listen +net.read +net.write +clock.read +random.read +task.spawn +thread.spawn +thread.block +atomic +atomic.weak +process.spawn +ffi +unsafe +``` + +A caller's effect set must cover transitive callee effects unless the effect is discharged by a verifier-recognized boundary. + +## 3. Capabilities + +Capabilities are unforgeable values created by the host/runtime or delegated by existing authority. + +Example: + +```aji +fn load( + fs: cap, + path: slice +) -> Result +effects [fs.read] +``` + +Without the capability, the operation cannot be performed even if the function declares the effect. + +## 4. Narrowing + +Capabilities may be narrowed but not widened. + +A broad filesystem capability may yield a capability limited to: + +- read-only access; +- a path prefix; +- a mount; +- an already-open resource; +- a bounded operation set. + +## 5. Capability transfer + +Capabilities may have ownership semantics: + +- copyable/read-only authority; +- move-only authority; +- local-only authority; +- delegatable authority. + +The capability type defines its transfer rules. + +## 6. Build/runtime separation + +Compilation does not imply runtime authority. + +A program may compile with a declared effect set yet fail to instantiate because the host does not grant matching capabilities. + +## 7. Auditability + +The toolchain should be able to emit: + +- declared effect graph; +- capability requirements per entry point; +- effective transitive authority; +- unsafe/FFI authority boundaries. diff --git a/docs/spec/06-resources-and-errors.md b/docs/spec/06-resources-and-errors.md new file mode 100644 index 0000000..501954c --- /dev/null +++ b/docs/spec/06-resources-and-errors.md @@ -0,0 +1,60 @@ +# 06. Resources and Errors + +## 1. Linear resources + +External resources are linear unless explicitly documented otherwise. + +Examples: + +```text +File +Socket +Thread +Task +Mapping +Timer +Device +``` + +A linear resource must be consumed by exactly one valid terminal action such as close, join, release or ownership transfer. + +The verifier rejects double consumption and use after consumption. + +## 2. Typestate + +Resources MAY encode state transitions in types. + +Example socket states: + +```text +Socket +Socket +Socket +Socket +Socket +``` + +A transition consumes one state and returns another. + +## 3. Cleanup + +Aji may provide `defer` as syntax sugar: + +```aji +let file = fs.open(...)?; +defer fs.close(move file); +``` + +AIR must contain explicit cleanup control-flow edges. Aji has no hidden destructors. + +## 4. Result + +Expected failure uses `Result`. + +Propagation syntax may exist only if its lowering is explicit and does not introduce exceptions or unwinding. + +## 5. Trap versus Result + +Use `Result` for failures callers may reasonably handle. + +Use trap for invariant violations, failed assertions and explicitly trapping primitives. diff --git a/docs/spec/07-air.md b/docs/spec/07-air.md new file mode 100644 index 0000000..880dedf --- /dev/null +++ b/docs/spec/07-air.md @@ -0,0 +1,184 @@ +# 07. AIR — Aji Intermediate Representation + +## 1. Role + +AIR is the canonical semantic representation of Aji. + +Source syntax is optional tooling. AIR is mandatory for conformance. + +AIR is: + +- typed; +- SSA-oriented; +- basic-block based; +- explicit about ownership and borrows; +- explicit about effects and capabilities; +- explicit about synchronization; +- deterministic to parse and verify. + +## 2. Functions and blocks + +Illustrative AIR: + +```text +fn @sum(%a: u64, %b: u64) -> u64 +effects [] + +entry: + %0 = add.checked.u64 %a, %b + ret %0 +``` + +Blocks receive values through block parameters rather than implicit phi nodes: + +```text +br @loop(%next) + +loop(%i: u64): + ... +``` + +## 3. Core instruction classes + +### Values and arithmetic + +```text +const +copy +move +add.checked +sub.checked +mul.checked +div.checked +add.wrap +sub.wrap +mul.wrap +and or xor +shl shr +eq ne lt le gt ge +``` + +### Control flow + +```text +br +cbr +switch +ret +trap +guard +assert +``` + +### Borrowing and memory + +```text +borrow.ref +borrow.mut +borrow.end +load +store +mem.copy +mem.zero +slice.make +slice.sub +``` + +### Ownership + +```text +own.alloc +own.free +region.create +region.alloc +region.alloc_uninit +region.reset +region.destroy +island.create +island.alloc +island.freeze +arc.clone +arc.release +``` + +### Calls + +```text +call +call.indirect +intrinsic.call +``` + +### Concurrency + +```text +task.scope.begin +task.scope.end +task.spawn +task.join +task.cancel +thread.spawn +thread.join +channel.send +channel.recv +mutex.lock +mutex.unlock +rwlock.read +rwlock.write +atomic.load +atomic.store +atomic.rmw +atomic.cmpxchg +atomic.fence +``` + +## 4. Instruction contract + +Every AIR instruction definition must specify: + +- operand types; +- result types; +- ownership-state transition; +- borrow-state transition; +- memory reads/writes; +- synchronization effects; +- effect requirements; +- capability requirements; +- trap behavior; +- verifier transfer function. + +## 5. No hidden semantics + +AIR does not contain: + +- hidden destructors; +- implicit allocation; +- implicit exception edges; +- default memory orderings; +- implicit task detachment. + +## 6. Serialization + +Canonical AIR should have both text and binary forms. + +Binary AIR conceptually contains: + +```text +HEADER +TYPE_TABLE +CONSTANT_TABLE +CAPABILITY_TABLE +FUNCTION_TABLE +BLOCK_TABLE +INSTRUCTION_STREAM +CONTRACT_TABLE +DEBUG_TABLE +``` + +Every binary must encode version and required feature bits. + +## 7. Verification before execution + +Native code must not be produced from unverified safe AIR. + +Unsafe AIR modules are allowed only through explicit trusted/unsafe boundaries and must appear in the unsafe dependency report. diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md new file mode 100644 index 0000000..c981182 --- /dev/null +++ b/docs/spec/08-verifier.md @@ -0,0 +1,119 @@ +# 08. Verifier + +## 1. Role + +The verifier is part of Aji's language semantics, not an optional lint pass. + +A safe module that fails verification is not an executable Aji program. + +## 2. Required passes + +A conforming verifier performs, directly or equivalently: + +1. type verification; +2. SSA/control-flow verification; +3. initialization verification; +4. ownership verification; +5. borrow/alias verification; +6. region lifetime and generation verification; +7. island closure verification; +8. linear-resource verification; +9. effect verification; +10. capability verification; +11. `Send`/`Share` verification; +12. task-scope verification; +13. synchronization and atomic-ordering validation; +14. range/bounds verification; +15. unsafe-boundary verification. + +## 3. Per-value abstract state + +The verifier may track: + +```text +type +initialization state +ownership state +borrow state +provenance +region and generation +bounds +alignment +integer range +Send/Share/Local properties +task scope +resource state +``` + +## 4. Ownership state machine + +Representative states: + +```text +AVAILABLE +MOVED +BORROWED_SHARED(n) +BORROWED_MUT +CONSUMED +``` + +Transitions are instruction-defined. + +A moved or consumed value cannot be reused unless a later operation returns a distinct new value. + +## 5. Path sensitivity + +The verifier propagates facts through branches. + +Example: + +```aji +if i < len(data) { + let x = data[i]; +} +``` + +Inside the branch, `i < len(data)` is available as a proof fact. + +## 6. Guards + +`guard condition` records a verifier-recognized condition on the continuing path. + +It may justify elimination of later runtime checks. + +## 7. Bounded analysis + +Verifier algorithms must have deterministic resource budgets. + +If verification exceeds configured/spec-defined complexity bounds, the verifier emits a stable failure rather than silently weakening checks. + +## 8. Contracts + +Contracts may be classified as: + +```text +PROVEN_STATICALLY +CHECKED_AT_RUNTIME +ASSUMED_UNSAFE +UNPROVEN +``` + +A high-assurance profile may reject `UNPROVEN` or `ASSUMED_UNSAFE` results. + +## 9. Concurrency verification + +The verifier must reject: + +- task lifetime escape; +- transfer of non-`Send` values to migratable tasks/threads; +- concurrent mutable aliases not proven disjoint; +- sharing non-`Share` values through concurrent immutable access; +- use of moved channel messages; +- accessing async I/O buffers while an outstanding operation owns/borrows them; +- illegal atomic memory orders. + +## 10. Diagnostics + +Every normative verifier rejection has a stable machine-readable code. + +Diagnostics should include enough structured state for an agent to repair the program without parsing prose. diff --git a/docs/spec/09-runtime-and-abi.md b/docs/spec/09-runtime-and-abi.md new file mode 100644 index 0000000..7a2c2e0 --- /dev/null +++ b/docs/spec/09-runtime-and-abi.md @@ -0,0 +1,72 @@ +# 09. Runtime, FFI and ABI + +## 1. Runtime principle + +The runtime should be small, explicit and auditable. + +Core responsibilities may include: + +- allocator adapters; +- task scheduler; +- synchronization primitives; +- I/O integration; +- capability materialization; +- platform intrinsics; +- deterministic/replay hooks. + +## 2. System calls + +Direct syscalls are runtime/unsafe-only by default. + +A syscall wrapper must describe: + +- argument types; +- memory read/write regions; +- created/consumed resources; +- effects; +- failure behavior; +- blocking behavior. + +## 3. FFI + +Foreign calls are explicit and unsafe unless wrapped in a verified safe abstraction. + +Illustrative declaration: + +```aji +extern "C" +unsafe fn read( + fd: i32, + buf: addr, + len: usize +) -> isize +effects [ffi]; +``` + +Safe wrappers must state and uphold ownership, aliasing and thread-safety assumptions. + +## 4. Volatile + +`volatile.load` and `volatile.store` affect compiler access elimination/reordering as defined by the volatile contract. + +Volatile does not itself imply atomicity or inter-thread synchronization. + +## 5. MMIO + +Device memory should use a distinct `Mmio` abstraction obtained through `cap`. + +CPU-memory atomics and device-ordering barriers are separate concepts. + +## 6. DMA + +DMA buffers are explicitly pinned. A buffer cannot be freed, reset or physically relocated while a device operation owns it. + +## 7. Signal/interrupt profiles + +Signal and interrupt handlers use restricted capabilities/effects. Allocation, ordinary locking and blocking I/O are forbidden unless a profile explicitly defines a safe mechanism. + +## 8. Backend + +The initial native backend should lower AIR to LLVM IR. + +A custom native backend is deferred until AIR and verifier semantics stabilize. diff --git a/docs/spec/10-diagnostics-and-agent-protocol.md b/docs/spec/10-diagnostics-and-agent-protocol.md new file mode 100644 index 0000000..403e345 --- /dev/null +++ b/docs/spec/10-diagnostics-and-agent-protocol.md @@ -0,0 +1,97 @@ +# 10. Diagnostics and Agent Protocol + +## 1. Goal + +Aji diagnostics are an API for automated repair, not only human-readable messages. + +## 2. Stable codes + +Every verifier/compiler error has: + +- stable code; +- stable machine kind; +- structured fields; +- optional human explanation; +- optional non-binding repair candidates. + +Example: + +```json +{ + "code": "E2104", + "kind": "memory.region_generation", + "function": "decode", + "value": "%17", + "region": "%3", + "expected_generation": 5, + "found_generation": 4, + "reset_instruction": 84, + "use_instruction": 91 +} +``` + +## 3. Repair candidates + +The compiler may emit structured suggestions: + +```json +{ + "repair_candidates": [ + {"kind": "move_reset_after_use"}, + {"kind": "copy_value_before_reset"} + ] +} +``` + +Suggestions never modify semantics automatically. + +## 4. ajid + +`ajid` is the long-running machine interface. + +Initial methods: + +```text +parse +typecheck +verify +compile +run +test +trace +inspect +explain +benchmark +``` + +## 5. Expected repair loop + +```text +agent patch + ↓ +ajid.verify + ↓ +structured errors + ↓ +agent repair + ↓ +ajid.test + ↓ +schedule exploration + ↓ +benchmark +``` + +## 6. Verification report + +The toolchain should emit an audit artifact containing: + +- unsafe sites; +- remaining runtime checks; +- eliminated bounds checks; +- ownership/borrow proof summaries; +- capability requirements; +- effect graph; +- weak atomic sites; +- lock-order findings; +- contract status. diff --git a/docs/spec/11-determinism-and-replay.md b/docs/spec/11-determinism-and-replay.md new file mode 100644 index 0000000..d575b29 --- /dev/null +++ b/docs/spec/11-determinism-and-replay.md @@ -0,0 +1,63 @@ +# 11. Determinism, Trace and Replay + +## 1. Interpreter + +The reference AIR interpreter defines executable semantic behavior for the language model. + +## 2. Trace + +Trace mode may record each AIR instruction and selected abstract-state changes. + +Example: + +```text +#120 region.create -> r3 +#121 region.alloc r3 4096 -> p8 +#122 borrow.mut p8 -> b4 +#123 store.u32 b4 10 +#124 borrow.end b4 +``` + +## 3. Deterministic mode + +Deterministic execution controls or records sources of nondeterminism including: + +- task scheduling choices; +- timer progression; +- clock reads; +- random inputs; +- I/O completion ordering; +- channel wake selection; +- selected filesystem/network inputs. + +## 4. Replay + +A recorded execution should be replayable when program, runtime and replay-format compatibility requirements are met. + +```text +aji run --record failure.ajr app.aji +aji replay failure.ajr +``` + +## 5. Concurrency exploration + +Test mode may systematically or pseudo-randomly vary scheduling at synchronization points. + +Candidate scheduling points include: + +- atomic operations; +- lock/unlock; +- channel send/receive; +- task yield/wake; +- I/O completion; +- cancellation observation. + +Example: + +```text +aji test --interleavings=10000 +``` + +## 6. Deterministic selection + +When `select` has multiple ready branches, deterministic mode must choose according to a stable rule and record the decision. diff --git a/docs/spec/12-packages-and-build.md b/docs/spec/12-packages-and-build.md new file mode 100644 index 0000000..dc0273f --- /dev/null +++ b/docs/spec/12-packages-and-build.md @@ -0,0 +1,45 @@ +# 12. Packages and Build + +## 1. Manifest + +A package contains an `aji.toml` manifest. + +Illustrative manifest: + +```toml +[package] +name = "aji-log" +version = "0.1.0" + +[target] +os = "linux" +arch = "x86_64" + +[capabilities] +filesystem = ["read", "write"] +network = false +``` + +## 2. Reproducibility + +Given the same: + +- source; +- compiler version; +- dependency lock; +- target; +- feature set; + +build graph evaluation must be deterministic. + +## 3. Build scripts + +Packages cannot execute arbitrary host code merely because they are dependencies. + +Any build extension must be explicitly declared, sandboxed and capability-limited. + +## 4. Dependencies + +Dependencies should be content-addressed or lockfile-pinned. + +The package system should record unsafe/runtime dependencies separately from ordinary safe source dependencies. diff --git a/docs/spec/13-contracts-and-unsafe.md b/docs/spec/13-contracts-and-unsafe.md new file mode 100644 index 0000000..7fb885a --- /dev/null +++ b/docs/spec/13-contracts-and-unsafe.md @@ -0,0 +1,86 @@ +# 13. Contracts and Unsafe Boundaries + +## 1. Contracts + +Functions may declare preconditions and postconditions. Types/modules may declare invariants. + +```aji +fn append(log: mut, data: slice) -> Result +requires { + len(data) <= 16 MiB +} +ensures { + result.is_ok() => log.offset >= old(log.offset) +} +effects [fs.write] +{ + ... +} +``` + +The verifier reports each contract as one of: + +```text +PROVEN_STATICALLY +CHECKED_AT_RUNTIME +ASSUMED_UNSAFE +UNPROVEN +``` + +A high-assurance profile may reject runtime-only or unproven obligations. + +## 2. Assertions and guards + +`assert condition` is a runtime-visible correctness check unless statically proven. Failure traps. + +`guard condition` both checks the condition as required by its form and introduces a path fact to the verifier. + +`assume condition` is unsafe-only because it introduces a proof fact without checking it. + +## 3. Unsafe + +Unsafe operations occur only in an explicit `unsafe` block/function/module. + +Unsafe does not disable the type system globally. It enables specific operations whose safety obligations cannot be established by the normal verifier. + +Typical unsafe facilities: + +```text +addr dereference +pointer arithmetic +FFI +direct syscalls +inline assembly +manual Send/Share declarations +custom synchronization primitives +``` + +## 4. Unsafe proof obligations + +Unsafe code must document applicable obligations, including: + +- valid allocation/provenance; +- alignment; +- initialization; +- lifetime; +- aliasing; +- synchronization; +- ABI assumptions; +- resource-state assumptions. + +Violation of an unsafe precondition may cause Undefined Aji Behavior. + +## 5. Unsafe dependency report + +The toolchain should produce a machine-readable report containing: + +```text +application unsafe blocks +unsafe standard-library modules +raw dereference sites +inline assembly sites +FFI boundaries +manual Send/Share declarations +``` + +This report is part of the audit surface for agent-generated systems. diff --git a/docs/spec/INDEX.md b/docs/spec/INDEX.md new file mode 100644 index 0000000..1593840 --- /dev/null +++ b/docs/spec/INDEX.md @@ -0,0 +1,18 @@ +# Aji Specification Index + +| File | Status | Topic | +|---|---|---| +| 00-status-and-conformance.md | Normative draft | Conformance, safety, profiles | +| 01-language-overview.md | Normative draft | Language shape and control flow | +| 02-types-and-values.md | Normative draft | Primitive/composite types, properties | +| 03-memory-model.md | Normative draft | Ownership, regions, islands, frozen graphs | +| 04-concurrency-and-atomics.md | Normative draft | Tasks, synchronization, memory model, atomics | +| 05-effects-and-capabilities.md | Normative draft | Authority and effect tracking | +| 06-resources-and-errors.md | Normative draft | Linear resources and error handling | +| 07-air.md | Normative draft | Canonical IR | +| 08-verifier.md | Normative draft | Verification rules | +| 09-runtime-and-abi.md | Normative draft | Runtime, FFI, MMIO/DMA | +| 10-diagnostics-and-agent-protocol.md | Normative draft | Stable diagnostics and ajid | +| 11-determinism-and-replay.md | Normative draft | Deterministic testing/replay | +| 12-packages-and-build.md | Normative draft | Manifest/build model | +| 13-contracts-and-unsafe.md | Normative draft | Contracts, proof status and unsafe boundaries | diff --git a/examples/append_log.aji b/examples/append_log.aji new file mode 100644 index 0000000..1db5251 --- /dev/null +++ b/examples/append_log.aji @@ -0,0 +1,52 @@ +module examples.append_log; + +const HEADER_SIZE: usize = 16; + +struct Header { + len: u32, + crc: u32, + sequence: u64, +} + +struct Log { + file: File, + offset: u64, +} + +fn encode_header(header: ref
) -> [u8; HEADER_SIZE] +effects [] +{ + var out = [0u8; HEADER_SIZE]; + bytes.put_u32_le(mut out, 0, header.len); + bytes.put_u32_le(mut out, 4, header.crc); + bytes.put_u64_le(mut out, 8, header.sequence); + return out; +} + +fn append( + log: mut, + data: slice +) -> Result +requires { + len(data) <= 16 MiB +} +effects [fs.write] +{ + let crc = crc32c(data); + let len32 = checked_cast(len(data))?; + + let header = Header { + len: len32, + crc: crc, + sequence: log.offset, + }; + let encoded = encode_header(ref header); + + fs.write_all(ref log.file, slice.of(encoded))?; + fs.write_all(ref log.file, data)?; + + let old = log.offset; + log.offset = checked_add(log.offset, HEADER_SIZE + len(data))?; + + return Ok(old); +} diff --git a/examples/atomic_publish.aji b/examples/atomic_publish.aji new file mode 100644 index 0000000..5627e37 --- /dev/null +++ b/examples/atomic_publish.aji @@ -0,0 +1,25 @@ +module examples.atomic_publish; + +struct Shared { + ready: AtomicBool, + value: AtomicU64, +} + +fn publish(shared: ref, value: u64) -> void +effects [atomic] +{ + atomic.store(ref shared.value, value, relaxed); + atomic.store(ref shared.ready, true, release); +} + +fn try_read(shared: ref) -> Option +effects [atomic] +{ + if atomic.load(ref shared.ready, acquire) { + // The acquire observes the release on `ready`; the earlier relaxed + // store to `value` is ordered before publication. `value` remains + // atomic storage, so no ordinary-memory alias exception is needed. + return Some(atomic.load(ref shared.value, relaxed)); + } + return None; +} diff --git a/examples/channel_transfer.aji b/examples/channel_transfer.aji new file mode 100644 index 0000000..133ca7a --- /dev/null +++ b/examples/channel_transfer.aji @@ -0,0 +1,23 @@ +module examples.channel_transfer; + +struct Message { + id: u64, +} + +fn producer( + tx: ref>>, + alloc: cap +) -> Result +effects [mem.alloc] +{ + var message = island.create(alloc, Message { id: 0 })?; + + borrow message as mut root { + root.id = 42; + } + + channel.send(tx, move message)?; + + // message is MOVED and cannot be used here. + return Ok(); +} diff --git a/examples/file_copy.aji b/examples/file_copy.aji new file mode 100644 index 0000000..56d7c0b --- /dev/null +++ b/examples/file_copy.aji @@ -0,0 +1,32 @@ +module examples.file_copy; + +fn copy( + fs_read: cap, + fs_write: cap, + src: slice, + dst: slice, + alloc: cap +) -> Result +effects [mem.alloc, fs.read, fs.write] +{ + let input = fs.open_read(fs_read, src)?; + defer fs.close(move input); + + let output = fs.open_write(fs_write, dst)?; + defer fs.close(move output); + + var region = region.create(alloc, limit = 64 KiB)?; + defer region.destroy(move region); + + let buffer = region.alloc_zeroed_array(mut region, 64 KiB)?; + + while true { + let n = fs.read(ref input, buffer)?; + if n == 0 { + break; + } + fs.write_all(ref output, slice.prefix(buffer, n))?; + } + + return Ok(); +} diff --git a/examples/hello.aji b/examples/hello.aji new file mode 100644 index 0000000..68c842b --- /dev/null +++ b/examples/hello.aji @@ -0,0 +1,10 @@ +module examples.hello; + +fn main( + stdout: cap +) -> Result +effects [io.write] +{ + io.stdout_write(stdout, "hello from aji\n")?; + return Ok(); +} diff --git a/examples/parallel_map.aji b/examples/parallel_map.aji new file mode 100644 index 0000000..eda6986 --- /dev/null +++ b/examples/parallel_map.aji @@ -0,0 +1,26 @@ +module examples.parallel_map; + +fn square_half(values: slice_mut) -> void +effects [] +{ + for i in 0..len(values) { + values[i] = values[i] * values[i]; + } +} + +fn square_all(values: slice_mut) -> Result +effects [task.spawn] +{ + let mid = len(values) / 2; + let (left, right) = slice.split_mut(values, mid); + + task.scope s { + let a = task.spawn_borrow_mut(s, square_half, left)?; + let b = task.spawn_borrow_mut(s, square_half, right)?; + + task.join(move a)?; + task.join(move b)?; + } + + return Ok(); +} diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..2886ecf --- /dev/null +++ b/mise.toml @@ -0,0 +1,2 @@ +[tools] +zig = "0.17.0" diff --git a/src/air.zig b/src/air.zig new file mode 100644 index 0000000..c9c7a39 --- /dev/null +++ b/src/air.zig @@ -0,0 +1,12 @@ +//! AIR — Aji Intermediate Representation (spec 07, RFC 0004). +//! +//! Phase 0 deliverables (docs/roadmap/phase-0.md): +//! - type and value model; +//! - text AIR lexer, parser and canonical serializer; +//! - functions, basic blocks with block parameters, terminators. +//! +//! Text AIR is the canonical interchange until opcode numbering freezes +//! (RFC 0004 "Binary stability"). + +/// Bumped on any incompatible change to text or binary AIR (spec 00 §5). +pub const format_version: u32 = 0; diff --git a/src/check.zig b/src/check.zig new file mode 100644 index 0000000..8cdbc82 --- /dev/null +++ b/src/check.zig @@ -0,0 +1,30 @@ +//! Front door used by the CLI, the conformance runner and (later) `ajid`: +//! parse → verify, collecting diagnostics. + +const std = @import("std"); +const diag = @import("diag.zig"); + +pub const Status = enum { + /// Module verified; no error diagnostics. + accepted, + /// At least one error diagnostic. + rejected, + /// The pipeline cannot yet decide this input. + unimplemented, +}; + +pub const Report = struct { + status: Status, + diagnostics: []const diag.Diagnostic, + /// Pipeline stage that is missing when `status == .unimplemented`. + missing_stage: []const u8 = "", +}; + +/// Checks a text AIR module. All allocations go into `arena`. +pub fn checkAir(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report { + _ = arena; + _ = file_name; + _ = source; + // TODO(phase-0): air.parse → verifier.verify. + return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = "air.parse" }; +} diff --git a/src/diag.zig b/src/diag.zig new file mode 100644 index 0000000..dd4a414 --- /dev/null +++ b/src/diag.zig @@ -0,0 +1,179 @@ +//! Stable machine-readable diagnostics (spec 10). +//! +//! Diagnostics are an API for automated repair. Codes and kinds are stable +//! once released; `registry` MUST mirror docs/reference/error-codes.md, which +//! is enforced by the test at the bottom of this file. + +const std = @import("std"); + +pub const Code = struct { + /// Stable identifier, e.g. "E2001". + id: []const u8, + /// Stable machine kind, e.g. "ownership.use_after_move". + kind: []const u8, + /// Short human description. Not part of the stable contract. + meaning: []const u8, +}; + +pub const registry = [_]Code{ + // E1xxx — Types and values + .{ .id = "E1001", .kind = "type.mismatch", .meaning = "Operand/result type mismatch" }, + .{ .id = "E1002", .kind = "type.invalid_cast", .meaning = "Cast not permitted by safe semantics" }, + .{ .id = "E1010", .kind = "init.read_uninitialized", .meaning = "Read from uninitialized storage" }, + // E2xxx — Memory and ownership + .{ .id = "E2001", .kind = "ownership.use_after_move", .meaning = "Value used after ownership transfer" }, + .{ .id = "E2002", .kind = "ownership.double_consume", .meaning = "Linear value consumed twice" }, + .{ .id = "E2101", .kind = "borrow.mutable_alias", .meaning = "Overlapping exclusive/shared borrow violation" }, + .{ .id = "E2102", .kind = "borrow.outlives_owner", .meaning = "Borrow may outlive backing storage" }, + .{ .id = "E2103", .kind = "memory.out_of_bounds", .meaning = "Access not proven in bounds" }, + .{ .id = "E2104", .kind = "memory.region_generation", .meaning = "Reference belongs to invalidated region generation" }, + .{ .id = "E2110", .kind = "island.escape", .meaning = "Island-internal reference escapes island" }, + .{ .id = "E2111", .kind = "island.foreign_mutable_edge", .meaning = "Island graph points to forbidden foreign mutable storage" }, + // E3xxx — Resources/capabilities/effects + .{ .id = "E3001", .kind = "resource.use_after_consume", .meaning = "Closed/joined/released resource reused" }, + .{ .id = "E3002", .kind = "resource.leak", .meaning = "Linear resource has no terminal consumption path" }, + .{ .id = "E3101", .kind = "effect.undeclared", .meaning = "Callee effect absent from caller contract" }, + .{ .id = "E3201", .kind = "capability.missing", .meaning = "Required authority unavailable" }, + .{ .id = "E3202", .kind = "capability.widen", .meaning = "Attempt to widen delegated authority" }, + // E4xxx — Concurrency + .{ .id = "E4001", .kind = "concurrency.not_send", .meaning = "Non-Send value moved to migratable task/thread" }, + .{ .id = "E4002", .kind = "concurrency.not_share", .meaning = "Non-Share value concurrently shared" }, + .{ .id = "E4101", .kind = "concurrency.possible_data_race", .meaning = "Conflicting ordinary access not ordered/synchronized" }, + .{ .id = "E4201", .kind = "atomic.invalid_order", .meaning = "Memory ordering invalid for atomic operation" }, + .{ .id = "E4301", .kind = "task.live_child_escape", .meaning = "Scope exits with live child task" }, + .{ .id = "E4302", .kind = "task.borrow_escape", .meaning = "Child task borrow can outlive parent storage" }, + .{ .id = "E4303", .kind = "io.buffer_in_flight", .meaning = "Buffer accessed while async operation owns/borrows it" }, + // E5xxx — AIR/verifier + .{ .id = "E5001", .kind = "air.invalid_ssa", .meaning = "SSA definition/dominance failure" }, + .{ .id = "E5002", .kind = "air.invalid_cfg", .meaning = "Invalid block/terminator structure" }, + .{ .id = "E5101", .kind = "verifier.resource_limit", .meaning = "Deterministic verifier resource limit exceeded" }, + // E6xxx — Unsafe/ABI + .{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary" }, + .{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" }, +}; + +pub fn lookup(id: []const u8) ?*const Code { + for (®istry) |*c| { + if (std.mem.eql(u8, c.id, id)) return c; + } + return null; +} + +pub const Severity = enum { @"error", warning, note }; + +pub const Span = struct { + file: []const u8, + /// 1-based. + line: u32, + /// 1-based, in bytes. + col: u32, +}; + +/// Structured, code-specific payload (e.g. "value": "%17"). +pub const Field = struct { + name: []const u8, + value: Value, + + pub const Value = union(enum) { + int: i64, + str: []const u8, + }; +}; + +pub const Diagnostic = struct { + code: *const Code, + severity: Severity = .@"error", + span: ?Span = null, + /// Optional human explanation. Agents MUST NOT need to parse it. + message: []const u8 = "", + fields: []const Field = &.{}, + /// Non-binding structured suggestions (spec 10 §3). + repair_candidates: []const []const u8 = &.{}, + + /// Writes the diagnostic as a single JSON object (no trailing newline). + /// Key order is fixed so output is byte-for-byte deterministic. + pub fn writeJson(d: Diagnostic, w: *std.Io.Writer) std.Io.Writer.Error!void { + var s: std.json.Stringify = .{ .writer = w }; + try s.beginObject(); + try s.objectField("code"); + try s.write(d.code.id); + try s.objectField("kind"); + try s.write(d.code.kind); + try s.objectField("severity"); + try s.write(@tagName(d.severity)); + if (d.span) |sp| { + try s.objectField("file"); + try s.write(sp.file); + try s.objectField("line"); + try s.write(sp.line); + try s.objectField("col"); + try s.write(sp.col); + } + for (d.fields) |f| { + try s.objectField(f.name); + switch (f.value) { + inline else => |v| try s.write(v), + } + } + if (d.message.len != 0) { + try s.objectField("message"); + try s.write(d.message); + } + if (d.repair_candidates.len != 0) { + try s.objectField("repair_candidates"); + try s.beginArray(); + for (d.repair_candidates) |kind| { + try s.beginObject(); + try s.objectField("kind"); + try s.write(kind); + try s.endObject(); + } + try s.endArray(); + } + try s.endObject(); + } +}; + +test "writeJson is deterministic and structured" { + var buf: [512]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const d: Diagnostic = .{ + .code = lookup("E2104").?, + .span = .{ .file = "decode.air", .line = 12, .col = 5 }, + .fields = &.{ + .{ .name = "value", .value = .{ .str = "%17" } }, + .{ .name = "expected_generation", .value = .{ .int = 5 } }, + }, + .repair_candidates = &.{"move_reset_after_use"}, + }; + try d.writeJson(&w); + try std.testing.expectEqualStrings( + \\{"code":"E2104","kind":"memory.region_generation","severity":"error","file":"decode.air","line":12,"col":5,"value":"%17","expected_generation":5,"repair_candidates":[{"kind":"move_reset_after_use"}]} + , w.buffered()); +} + +test "registry mirrors docs/reference/error-codes.md" { + const md = @embedFile("error_codes_md"); + var seen: usize = 0; + var lines = std.mem.splitScalar(u8, md, '\n'); + while (lines.next()) |line| { + // Table rows look like: | E1001 | type.mismatch | Meaning | + if (!std.mem.startsWith(u8, line, "| E")) continue; + var cols = std.mem.tokenizeScalar(u8, line, '|'); + const id = std.mem.trim(u8, cols.next().?, " "); + const kind = std.mem.trim(u8, cols.next().?, " "); + const code = lookup(id) orelse { + std.debug.print("code {s} is in error-codes.md but not in diag.registry\n", .{id}); + return error.RegistryOutOfSync; + }; + try std.testing.expectEqualStrings(kind, code.kind); + seen += 1; + } + try std.testing.expectEqual(registry.len, seen); +} + +test "registry ids are unique" { + for (registry, 0..) |a, i| { + for (registry[i + 1 ..]) |b| try std.testing.expect(!std.mem.eql(u8, a.id, b.id)); + } +} diff --git a/src/interp.zig b/src/interp.zig new file mode 100644 index 0000000..0968dc6 --- /dev/null +++ b/src/interp.zig @@ -0,0 +1,6 @@ +//! AIR interpreter (spec 07, spec 11). Defines observable semantics. +//! +//! Requirements: +//! - executes only verified AIR; +//! - deterministic: identical input and seed give identical output and trace; +//! - traps are explicit values, never host panics or unwinding. diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..dabae4c --- /dev/null +++ b/src/main.zig @@ -0,0 +1,95 @@ +//! `aji` command-line driver. +//! +//! Output contract (stable, consumed by agents): +//! - diagnostics go to stdout as JSON Lines, one object per line; +//! - human-oriented notes go to stderr; +//! - exit codes: 0 accepted, 1 rejected, 2 usage or I/O error, +//! 3 input not decidable yet (pipeline stage unimplemented). + +const std = @import("std"); +const aji = @import("aji"); + +const usage = + \\usage: aji [args] + \\ + \\commands: + \\ check parse and verify a text AIR module + \\ codes list diagnostic codes as JSON Lines + \\ explain show one diagnostic code + \\ version print toolchain version + \\ +; + +const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3 }; + +pub fn main(init: std.process.Init) !void { + const arena = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(arena); + + var stdout_buf: [4096]u8 = undefined; + var stdout_fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf); + const out = &stdout_fw.interface; + + const code = run(io, arena, args, out) catch |err| switch (err) { + error.WriteFailed => return stdout_fw.err.?, + else => |e| return e, + }; + try out.flush(); + std.process.exit(@backingInt(code)); +} + +fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *std.Io.Writer) !ExitCode { + if (args.len < 2) { + std.debug.print("{s}", .{usage}); + return .usage; + } + const cmd = args[1]; + if (std.mem.eql(u8, cmd, "version")) { + try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version }); + return .accepted; + } + if (std.mem.eql(u8, cmd, "codes")) { + for (aji.diag.registry) |c| try writeCode(out, c); + return .accepted; + } + if (std.mem.eql(u8, cmd, "explain")) { + if (args.len != 3) return usageError("explain takes exactly one code"); + const c = aji.diag.lookup(args[2]) orelse return usageError("unknown diagnostic code"); + try writeCode(out, c.*); + return .accepted; + } + if (std.mem.eql(u8, cmd, "check")) { + if (args.len != 3) return usageError("check takes exactly one file"); + const path = args[2]; + 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 }); + return .usage; + }; + const report = try aji.check.checkAir(arena, path, source); + for (report.diagnostics) |d| { + try d.writeJson(out); + try out.writeByte('\n'); + } + return switch (report.status) { + .accepted => .accepted, + .rejected => .rejected, + .unimplemented => { + std.debug.print("aji: not implemented yet: {s}\n", .{report.missing_stage}); + return .unimplemented; + }, + }; + } + return usageError("unknown command"); +} + +fn writeCode(out: *std.Io.Writer, c: aji.diag.Code) !void { + var s: std.json.Stringify = .{ .writer = out }; + try s.write(.{ .code = c.id, .kind = c.kind, .meaning = c.meaning }); + try out.writeByte('\n'); +} + +fn usageError(msg: []const u8) ExitCode { + std.debug.print("aji: {s}\n\n{s}", .{ msg, usage }); + return .usage; +} diff --git a/src/root.zig b/src/root.zig new file mode 100644 index 0000000..eb32ece --- /dev/null +++ b/src/root.zig @@ -0,0 +1,17 @@ +//! Aji reference implementation. +//! +//! Trusted computing base (AGENTS.md): verifier, AIR interpreter semantics, +//! backend, unsafe runtime modules, ABI/platform descriptions. Keep modules +//! small and keep the verifier free of heuristics. + +pub const version = "0.0.0-dev"; + +pub const diag = @import("diag.zig"); +pub const air = @import("air.zig"); +pub const verifier = @import("verifier.zig"); +pub const interp = @import("interp.zig"); +pub const check = @import("check.zig"); + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/src/verifier.zig b/src/verifier.zig new file mode 100644 index 0000000..39f6406 --- /dev/null +++ b/src/verifier.zig @@ -0,0 +1,8 @@ +//! AIR verifier (spec 08). Part of the language semantics, not a lint. +//! +//! Passes are added in roadmap order. Each normative rejection MUST map to a +//! code in `diag.registry` and MUST have positive and negative conformance +//! tests under tests/conformance/. +//! +//! Phase 0: SSA/dominance (E5001), CFG/terminators (E5002), types (E1001), +//! deterministic resource budget (E5101). diff --git a/tests/conformance/README.md b/tests/conformance/README.md new file mode 100644 index 0000000..8964209 --- /dev/null +++ b/tests/conformance/README.md @@ -0,0 +1,42 @@ +# Conformance suite + +Run with `zig build conformance` (add `-- --json` for JSON Lines, `-- --filter ` to narrow). + +## Layout + +```text +tests/conformance/ + phase/accept/*.air modules a conforming verifier MUST accept + phase/reject/*.air modules a conforming verifier MUST reject +``` + +`phase` is the roadmap phase (`docs/roadmap/implementation-plan.md`) that first requires the test to pass. + +## Test header + +Every test starts with a block of `;` lines. Keys: + +| Key | Required | Value | +|---|---|---| +| `expect` | yes | `accept`, or `reject` followed by one or more codes from `docs/reference/error-codes.md` | +| `phase` | yes | roadmap phase number | +| `spec` | yes | spec section that justifies the expectation | + +Header lines without a `key:` are free-form description. The runner blanks the header before handing the module to the pipeline, so line numbers in diagnostics are unchanged and the AIR grammar does not need to know about test metadata. + +`reject` compares the exact multiset of error codes. Listing a code twice means two diagnostics with that code are expected. + +## Outcomes + +| Outcome | Meaning | +|---|---| +| `PASS` | result matches `expect` | +| `FAIL` | result differs, or the header is malformed; the run exits 1 | +| `PENDING` | the pipeline stage needed for this input is not implemented yet | + +## Rules + +- Every verifier rule gets at least one `accept` and one `reject` test (AGENTS.md, testing policy). +- One defect per `reject` test. A test that triggers several unrelated errors is hard to repair against. +- Keep tests minimal: the smallest module that exhibits the rule. +- Text AIR syntax in the seed tests is provisional until the text AIR grammar is specified (Phase 0, task P0-1). Update the tests when the grammar lands. diff --git a/tests/conformance/phase0/accept/loop_block_params.air b/tests/conformance/phase0/accept/loop_block_params.air new file mode 100644 index 0000000..204ab89 --- /dev/null +++ b/tests/conformance/phase0/accept/loop_block_params.air @@ -0,0 +1,22 @@ +; Counting loop passing state through block parameters instead of phi nodes. +; expect: accept +; phase: 0 +; spec: docs/spec/07-air.md +fn @count(%n: u64) -> u64 +effects [] + +entry: + %zero = const.u64 0 + br @loop(%zero) + +loop(%i: u64): + %done = ge.u64 %i, %n + cbr %done, @exit(%i), @body(%i) + +body(%j: u64): + %one = const.u64 1 + %next = add.checked.u64 %j, %one + br @loop(%next) + +exit(%r: u64): + ret %r diff --git a/tests/conformance/phase0/accept/sum.air b/tests/conformance/phase0/accept/sum.air new file mode 100644 index 0000000..e27e1d0 --- /dev/null +++ b/tests/conformance/phase0/accept/sum.air @@ -0,0 +1,10 @@ +; Checked addition of two parameters. +; expect: accept +; phase: 0 +; spec: docs/spec/07-air.md +fn @sum(%a: u64, %b: u64) -> u64 +effects [] + +entry: + %0 = add.checked.u64 %a, %b + ret %0 diff --git a/tests/conformance/phase0/reject/missing_terminator.air b/tests/conformance/phase0/reject/missing_terminator.air new file mode 100644 index 0000000..6612736 --- /dev/null +++ b/tests/conformance/phase0/reject/missing_terminator.air @@ -0,0 +1,9 @@ +; The only block falls off its end without a terminator. +; expect: reject E5002 +; phase: 0 +; spec: docs/spec/07-air.md +fn @f(%a: u64) -> u64 +effects [] + +entry: + %0 = add.checked.u64 %a, %a diff --git a/tests/conformance/phase0/reject/operand_type_mismatch.air b/tests/conformance/phase0/reject/operand_type_mismatch.air new file mode 100644 index 0000000..b5bcf25 --- /dev/null +++ b/tests/conformance/phase0/reject/operand_type_mismatch.air @@ -0,0 +1,10 @@ +; add.checked.u64 applied to a u32 operand. +; expect: reject E1001 +; phase: 0 +; spec: docs/spec/02-types-and-values.md +fn @f(%a: u64, %b: u32) -> u64 +effects [] + +entry: + %0 = add.checked.u64 %a, %b + ret %0 diff --git a/tests/conformance/phase0/reject/undefined_value.air b/tests/conformance/phase0/reject/undefined_value.air new file mode 100644 index 0000000..03376ee --- /dev/null +++ b/tests/conformance/phase0/reject/undefined_value.air @@ -0,0 +1,10 @@ +; %c is used but never defined. +; expect: reject E5001 +; phase: 0 +; spec: docs/spec/07-air.md +fn @f(%a: u64) -> u64 +effects [] + +entry: + %0 = add.checked.u64 %a, %c + ret %0 diff --git a/tests/conformance/phase1/reject/use_after_move.air b/tests/conformance/phase1/reject/use_after_move.air new file mode 100644 index 0000000..d4aaea9 --- /dev/null +++ b/tests/conformance/phase1/reject/use_after_move.air @@ -0,0 +1,11 @@ +; %p is moved into %q and then used again. +; expect: reject E2001 +; phase: 1 +; spec: docs/spec/03-memory-model.md +fn @f(%p: Own) -> Own +effects [] + +entry: + %q = move %p + %r = move %p + ret %r diff --git a/tools/conformance.zig b/tools/conformance.zig new file mode 100644 index 0000000..ac0c401 --- /dev/null +++ b/tools/conformance.zig @@ -0,0 +1,215 @@ +//! Conformance suite runner. Format: tests/conformance/README.md. +//! +//! usage: aji-conformance [--json] [--filter ] +//! +//! Exit status is 1 if any test FAILs or has a malformed header. PENDING +//! (pipeline stage not implemented yet) does not fail the run. + +const std = @import("std"); +const aji = @import("aji"); + +const Expect = union(enum) { + accept, + /// Exact multiset of error codes, sorted. + reject: []const []const u8, +}; + +const Outcome = enum { pass, fail, pending }; + +const Header = struct { + expect: Expect, + phase: u8, + spec: []const u8, +}; + +pub fn main(init: std.process.Init) !void { + const arena = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(arena); + + if (args.len < 2) { + std.debug.print("usage: aji-conformance [--json] [--filter ]\n", .{}); + std.process.exit(2); + } + const root = args[1]; + var json = false; + var filter: []const u8 = ""; + var i: usize = 2; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--json")) { + json = true; + } else if (std.mem.eql(u8, args[i], "--filter") and i + 1 < args.len) { + i += 1; + filter = args[i]; + } else { + std.debug.print("aji-conformance: unknown argument {s}\n", .{args[i]}); + std.process.exit(2); + } + } + + // Collect and sort paths so that output order is deterministic. + var paths: std.ArrayList([]const u8) = .empty; + var dir = try std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }); + defer dir.close(io); + var walker = try dir.walk(arena); + defer walker.deinit(); + while (try walker.next(io)) |entry| { + if (entry.kind != .file or !std.mem.endsWith(u8, entry.path, ".air")) continue; + if (std.mem.indexOf(u8, entry.path, filter) == null) continue; + try paths.append(arena, try arena.dupe(u8, entry.path)); + } + std.mem.sort([]const u8, paths.items, {}, lessThan); + + var stdout_buf: [4096]u8 = undefined; + var stdout_fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf); + const out = &stdout_fw.interface; + + var counts = std.EnumArray(Outcome, usize).initFill(0); + for (paths.items) |rel| { + const source = try dir.readFileAlloc(io, rel, arena, .limited(16 << 20)); + const display = try std.fs.path.join(arena, &.{ root, rel }); + const result = try runOne(arena, display, source); + counts.getPtr(result.outcome).* += 1; + if (json) { + var s: std.json.Stringify = .{ .writer = out }; + try s.write(.{ .@"test" = display, .outcome = @tagName(result.outcome), .detail = result.detail }); + try out.writeByte('\n'); + } else { + try out.print("{s:<8} {s}", .{ label(result.outcome), display }); + if (result.detail.len != 0) try out.print(" ({s})", .{result.detail}); + try out.writeByte('\n'); + } + } + if (!json) { + try out.print("\n{d} passed, {d} failed, {d} pending\n", .{ + counts.get(.pass), counts.get(.fail), counts.get(.pending), + }); + } + try out.flush(); + if (counts.get(.fail) != 0) std.process.exit(1); +} + +fn lessThan(_: void, a: []const u8, b: []const u8) bool { + return std.mem.lessThan(u8, a, b); +} + +fn label(o: Outcome) []const u8 { + return switch (o) { + .pass => "PASS", + .fail => "FAIL", + .pending => "PENDING", + }; +} + +const Result = struct { outcome: Outcome, detail: []const u8 = "" }; + +fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Result { + const header = parseHeader(arena, source) catch |err| + return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) }; + + // Blank header lines (keeping newlines) so spans in diagnostics stay accurate + // and the AIR grammar does not have to know about test metadata. + const body = try arena.dupe(u8, source); + var line_start: usize = 0; + while (line_start < body.len and body[line_start] == ';') { + const end = std.mem.indexOfScalarPos(u8, body, line_start, '\n') orelse body.len; + @memset(body[line_start..end], ' '); + line_start = end + 1; + } + + const report = try aji.check.checkAir(arena, path, body); + if (report.status == .unimplemented) + return .{ .outcome = .pending, .detail = report.missing_stage }; + + var got: std.ArrayList([]const u8) = .empty; + for (report.diagnostics) |d| { + if (d.severity == .@"error") try got.append(arena, d.code.id); + } + std.mem.sort([]const u8, got.items, {}, lessThan); + + switch (header.expect) { + .accept => if (report.status == .accepted) return .{ .outcome = .pass }, + .reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass }, + } + return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{ + fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items), + }) }; +} + +fn eqlCodes(a: []const []const u8, b: []const []const u8) bool { + if (a.len != b.len) return false; + for (a, b) |x, y| if (!std.mem.eql(u8, x, y)) return false; + return true; +} + +fn fmtExpect(e: Expect) std.fmt.Alt(Expect, formatExpect) { + return .{ .data = e }; +} + +fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void { + switch (e) { + .accept => try w.writeAll("accept"), + .reject => |codes| { + try w.writeAll("reject"); + for (codes) |c| try w.print(" {s}", .{c}); + }, + } +} + +const HeaderError = error{ MissingExpect, MissingPhase, MissingSpec, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow }; + +fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header { + var expect: ?Expect = null; + var phase: ?u8 = null; + var spec: ?[]const u8 = null; + + var lines = std.mem.splitScalar(u8, source, '\n'); + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, ";")) break; + const content = std.mem.trim(u8, line[1..], " \t\r"); + const colon = std.mem.indexOfScalar(u8, content, ':') orelse continue; // free-form comment + const key = content[0..colon]; + const value = std.mem.trim(u8, content[colon + 1 ..], " \t"); + if (std.mem.eql(u8, key, "expect")) { + var it = std.mem.tokenizeScalar(u8, value, ' '); + const verb = it.next() orelse return error.BadExpect; + if (std.mem.eql(u8, verb, "accept")) { + if (it.next() != null) return error.BadExpect; + expect = .accept; + } else if (std.mem.eql(u8, verb, "reject")) { + var codes: std.ArrayList([]const u8) = .empty; + while (it.next()) |c| { + if (aji.diag.lookup(c) == null) return error.UnknownCode; + try codes.append(arena, c); + } + if (codes.items.len == 0) return error.BadExpect; + std.mem.sort([]const u8, codes.items, {}, lessThan); + expect = .{ .reject = codes.items }; + } else return error.BadExpect; + } else if (std.mem.eql(u8, key, "phase")) { + phase = try std.fmt.parseInt(u8, value, 10); + } else if (std.mem.eql(u8, key, "spec")) { + spec = value; + } else return error.UnknownKey; + } + return .{ + .expect = expect orelse return error.MissingExpect, + .phase = phase orelse return error.MissingPhase, + .spec = spec orelse return error.MissingSpec, + }; +} + +test parseHeader { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const h = try parseHeader(arena_state.allocator(), + \\; Use of %x without a definition. + \\; expect: reject E5001 + \\; phase: 0 + \\; spec: docs/spec/07-air.md + \\fn @f() -> u64 + ); + try std.testing.expectEqual(@as(u8, 0), h.phase); + try std.testing.expectEqualStrings("E5001", h.expect.reject[0]); + try std.testing.expectError(error.UnknownCode, parseHeader(arena_state.allocator(), "; expect: reject E9999\n")); +}