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.
This commit is contained in:
dev committed 2026-10-04 11:59:13 +03:00
commit 17a55a7fef
67 files changed
+4197

No files matched your search

+19
View File
@@ -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
```
+59
View File
@@ -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.
+41
View File
@@ -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.
+61
View File
@@ -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 |
+23
View File
@@ -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.
+51
View File
@@ -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 | "_" } ;
+93
View File
@@ -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
```
+37
View File
@@ -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<T>`, `Region`, `Island<T>`, `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.
+56
View File
@@ -0,0 +1,56 @@
# RFC NNNN: Title
Status: Draft
Target: Aji 0.x
Supersedes: —
<!-- Status values: Draft → Proposed → Accepted → Implemented, or Rejected. See README.md. -->
## 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
@@ -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<T> single object ownership
Region bulk lifetime
Island<T> closed uniquely owned mutable graph
Frozen<T> 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<T>` 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<T>` edges may be cyclic but are scoped to the island.
## Transfer
Ownership of `Island<T>` 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<T>`.
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<T>
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<T>`;
- whether sub-islands can be detached in O(1);
- interaction with memory-mapped files.
+65
View File
@@ -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.
+61
View File
@@ -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<ref<T>> 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.
+90
View File
@@ -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.
+23
View File
@@ -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.
+112
View File
@@ -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.
+118
View File
@@ -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<T>`;
- `ref<T>` / `mut<T>`;
- 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<T>`;
- closure verification;
- move/transfer;
- freeze;
- `Frozen<T>`.
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.
+25
View File
@@ -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`.
+75
View File
@@ -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.
+105
View File
@@ -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<T, E>`.
```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<T>(a: mut<T>, b: mut<T>) { ... }
```
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.
+146
View File
@@ -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<T>
```
Release/debug modes MUST NOT change these semantics.
## 3. Composite types
```aji
[u8; 4096]
slice<u8>
slice_mut<u8>
(u32, u64)
Option<T>
Result<T, E>
```
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<ref<T>>
Option<mut<T>>
```
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(...)
```
+283
View File
@@ -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<T> individually owned dynamic allocation
Region bulk allocation/lifetime domain
Island<T> uniquely owned closed mutable graph
Frozen<T> deeply immutable graph
Arc<T> explicit shared ownership of Share data
ref<T> immutable borrow
mut<T> exclusive mutable borrow
Uninit<T> allocated but not yet initialized
addr<T> unsafe raw address
```
## 3. Safe-reference aliasing rule
For overlapping storage, safe code permits either:
```text
N immutable borrows: ref<T>
```
or:
```text
1 exclusive mutable borrow: mut<T>
```
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<ref<'a, T>>
```
## 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<T>
`Own<T>` is a move-only handle to an individually allocated object.
```aji
let node: Own<Node> = heap.alloc<Node>(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<Node>(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<T>
```
Exclusive mutable slice:
```text
slice_mut<T>
```
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<T> uninitialized
region.alloc_zeroed<T> 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<T>`.
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<T>
An `Island<T>` 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<T>` handles for graph edges.
`iref<T>`:
- 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<T>
`Frozen<T>` 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<T>` is `Share` and `Send` when contained external resources permit sharing.
## 14. Arc<T>
`Arc<T>` 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<T>` 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<T>`.
Pinning is required for selected FFI, DMA and self-referential runtime structures.
## 16. Raw addresses
`addr<T>` 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.
+340
View File
@@ -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<T>`: 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<task.detach>`.
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<T>` may not be concurrently shared.
Safe shared mutation uses approved synchronization types:
```text
Mutex<T>
RwLock<T>
Atomic*
Channel<T>
```
## 8. Verified interior mutability
Synchronization wrappers such as `Mutex<T>`, `RwLock<T>` and atomic types are verifier-known interior-mutability abstractions.
Their internal mutable storage is not directly reachable through ordinary `ref<T>` or `mut<T>` 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<T>` 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<Rank, T>`.
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<T>` permits:
- multiple read guards yielding `ref<T>`;
- exactly one write guard yielding `mut<T>`.
Fairness is runtime-specific unless a runtime profile promises otherwise.
## 12. Channels
Channels transfer ownership.
```aji
let (tx, rx) = channel.create<Message>(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<T>` 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<T, E>`.
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.
+101
View File
@@ -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<u8>) -> 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<fs.read>,
path: slice<u8>
) -> Result<Data, IoError>
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.
+60
View File
@@ -0,0 +1,60 @@
# 06. Resources and Errors
## 1. Linear resources
External resources are linear unless explicitly documented otherwise.
Examples:
```text
File
Socket
Thread<T>
Task<T>
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<Created>
Socket<Bound>
Socket<Listening>
Socket<Connected>
Socket<Closed>
```
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<T, E>`.
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.
+184
View File
@@ -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.
+119
View File
@@ -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.
+72
View File
@@ -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<u8>,
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<T>` abstraction obtained through `cap<device.mmio>`.
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.
@@ -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.
+63
View File
@@ -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.
+45
View File
@@ -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.
+86
View File
@@ -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<Log>, data: slice<u8>) -> Result<u64, Error>
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<T> 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.
+18
View File
@@ -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 |