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

+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 |