647 lines
73 KiB
Markdown
647 lines
73 KiB
Markdown
# 15. Source Language `.aji` 0.1 (Phase 6A)
|
||
|
||
This file is normative for `.aji` source 0.1. Decision record: RFC 0013. Grammar: [`../reference/grammar.ebnf`](../reference/grammar.ebnf).
|
||
|
||
## 1. Principle
|
||
|
||
`.aji` is the agent-facing language. AIR (spec 07) remains the normative execution format. A `.aji` module means exactly the AIR it lowers to, and that AIR is checked by the normative verifier (spec 08). The frontend is outside the trusted computing base.
|
||
|
||
**Boundary rule.** Source syntax MAY hide representation mechanics:
|
||
|
||
- SSA values;
|
||
- the CFG and block parameters;
|
||
- `borrow.end`;
|
||
- `local.alloc`;
|
||
- the `features [...]` header;
|
||
- intermediate values.
|
||
|
||
It MUST NOT hide:
|
||
|
||
- authority (capabilities);
|
||
- allocation (`own.*`, `region.*`, `channel.make`);
|
||
- ownership transfer (`move`);
|
||
- resource consumption (close, free, take);
|
||
- synchronization (`lock`, `send`, `recv`, `join`);
|
||
- external effects (`effects [...]`, intrinsics);
|
||
- task structure (`scope`, `task.spawn`);
|
||
- cancellation;
|
||
- recoverable failure (every outcome of a fallible operation).
|
||
|
||
Rules:
|
||
|
||
1. Lowering is a pure function of its explicit source inputs: the same module graph gives byte-identical canonical AIR (spec 07 §8.5).
|
||
2. No source construct admits a program whose AIR the verifier rejects. Errors the verifier would find are reported with the verifier's code (§9).
|
||
3. `.aji` 0.1 covers the published features of Phases 0–3 and nothing else.
|
||
4. Every construct has **one canonical spelling**. There are no alternative forms of the same operation. Parentheses for expression grouping and the optional list delimiters of §2 do not introduce operations.
|
||
|
||
## 2. Modules and declarations
|
||
|
||
```aji
|
||
module demo.echo
|
||
|
||
struct Pair {
|
||
a: u8,
|
||
b: u8,
|
||
}
|
||
|
||
enum Shape {
|
||
Empty,
|
||
Square(u64),
|
||
Rect(u64, u64),
|
||
}
|
||
|
||
fn main(input: cap<io.read>, out: cap<io.write>) -> void
|
||
effects [io.read, io.write]
|
||
{
|
||
...
|
||
}
|
||
```
|
||
|
||
- A file holds one module: `module <dotted.path>`, then type and function declarations in any order.
|
||
- Between the module header and declarations, `import <dotted.path>;` imports a standard (§13) or explicitly supplied package module (§14). `import` is contextual at this position; it remains an ordinary identifier elsewhere.
|
||
- `//` starts a line comment. `recv` and `send` are contextual in `select`, and remain identifiers elsewhere; a lone `_` is a wildcard/discard, not an identifier. Keywords are listed in the grammar; after `.` they may name a member.
|
||
- Trailing commas MAY appear in parameter, argument, effect, field, variant, array-literal element and binding lists, including static-function contract parameters/effects. Type parameter/argument lists and enum declaration payload-type lists MUST NOT have trailing commas. Empty outcome/tuple/select-cancellation binding lists MAY retain `()`; the operation still checks the number and kinds of bindings. Enum payload lists MUST NOT be empty (§5–§6).
|
||
- Function `f` lowers to `@f`; type `T` to `@T`.
|
||
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block.
|
||
- **Parameter names are preserved.** A parameter `p` lowers to `%p`. Names the compiler generates are chosen so that they never equal a parameter name of the function. The names of `@main`'s parameters are part of the instantiation contract.
|
||
- **The entry point** is `main`. Its parameters are capabilities `cap<K>`, bound by name (spec 05 §10.2). Startup values of other types (command-line arguments, for example) are not part of `.aji` 0.1.
|
||
- **Grants are not source semantics.** A program only declares `main`'s capability parameters. Granting them is instantiation after the module is lowered and verified (`aji run --grant …`, `aji.toml`, spec 12 §1). A missing grant is `not_instantiated` at run time, never a source or verifier diagnostic.
|
||
- **One source for every profile.** The frontend does not know the execution profile. The same `.aji` runs in the deterministic and the hosted profile (spec 11).
|
||
- **`trusted` is not available.** It is the boundary of runtime, std and toolchain modules (spec 13 §6.3), not something a program declares about its own code. The word is reserved and a `trusted` clause is `E7006`.
|
||
- **Unsafe operations** are the format-0 ones and nothing else: `ref unchecked s[i]` / `mut unchecked s[i]` (also bound: `ref unchecked e = s[i];`) lower to `borrow.index.unchecked`, and `assume(c)` to `assume`. Their boundary is the AIR one: the function declares `effects [unsafe]`, which propagates to its callers. Outside it the verifier reports `E6001`. There is no `unsafe { … }` block, because AIR has no block-level unsafe boundary (owner decision: deferred; localizing unsafe inside a function would be an AIR change through its own RFC). There is no FFI, raw address or syscall surface in format 0, so none exists in source.
|
||
|
||
## 3. Types
|
||
|
||
The AIR spellings are used (spec 07 §8):
|
||
|
||
- integers `u8`…`u128`, `usize`, `i8`…`i128`, `isize`; `bool`, `void`, `never`;
|
||
- named types;
|
||
- `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`;
|
||
- `own<T>`, `own_array<T>`, `buffer<T>` (§17), `region`;
|
||
- `cap<K>`;
|
||
- `file<read|write|append>`, `listener`, `stream`;
|
||
- `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>`;
|
||
- `island<T>`, `frozen<T>`, `arc<T>`, `iref<T>`, `atomic<T>`;
|
||
- the built-in enums `io_error`, `alloc_error`, `cap_error`.
|
||
|
||
Arrays are written `[T; N]`. `scope`, `shield` and `guard<T>` are not source types: they exist only inside the block forms of §7.
|
||
|
||
## 4. Statements and control flow
|
||
|
||
Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`, `select`, `scope`, `shield`, `lock`, `{ … }`) do not require one.
|
||
|
||
**Block boundary.** At a statement or block-tail start, an unparenthesized `if`, `match` or `{ … }` MUST be parsed as one complete construct, including its `else` chain or arms, without consuming subsequent postfix, cast or binary operations. Immediately before the enclosing `}`, it is the tail expression; followed by `;`, it is an expression statement that explicitly discards its result; otherwise it is a block statement and MUST yield `void` or diverge (`E7006` for a value). This prevents an old value-producing expression from silently becoming two statements. Other block statements likewise end at their final `}`. Whitespace and comments MUST NOT affect these boundaries.
|
||
|
||
To continue such an expression in statement/tail position, parenthesize the complete construct: `({ 2u64 }) * 3u64`. Expression contexts (initializers, assignment right-hand sides, returns, arguments, conditions and expression arms) retain ordinary expression parsing: `return { 2u64 } * 3u64;` needs no extra parentheses.
|
||
|
||
| Source | Meaning |
|
||
|---|---|
|
||
| `let x = e;` / `let x: T = e;` | immutable binding |
|
||
| `var x: T = e;` / `var x: T = zero;` | variable; `zero` is `local.zero` (zeroable types only) |
|
||
| `x = e;` | assignment to a variable |
|
||
| `*r = e;` | store through `mut<T>` |
|
||
| `r.f = e;` | store into a field through `mut<Struct>` |
|
||
| `if c { … } else { … }` | `else if` chains allowed |
|
||
| `while c { … }` | |
|
||
| `for i in a..b { … }` | `a ≤ i < b`, integer type of `a` and `b`; `b` evaluated once |
|
||
| `loop { … }` | |
|
||
| `break;` / `continue;` | innermost loop |
|
||
| `return;` / `return e;` | |
|
||
| `trap;` | |
|
||
| `assert(c);` | traps `T0002` |
|
||
| `match e { … }` | §6 |
|
||
|
||
`if` and `match` are expressions when every branch yields a value of the same type through a tail expression (an expression without `;` at the end of a block) or diverges (`return`, `break`, `continue`, `trap`).
|
||
|
||
**Joins carry only variables that change and are read again.** A variable is passed to a join (the block after an `if`, `match`, `lock` or `select`, a loop header, a loop exit) only if two things hold:
|
||
|
||
- the construct assigns it, by `x = e;` or by rebinding on an outcome edge;
|
||
- it may be read after the join: on a later path, or, for a loop header, anywhere in the loop.
|
||
|
||
Any other variable keeps its dominating value. An unchanged linear value is therefore never passed as a block argument while it is borrowed (`mut g = isl;` around a loop), and a variable that is not read again is not passed on. This is ordinary pruned SSA construction, not tracking of moves. A linear value consumed before a join (`channel.close_receiver(move r)` before `break`) does not travel to it. A linear value that is read after it was consumed is still the verifier's `E2001`. The analysis is conservative: any read on a later path counts, and only a whole-variable assignment in straight-line code ends a variable's life.
|
||
|
||
**Type inference is deliberately small.** It works within one function, it is monomorphic, and it does no overload resolution or search among several admissible types. An expression's type comes from:
|
||
|
||
- its own form: a literal suffix, a name, a call's declared return type, a cast, a struct or enum constructor;
|
||
- otherwise its context: an annotation, the other operand, the parameter type of the function called, the function's return type.
|
||
|
||
An untyped `let x = <literal>` takes the type its first later use in the same function determines in that way. If nothing determines a type, the result is `E7007`: the frontend never picks a default.
|
||
|
||
Lowering: structured control flow becomes blocks and terminators. A variable assigned on several paths becomes a block parameter at the join.
|
||
|
||
## 5. Expressions
|
||
|
||
**Arithmetic, comparison and logic:**
|
||
|
||
| Source | AIR |
|
||
|---|---|
|
||
| `a + b`, `a - b`, `a * b`, `a / b`, `a % b` | checked (`T0003`, `T0004`) |
|
||
| `a +% b`, `a -% b`, `a *% b` | wrapping |
|
||
| `a & b`, `a \| b`, `a ^ b`, `a << b`, `a >> b` | bitwise and shifts (`T0005`) |
|
||
| `==`, `!=`, `<`, `<=`, `>`, `>=` | comparisons |
|
||
| `and`, `or`, `not` | boolean operations |
|
||
| `-a` | `0 - a`, checked |
|
||
|
||
**Casts:**
|
||
|
||
| Source | AIR |
|
||
|---|---|
|
||
| `x as T` | `cast.widen`; only where every value is representable, otherwise `E1002` |
|
||
| `x as! T` | `cast.checked` (`T0006`) |
|
||
| `x as% T` | `cast.wrap` |
|
||
|
||
**Literals:**
|
||
|
||
- integers (`42`, `0xff`, `0b101`, `1_000`) take their type from context, or a suffix (`42u8`);
|
||
- `true`, `false`;
|
||
- `b"…"`: a byte string, of type `[u8; N]`, with escapes `\n`, `\t`, `\\`, `\"`, `\xHH`.
|
||
|
||
**Aggregates.**
|
||
|
||
- **Struct values.** `Pair { a: 1, b: 2 }` is the only way to build one: every field exactly once, in any order. A missing or repeated field is `E7006`, an unknown one `E7002`. The initializers are evaluated, and lowered, in **declaration order**, so the AIR does not depend on the order the fields are written in. There is no positional constructor.
|
||
- **Enum values.** `Shape::Square(4)`, or `Shape::Empty` for a variant without payload, is the only form. An empty `()` after a qualified variant MUST reject E7001, including a variant that requires payload values.
|
||
- **Arrays.** `[e; N]` is `array.splat`.
|
||
- **Field access.** `v.f` on a struct value is `struct.get`.
|
||
|
||
6A has no destructuring: no `let Point { x, y } = p`, no nested patterns, guards or or-patterns.
|
||
|
||
**Calls.** `f(args)` calls a local function; a directly imported function uses its full path (§13–§14). Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right.
|
||
|
||
**Borrows and places.** A place is:
|
||
|
||
- a variable;
|
||
- `place.f`;
|
||
- `place[i]`;
|
||
- `place[a..b]`;
|
||
- `*r`;
|
||
- a parenthesized place, such as `(*r).field` or `(*r)[i]`. Dereference consumes a unary operand: `*r.field` means `*(r.field)`.
|
||
|
||
| Source | Meaning |
|
||
|---|---|
|
||
| `ref r = place;` / `mut r = place;` | **the only way to bind a borrow**: a statement, valid to the end of the enclosing block. `let r = mut x;` is `E7006`. An active borrow cannot be shadowed by the same name in the same scope (`E7006`). Borrowing a whole array binds a slice (`slice<T>` / `slice_mut<T>`). Borrowing a borrow binding reborrows it. Declared borrow-returning calls are bound with the same forms under §19. |
|
||
| `ref place` / `mut place` as an argument | a temporary borrow for that call (ended right after it); allowed only as an argument |
|
||
| `*r` | load through `ref<T>`/`mut<T>` of a scalar or struct; slices and arrays use `s[i]` (`E7006`) |
|
||
| `r.f` | field through a borrow of a struct (borrow, load, end) |
|
||
| `s[i]` | element value (borrow, load, end) |
|
||
| `s.len` | `slice.len`, or the static length of an array |
|
||
| `s[a..b]` | a sub-slice (`slice.sub` with start `a`, length `b - a`); a borrow, so it is bound or passed, never a value |
|
||
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`. Besides `atomic.compare_exchange` (§12), the only multi-result binding. There is no general tuple destructuring. |
|
||
| `slice.copy(mut dst, ref src)` | primitive `slice.copy`; insufficient capacity traps. Recoverable byte copy is `std.bytes.copy` (spec 16 §2.4). |
|
||
|
||
**Whole-array arguments.** In an ordinary function call, `ref place` / `mut place` MUST preserve a whole-array referent when the known parameter is `ref<[T; N]>` / `mut<[T; N]>`; otherwise the existing whole-array-to-slice rule applies. Element type, length and explicit borrow mode MUST match (`E7005`); a slice MUST NOT be converted back to an array borrow. This also applies after explicit generic/static-function specialization and to array fields, elements and dereferenced array borrows (`ref (*a)`). Shared reborrowing of an exclusive parent follows the existing AIR rule. All temporary ancestors end after the call, child first. Borrow bindings still produce slices; bare byte-string arguments still produce `slice<u8>`. The named-origin requirement of §19 and the named-loan requirement of `task.spawn` (§7) remain mandatory.
|
||
|
||
**Writes.**
|
||
|
||
- `*r = v;` for a scalar or struct referent;
|
||
- `r.f = v;`, `x.f = v;`;
|
||
- `s[i] = v;`, `x[i] = v;`.
|
||
|
||
The value is evaluated first, then the place is borrowed for the store and the borrow ends. So `s[i] = s[i] + 1;` reads before it writes.
|
||
|
||
**Bounds.** These follow AIR exactly:
|
||
|
||
- `s[i]` is a checked `borrow.index` (`T0008`);
|
||
- inside the true branch of `if i < s.len`, with `i` and `s` the unchanged SSA values, the frontend emits `borrow.index.proven`. This is the fact the verifier proves (spec 08 §12, "fact on the same slice");
|
||
- in every other case the index stays checked. The frontend never knows more about bounds than the verifier.
|
||
|
||
**Unsafe indexing.** `ref unchecked s[i]` and `mut unchecked s[i]` are `borrow.index.unchecked`, and `assume(c)` is `assume`. Both are allowed only under spec 13 §6.
|
||
|
||
**Arrays and byte strings.**
|
||
|
||
- `[e; N]` evaluates `e` once and copies the value N times (`array.splat`). The element must be Copy; a non-Copy value rejects E7005 at `e`, with `constraint: Copy` and `type_constructor: array`. A borrowed element retains E7006 `invalid_literal`.
|
||
- `b"…"` is an immutable `[u8; N]` value held in frame storage, written there byte by byte, with no heap. The escapes are exactly `\n \r \t \\ \" \0 \xNN`.
|
||
- Used where a `slice<u8>` is expected, it is borrowed for the operation.
|
||
|
||
**Moves.**
|
||
|
||
- A named linear value (`own<T>`, `own_array<T>`, `region`, and the resources and endpoints of later layers) is consumed only by `move x`. Using a named linear value as a consuming operand without `move` is `E7003`; the diagnostic carries `suggestion: "move x"`. Consuming operands are: call arguments, `let`/`var` initializers, assignments, `return`, the value operand of an allocation, and `own.take`, `own.free`, `region.destroy`.
|
||
- `move` of a copyable value is `E7006`.
|
||
- The frontend does not track moved state. Use after move (`E2001`), double consumption (`E2002`), use after consume (`E3001`) and leaks (`E3002`) are found by the verifier on the lowered AIR and reported at the source location.
|
||
- A linear value used as a borrow place (`ref x`, `mut x`, `ref r = x;`) is borrowed in place: `own<T>` as `ref<T>`/`mut<T>`, `own_array<T>` as `slice<T>`/`slice_mut<T>`, `region` as `ref<region>`. There is no implicit dereference of an owner.
|
||
- A temporary, that is the result of a call or operation used directly as an operand, needs no `move`: it has no other owner in the source.
|
||
- Copyable values are copied by plain use.
|
||
|
||
## 6. Fallible operations and `match`
|
||
|
||
Arm bodies beginning with `{` consume the whole block; a following comma MAY be present. Other expression arms MUST end with a comma unless immediately followed by the enclosing `}`. Integer patterns MAY have a leading minus. Qualified enum patterns use bare names for payload-free variants; an empty payload-binding `()` MUST reject E7001. Payload bindings MAY use `_` to discard a value, subject to the existing linear-value rules.
|
||
|
||
Every AIR terminator with outcome edges is written as a `match` over its outcomes. The arms are named after the edge roles and the match MUST be exhaustive (`E7004`):
|
||
|
||
| Operation | Outcomes |
|
||
|---|---|
|
||
| fallible intrinsics, `own.new`, `own.array`, `region.create`, `region.new`, `region.array`, `cap.narrow.*` | `ok(…)`, `err(e)` |
|
||
| `channel.make<T>(n, mem)` | `ok(tx, rx)`, `err(e)` |
|
||
| `channel.send(tx, v)` | `ok`, `closed(v)`, `cancelled(v)` |
|
||
| `channel.recv(rx)` | `ok(v)`, `closed`, `cancelled` |
|
||
| `channel.close_receiver(move rx)` | `ok`, `pending(rx)` |
|
||
| `task.check_cancel()` | `ok`, `cancelled` |
|
||
| `task.join_cancel(move t)` | `ok(v)`, `cancelled(t)` |
|
||
|
||
```aji
|
||
match io.stdin_read(input, mut buf) {
|
||
ok(n) => { … }
|
||
err(e) => { trap; }
|
||
}
|
||
```
|
||
|
||
- **Match kinds.** The parser decides the kind of a `match` from its arms: `Enum::Variant` arms make an enum match, integer literals and `_` an integer match, and bare outcome names (`ok`, `err`, `closed`, `cancelled`, `pending`) an outcome match. Outcome names are not enum patterns. In an outcome match the scrutinee MUST be a fallible operation (`E7006` otherwise). Each outcome is matched exactly once: a repeated one is `E7006`, an unknown one `E7002`, a wrong number of bound names `E7005`. A fallible operation outside an outcome match or `or trap` is `E7006`.
|
||
- **Outcome values.** `err(e)` binds the real error value (`alloc_error`, `cap_error`, `io_error`). These built-in enums are matched like declared ones: `alloc_error::out_of_memory`, exhaustive, no `_`. A borrow bound by an outcome (the `ok(item)` of `region.new`) ends at the end of its arm. A borrow bound by `let item = region.new(arena, v) or trap;` ends at the end of the enclosing block.
|
||
- **Error construction.** Every registered built-in error variant is also a payload-free expression, e.g. `let e = alloc_error::budget_exceeded;`. It lowers to `error.const` with feature `error_values` and its dependency closure (spec 05 §14), requires no effects or capabilities and changes no resource state. Unknown variants are `E7002`, payload arguments `E7005`; errors are Copy data and cannot confer authority.
|
||
- **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`. If that name is a variable (`var`) of the value's type, the value becomes the variable's new value. A receiver kept in `var r` is closed with `match channel.close_receiver(move r) { ok => …, pending(r) => … }` and received from again.
|
||
- **`or trap`.** `op(args) or trap` is the expression of the `ok` value, or of `void`. Every other outcome traps (`T0001`). It is the only shorthand.
|
||
- **Enums.** A `match` over a value of an enum type has exactly one arm per variant, each written `Enum::Variant(names…)` (`Enum::Variant` without payload). It must be exhaustive (`E7004` lists the missing variants), and `_` is not allowed (`E7006`), so a new variant cannot slip through silently. Payload names are bound only inside their arm (they are the arm block's parameters in AIR). It lowers to `enum.switch`.
|
||
- **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). Pattern values MUST fit the scrutinee type (`E7005`); different spellings of the same value are duplicate arms (`E7006`). It lowers to `switch` with canonical decimal literals, without source suffixes or separators.
|
||
- **Booleans** use `if`.
|
||
- **As expressions.** `match` and `if` are expressions when their arms yield values (§4). Every arm must have the type of the others, or diverge.
|
||
- **Source map.** The switch maps to the `match`; each arm's code and its branch to the join map to that arm.
|
||
|
||
## 7. Tasks, cancellation, channels, select and mutex
|
||
|
||
```aji
|
||
scope s {
|
||
let a = task.spawn(s, square, mut left);
|
||
let r = task.join(move a);
|
||
}
|
||
```
|
||
|
||
**`scope s { … }`** is `task.scope.begin` and `task.scope.end`, at every normal exit of the block.
|
||
|
||
The name `s` MUST denote only a lexical scope identifier, used by name as the first operand of `task.spawn`. It MUST NOT be used as an ordinary value (`s` or `move s`: `E7006`, reason `invalid_expression`) or borrowed (`E7006`, reason `invalid_place`). Assignment to this immutable identifier is `E7006`, reason `invalid_assignment`. Consequently it cannot be aliased, yielded, returned, put in an aggregate or passed as an ordinary argument. Ordinary lexical shadowing remains permitted: lookup selects the innermost binding, while completion always consumes the originating block's saved AIR scope identity. Leaving a shadowing block restores the outer binding; an unjoined child still rejects with `E4301`. This source restriction does not change function-local AIR scope flow (spec 04 §33).
|
||
|
||
Task operations inside the block:
|
||
|
||
- `task.spawn(s, f, args)` spawns `f` (a local or directly imported qualified function, §14) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`);
|
||
- `task.join(move t)` joins; its value is the task's result (`task<T>` gives `T`);
|
||
- a task that is not joined at an exit is `E4301`.
|
||
|
||
**Task operations elsewhere:**
|
||
|
||
- `task.cancel(t)` (not consuming);
|
||
- `task.cancelled()`;
|
||
- `task.check_cancel()` and `task.join_cancel(move t)`, which are matches (§6).
|
||
|
||
**`shield { … }`** is `task.shield.begin` and `task.shield.end`, at every normal exit. Shields nest by construction.
|
||
|
||
**Channels:**
|
||
|
||
- `channel.make<T>(n, mem)`: a match, §6;
|
||
- `channel.dup(tx)`: `channel.sender.dup` on a shared borrow of `tx`, made for the operation;
|
||
- `channel.send(tx, v)` (`move v` for a linear `v`);
|
||
- `channel.recv(rx)`; for `send` and `recv` the endpoint is borrowed `mut` for the operation and the borrow ends on every edge;
|
||
- `channel.close_sender(move tx)`;
|
||
- `channel.close_receiver(move rx)`.
|
||
|
||
**`select { … }`** has one form:
|
||
|
||
```aji
|
||
select {
|
||
recv(rx_a) { ok(x) => …, closed => … }
|
||
send(tx_b, move job) { ok => …, closed(job) => … }
|
||
cancelled(job) => …
|
||
}
|
||
```
|
||
|
||
Every edge binds its own value (the received `T` of a `recv` arm's `ok`) and then the send values not sent on it, distinct values in the order of first appearance (spec 04 §39). With `send(tx_b, move job)` in the `select`, the `recv` arm's edges are `ok(x, job)` and `closed(job)`, the send arm's are `ok` and `closed(job)`, and the `select`'s own is `cancelled(job)`. A wrong number of names is `E7005`, a missing outcome `E7004`. Each endpoint is borrowed `mut` once for the `select`, even when several arms name it, and the borrow ends on every edge.
|
||
|
||
**Mutex:**
|
||
|
||
- `mutex.make(v)`; to share a mutex with tasks, bind `ref mr = m;` and pass `mr` (a `ref<mutex<T>>`);
|
||
- `mutex.take(move m)`, which needs no live borrow of `m`;
|
||
- `lock ref m as x { … } cancelled { … }`.
|
||
|
||
**The `lock` block** lowers to:
|
||
|
||
1. `mutex.lock` on the borrow `ref m`: `m` is a `mutex<T>` (borrowed for the lock, the borrow ending after the unlock and on the `cancelled` edge) or a `ref<mutex<T>>` binding (used as it is);
|
||
2. on the `ok` edge: `mutex.borrow` of the guard, bound as `x: mut<T>`;
|
||
3. the block;
|
||
4. `borrow.end x` and `mutex.unlock` of the guard.
|
||
|
||
Step 4 happens at **every normal exit** from the block: fall-through, and every `return`, `break` and `continue` that leaves it. The `cancelled { … }` block is the lock's cancelled edge. On a trap nothing is unlocked: the execution terminates (spec 04 §33.2). The guard is never a source value. The critical-section rule (spec 04 §41) applies to the block's contents.
|
||
|
||
**Resource and endpoint operands.** An operation whose AIR operand is a borrow of a resource or endpoint accepts the resource by name and borrows it for the duration of the operation (§8):
|
||
|
||
- `file<…>`, `stream`, `listener`;
|
||
- `sender<T>`, `receiver<T>`;
|
||
- `task<T>` for `task.cancel`.
|
||
|
||
For example `net.accept(l)`, `fs.read(f, mut buf)`, `channel.send(tx, move v)`. Data borrows (`ref`/`mut` of values, arrays and slices) are always written. A mutex is borrowed explicitly: `lock ref m`. A region is borrowed explicitly too (§8).
|
||
|
||
## 8. Allocation, resources and intrinsics
|
||
|
||
Allocation and resource operations keep their AIR names and operand order:
|
||
|
||
- `own.new(v, mem)` and `own.array(n, v, mem)` (outcome matches, §6): `ok(o)` binds `own<T>` / `own_array<T>`, `err(e)` an `alloc_error`;
|
||
- `let v = own.take(move o);`, `own.free(move o);` (`own<T>` or `own_array<T>`; there is no take for arrays);
|
||
- `region.create(mem)`: `ok(r)` binds a `region`;
|
||
- `region.new(rb, v)`, `region.array(rb, n, v)`: `rb` MUST be a `ref`/`mut` borrow binding of the region; `ok(item)` binds `mut<T>` / `slice_mut<T>`;
|
||
- `region.reset(r)`, `region.destroy(move r)`;
|
||
- `cap.narrow.budget(c, n)` and `cap.narrow.prefix(c, path)`: `ok(c2)` binds a `cap<K>`, `err(e)` a `cap_error` (`invalid_restriction`, `not_subset`, `unsupported_restriction`). Narrowing is always fallible and never yields an empty capability;
|
||
- capabilities are values of type `cap<K>`, received as parameters and copied by plain use (no `move`);
|
||
- intrinsics under their registered names and operand order (`reference/intrinsics.md`), as plain calls: `io.stdout_write(out, ref buf[0..n])`, `fs.open_read(c, b"/in/data.txt")`, `fs.close(move f)`, `net.listen(c, b"127.0.0.1:7")`. There are no methods, no `File.open()` and no implicit I/O.
|
||
|
||
**Intrinsics.**
|
||
|
||
- **Failure.** A fallible intrinsic is an outcome match (`ok(results…)`, `err(e)` with `e: io_error`) or `op(…) or trap` (§6). Used as a plain value or statement it is `E7006`. An infallible one (`clock.monotonic`, `random.fill`) is a plain call; matching it is `E7006`.
|
||
- **Authority.** A capability is needed only to acquire authority: `fs.open_read(c, path)` returns a `file<read>` that carries it, and `fs.read(f, mut buf)` takes no capability. The capability kind is checked by the verifier (`E3201`), and the effect too (`E3101`).
|
||
- **Resource operands.** An operand the registry marks as borrowed is the resource **by name**. The frontend borrows it `mut` for that one operation and ends the borrow on every outcome edge. A `mut` borrow binding or parameter of the resource (`f: mut<file<write>>`) is passed as is. Writing `mut f` there is `E7006` (one spelling); a resource of the wrong type or mode is `E7005`.
|
||
- **Consumed operands** (`fs.close`, `net.close_stream`, `net.close_listener`) take `move f` (`E7003` without it). The frontend never inserts a close: an unclosed resource is the verifier's `E3002`, use after close `E3001`.
|
||
- **Data operands** are always written: `ref bytes` / `ref buf[a..b]` / a byte string for read bytes, `mut buf` / `mut buf[a..b]` for a buffer the operation fills (`E7005` otherwise).
|
||
- **Paths and addresses** are byte strings or borrowed bytes, passed as they are. There is no `Path` type and the frontend does not normalize. Whether a path is absolute, free of `.`/`..` and inside the capability's scope is decided by the intrinsic at run time (`invalid_input`, `permission_denied`; for narrowing, `invalid_restriction`, `not_subset`).
|
||
- **Source map.** The intrinsic's terminator maps to the call. The borrow ends on each edge map to the call, and each arm's code to its arm. A runtime trap under `or trap` points at the call (`source_location` in the run record). A verifier diagnostic on an operand points at that operand's construct.
|
||
|
||
**Region borrows are explicit.** The borrow of a region that `region.new`/`region.array` take is written by the programmer and lexically outlives the allocation borrows derived from it:
|
||
|
||
```aji
|
||
{
|
||
ref arena = r;
|
||
match region.new(arena, 1u64) {
|
||
ok(item) => { *item = *item + 1; }
|
||
err(e) => { trap; }
|
||
}
|
||
}
|
||
region.reset(r);
|
||
```
|
||
|
||
Passing the region itself is `E7005`; the frontend never creates a temporary region borrow. `region.reset` and `region.destroy` end no borrow: a live allocation borrow at a reset or destroy is the verifier's `E2104`. The programmer narrows the scope.
|
||
|
||
**Islands, frozen graphs and arcs** (spec 03 §22–§24; layer 9). Types `island<T>`, `frozen<T>`, `arc<T>`, `iref<T>`.
|
||
|
||
| Source | AIR |
|
||
|---|---|
|
||
| `island.create(v, mem)`, `island.alloc(g, v)`, `arc.new(v, mem)` | outcome matches or `or trap` (`ok(…)`, `err(e: alloc_error)`) |
|
||
| `island.root(g)`, `frozen.root(g)`, `arc.root(g)` | `island.root`, `frozen.root`, `arc.root` |
|
||
| `ref x = island.at(g, r);` / `mut x = island.at(g, r);` | `island.borrow` (`mut` needs `g: mut<island<T>>`) |
|
||
| `ref x = frozen.at(g, r);`, `ref x = arc.at(g, r);` | `frozen.borrow`, `arc.borrow` (`mut` is `E7005`) |
|
||
| `island.freeze(move i)`, `island.destroy(move i)`, `frozen.release(move f)`, `arc.from_frozen(move f)`, `arc.release(move a)` | the same |
|
||
| `arc.clone(a)` | `arc.clone` on a shared borrow of `a`, made for the operation |
|
||
| `a == b`, `a != b` for `iref<T>` | `iref.eq` (then `not`) |
|
||
|
||
**Container borrows are explicit, as for regions.** `.root`, `.at` and `island.alloc` take a named borrow binding of the graph's owner (`mut g = isl;`), which outlives the borrows derived from it. Passing the owner itself is `E7005`, with a hint. A container borrow written inline is `E7006`. `island.at`, `frozen.at` and `arc.at` appear only as the place of a `ref`/`mut` binding (`E7006` elsewhere).
|
||
|
||
**Linear aggregates.** A struct, enum or fixed array with linear members follows §16 and spec 03 §25. The frontend declares `linear_aggregates` and lowers complete explicit ownership transfers.
|
||
|
||
A byte string or array used where a `slice<u8>` is expected is materialized in frame storage and borrowed for the operation.
|
||
|
||
## 9. Frame storage, borrow scopes and features
|
||
|
||
- **Frame storage.** Addressability is a property of lowering, not of source types. Linear values (owners, regions, resources, endpoints, tasks, mutexes) never get frame storage: they are borrowed in place. A variable whose name is borrowed, indexed, or written through a field or element anywhere in the function lowers to `local<T>` storage, allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The decision is by name, so the same source always gives the same placement. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
|
||
- **Borrow scopes.** A borrow bound by `ref`/`mut` ends at the end of the block that contains the binding. Because a borrow's name is not visible after its scope, a use after the borrow ended (`E2106`) cannot be written in source. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope, except the named returned borrow and its owned ancestors transferred under §19. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
|
||
- **Features.** The frontend emits the `features [...]` header as the dependency closure of the constructs used, always including `effects`.
|
||
- **Effects.** They are declared by the programmer. Every function/template/static-function contract MUST use registered atoms (`reference/effects.md`); an unknown atom MUST reject E7002 with `name` and `effect`, before body lowering. The source position is the function start, or the static parameter start for its contract. Ordinary signature type/`from` checks and existing template/header check order remain prior checks. Ordinary effect lists retain AIR set semantics; static-function contract effects remain unique (§18). `E3101` names the missing effect and suggests the complete effect list (`suggested_effects`).
|
||
|
||
## 10. Diagnostics
|
||
|
||
| Problem | Code |
|
||
|---|---|
|
||
| found by the verifier on the lowered AIR | the AIR code; the diagnostic's `file`, `line` and `col` are the source location of the construct the instruction came from, and `air_line`/`air_col` locate it in the lowered AIR (`aji lower`); the verifier's own fields (`function`, `block`, `inst`) are kept |
|
||
| syntax, name resolution, lowering and invalid source constructs | `E7xxx`, below |
|
||
| several AIR instructions of one construct reporting the same code | one diagnostic (the first) per code and source location |
|
||
| the lowered AIR is malformed: a parse error (`E0001`–`E0005`) or invalid SSA or CFG (`E5001`, `E5002`) | `E7900` (`source.internal_compiler_error`) at the source construct, with the AIR code in `air_code`. It is a compiler bug, never an error in the program, and replaces every other diagnostic of the module. Semantic codes (ownership, borrows, resources, effects, capabilities, concurrency, `E0006`) are not affected |
|
||
| trap at run time | the trap record also carries `source_location` (`file`, `line`, `col`) |
|
||
|
||
**Which errors the frontend reports.** An error that is fully decided by source types is `E7005` (or another `E7xxx`) at the source construct, and never reaches the verifier as `E1001`/`E1002`. The frontend checks:
|
||
|
||
- the types of expressions, operands and results;
|
||
- arity and argument types of functions and built-in operations;
|
||
- the existence of fields and variants;
|
||
- `ref`/`mut` compatibility;
|
||
- A place store MUST require `mut<T>`; a `mut` binding or argument MUST require an exclusive place before whole-array-to-slice conversion. A shared place rejects E7005 at the place (binding/store) or argument with `expected`/`found` borrow types. The RHS is still evaluated first; whole-array stores retain E7006. Content linearity and alias/lifetime checks remain verifier rules.
|
||
- lossless widening by `as` (the verifier's own rule);
|
||
- slice element types of `slice.copy`;
|
||
- the element rules of channels and mutexes (no borrow, scope, task, shield or guard).
|
||
- Copy content of `own_array<T>` and the repeated value of `own.array`; an invalid content type is E7005 at that annotation/value, with `constraint: Copy` and `type_constructor: own_array`. Known linear content in unused generic signatures and static contracts MUST reject; unknown type parameters are checked after substitution.
|
||
- Inferred array literal elements MUST satisfy the existing member-position rules. Borrowed elements reject E7006 `invalid_literal`; other invalid constructors reject E7005 at the element with `position: member` and `type_constructor`. Lists preserve explicit linear transfers; repetitions MUST satisfy Copy.
|
||
- Inferred content of `own.new`, `own.pack`, `region.new`, `region.array`, `mutex.make`, `island.create`, `island.alloc` and `arc.new` MUST be a value: `void`/`never` reject E7005 at the content argument, with `position: member` and `type_constructor`. `own.new` and region storage MUST require Copy (E7005 with `constraint: Copy` and `operation`); `own.pack` MUST reject borrowed content (E7005 with `position: member` and `type_constructor`) while preserving complete linear transfers and failure recovery. These checks follow ordinary explicit-move checks and precede allocation authority checks. Graph-content properties, reserved transfers and concurrency checks otherwise retain their verifier diagnostics; `own.array` retains its Copy diagnostic above.
|
||
- A typed operand needed by an operation MUST yield a value: `never` rejects E7005 at that operand with `expected` and `found: never`, before later operands or instruction emission. This includes calls, operators, aggregate inputs, conditions, ranges, indices, sizes and the value stored through `*`, a field or an index. For a place store this check precedes borrowing/evaluating the target; an unknown target type uses `expected: a stored value`. Existing void/type mismatches retain their diagnostics. Divergence in returns, tails, statements and if/match arms remains valid. Assignment to a variable by name and `var` initialization MAY diverge after the ordinary binding/annotation checks; no store is emitted for either SSA or frame storage. `let` still requires a value. Expressions emitted after unconditional divergence MUST reject E7006 `unreachable`, never abort the compiler.
|
||
|
||
Source type annotations MUST satisfy the existing AIR type-position rules (spec 07 §8.3/§8.8), including nested constructors. An invalid constructor is E7005 at its annotation, with `position` and `type_constructor` fields. Known constructors in unused generic signatures and static function contracts MUST be checked; restrictions depending on a type parameter are checked after substitution. Graph-content properties and feature gates for otherwise correctly positioned types retain their verifier diagnostics.
|
||
|
||
The verifier remains the authority for:
|
||
|
||
- ownership state, linearity and moves;
|
||
- borrow conflicts and lifetimes;
|
||
- resource state;
|
||
- effects and capabilities;
|
||
- concurrency (loans, `Send`/`Share`, the critical-section rule);
|
||
- reserved features;
|
||
- every other verifier invariant.
|
||
|
||
Its diagnostics keep their AIR codes, reported at the source location.
|
||
|
||
| Code | Kind | Meaning |
|
||
|---|---|---|
|
||
| E7001 | source.syntax | Malformed `.aji` source |
|
||
| E7002 | source.unknown_name | Undefined variable, function, type, field, variant or effect |
|
||
| E7003 | source.missing_move | Named linear value consumed without `move` |
|
||
| E7004 | source.not_exhaustive | `match` misses an outcome, variant or default |
|
||
| E7005 | source.type_mismatch | Expression has the wrong type in a source position |
|
||
| E7006 | source.invalid_construct | Construct not allowed here (e.g. `break` outside a loop, `move` of a non-linear value, `zero` for a non-zeroable type) |
|
||
| E7007 | source.ambiguous | Source meaning cannot be determined (e.g. an integer literal with no type from context) |
|
||
| E7900 | source.internal_compiler_error | The frontend produced invalid AIR for this construct (a compiler bug, not a program error) |
|
||
|
||
Every E7006 MUST include a stable string `reason` from the [reason registry](../reference/error-codes.md#e7006-reasons), chosen directly by the rejecting rule, independently of `message`. `move_copy` denotes an explicit rejected move of a plain Copy value; borrows use `move_borrow`, and non-materializable operands use `invalid_move`. Permitted generic transfers MUST NOT emit these errors. Reason meanings MUST remain stable; extensions MAY add registered reasons. Consumers MUST tolerate new reasons. Codes, rejection rules, primary positions and existing fields are unchanged; `reason` is appended after existing code-specific fields. A historical or incomplete record without a reason is unknown, never evidence of `move_copy` or its absence.
|
||
|
||
Each related AIR position (spec 10 §2) MUST be mapped independently through the lowering map, including imported/specialized source files, retaining its original coordinates as `air_line`/`air_col`. If absent, the related source `file`/`line`/`col` MUST be omitted together; `role`, `value` and AIR coordinates remain. A guessed related source position MUST NOT be substituted. Primary fallback and duplicate selection remain unchanged.
|
||
|
||
## 11. Tooling
|
||
|
||
| Command | Does |
|
||
|---|---|
|
||
| `aji check file.aji` | parse, lower, verify |
|
||
| `aji run file.aji` | the same, then run (same flags and run record as for `.air`) |
|
||
| `aji lower file.aji` | print the canonical AIR |
|
||
| `aji lower --stats file.aji` | source and AIR size, expansion ratios and the two `mechanical_air_eliminated` metrics below |
|
||
| `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) |
|
||
| `aji fmt file.aji` | print formatted source; leave the file unchanged |
|
||
| `aji fmt --check file.aji` | emit a JSON format record; exit 0 if formatted, 1 if formatting is needed |
|
||
| `aji fmt --write file.aji` | atomically replace a regular file when needed; emit a JSON format record |
|
||
|
||
`check`, `lower`, `report`, `run` and `explore` also accept `--manifest PATH` for explicit package inputs (§14, spec 12 §1.3). Check/lower/report do not instantiate grants.
|
||
|
||
Lowering is deterministic: the same source inputs and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
|
||
|
||
**Source formatting.** `fmt` MUST parse one `.aji` file without linking, specializing, verifying or executing it. Libraries without `main`, unresolved imports and semantically rejected programs MAY be formatted. A syntax error MUST produce the existing E7001 JSON diagnostic and exit 1, with no formatted output or file modification; usage/I/O errors or an internal token-preservation failure exit 2 with a note on stderr. There is no manifest/directory discovery. `--check` and `--write` are mutually exclusive. Their record is `{ "file": PATH, "status": "formatted" | "needs_format", "changed": BOOL }`; `changed` reports whether the input differs from the formatted bytes, and `--write` reports `formatted` after a successful write. An unchanged file MUST NOT be rewritten. `--write` MUST preserve file permissions and reject non-regular files, including symbolic links. Atomic replacement changes one directory entry; other hard links retain the previous contents.
|
||
|
||
Formatting MUST preserve the ordered token spellings, comment contents (including trailing spaces/tabs, apart from terminal CR bytes normalized to LF) and declaration order, changing only whitespace between tokens and around comments. The result MUST parse to the same AST, ignoring source positions, and formatting it again MUST be byte-identical. Thus ownership/effects/capabilities, literal bytes, operator grouping and generated AIR remain unchanged; source diagnostic positions follow the formatted text. The reference layout uses LF, one final newline, four-space block/continuation indentation, expanded declaration/match bodies and compact struct literals. It retains at most one existing blank line between statements. Operators are spaced, type/application angles and paths are compact, and commas separate inline lists or start the next line in expanded bodies. Comments remain at their token boundary; trailing comments stay with the preceding token. Formatting MUST NOT introduce a line-width limit, reorder effects/imports or repair code.
|
||
|
||
**Size metrics** (`--stats`, non-normative tooling with a fixed definition):
|
||
|
||
- With `--manifest`, source sizes count the entry file only; AIR sizes count the combined module. These ratios MUST NOT be interpreted as whole-package compression.
|
||
- Sizes count code only: non-empty lines that are not comments (`//` in source, `;` in AIR), each with its newline.
|
||
- `mechanical_air_eliminated_raw` = 1 − `source_bytes` / `air_bytes`: how much of the AIR text the author did not write. This is the main engineering metric.
|
||
- `mechanical_air_eliminated_normalized` = 1 − `source_bytes` / `air_bytes_normalized`: the same against AIR in which every byte-string materialization counts as one logical constant operation. Such a materialization is the instructions from the string's `local.zero` to its final `borrow.end`, a store per non-zero byte, because format 0 has no byte-array constant. It is replaced by the single notional line ` const.bytes %<storage>, <literal>`, where `<literal>` is the canonical spelling: printable ASCII as is, otherwise the escapes `\n \r \t \0 \\ \" \xNN`. The storage's `local.alloc` is real frame storage and stays. No other instruction is normalized. The rule is the same for every program, and `byte_string_constants` reports how many were replaced.
|
||
|
||
## 12. Atomics
|
||
|
||
Spec 04 §20–§30, §42; layer 10, RFC 0015. Implemented with the publication of feature `atomics` (Phase 5).
|
||
|
||
| Source | AIR |
|
||
|---|---|
|
||
| `atomic<T>` (`T` AtomicScalar) | `atomic<T>`; linear, borrowed in place like a mutex |
|
||
| `let a = atomic.new(v);` | `atomic.new` |
|
||
| `let v = atomic.take(move a);` | `atomic.take`; needs no live borrow of `a` |
|
||
| `atomic.load(c, o)` | `atomic.load.<o>` |
|
||
| `atomic.store(c, v, o);` | `atomic.store.<o>` |
|
||
| `atomic.swap(c, v, o)` | `atomic.xchg.<o>` |
|
||
| `atomic.add.wrap(c, v, o)`, `atomic.sub.wrap(c, v, o)` | `atomic.add.wrap.<o>`, `atomic.sub.wrap.<o>` |
|
||
| `atomic.and(c, v, o)`, `atomic.or(c, v, o)`, `atomic.xor(c, v, o)` | `atomic.and.<o>`, `atomic.or.<o>`, `atomic.xor.<o>` |
|
||
| `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, s, f);` | `atomic.cmpxchg.<s>.<f>`, the second multi-result binding |
|
||
| `atomic.fence(o);` | `atomic.fence.<o>` |
|
||
|
||
The cell operand `c`:
|
||
|
||
- `c` is a `ref<atomic<T>>` binding or parameter, or a temporary `ref a` of an `atomic<T>` written as the argument.
|
||
- Passing the atomic itself, without `ref`, is `E7005`. So is writing `mut`.
|
||
- To share a cell with tasks, bind `ref c = a;` and pass `c`.
|
||
|
||
The orderings:
|
||
|
||
- They are the bare words `relaxed`, `acquire`, `release`, `acq_rel`, `seq_cst`, written last.
|
||
- They are not values: they cannot be bound, passed or computed (`E7006`).
|
||
- A word outside the operation's row is the verifier's `E4201`, reported at the ordering.
|
||
|
||
Other rules:
|
||
|
||
- `*c` and any other ordinary read of a cell is `E4202`.
|
||
- Effects are declared by the programmer (spec 05 §13).
|
||
|
||
## 13. Built-in standard modules
|
||
|
||
The compiler MUST provide the standard modules listed in spec 16 §2, pinned to its own version. An import of `std` or a `std.*` path MUST resolve only against that closed registry: no file-system search, environment variable, network fetch, package manifest, or build extension participates. Unknown modules are `E7002`; duplicate imports are `E7006`. Imports MUST precede declarations; a misplaced import or missing semicolon is `E7001`.
|
||
|
||
An imported standard function is called by its full path, for example `std.bytes.equal(ref a, ref b)`. An unknown member or a call without the corresponding import is `E7002`. Importing a module MUST NOT introduce unqualified names or aliases. Qualified standard calls MUST NOT resolve through a local binding named `std`. User functions with the same short name remain independent. Standard functions are ordinary function calls: their argument types, borrows, moves, effects and failure contracts follow the existing rules. Type arguments on these monomorphic functions are rejected (`E7006`, §15).
|
||
|
||
Lowering MUST append the complete non-generic type and function declarations of the imported modules after the program's declarations, in lexicographic module order and source declaration order within each module. For a type or function `f` in module `m`, the AIR name starts as `__aji_` plus `m` with dots replaced by underscores, then `_f`. If that name collides with a program type/function or a previously linked standard declaration, the compiler MUST append the smallest positive decimal suffix `_1`, `_2`, … that is unused. Qualified source calls MUST use the resulting AIR name. This is name mangling, not an extension to the format-0 identifier grammar. Generic templates follow §15. The imported source is parsed and lowered as ordinary safe `.aji` and the combined AIR MUST pass the same verifier. No runtime dispatch or new AIR instruction is introduced. The feature header is the dependency closure of the combined module, including unused imported functions.
|
||
|
||
Imports grant no authority, perform no runtime initialization and allocate no program heap memory. Merely importing a module does not add effects to the caller's contract; calling an effectful function would require its declared effects under the usual call rule.
|
||
|
||
Canonical AIR MUST be independent of import order, working directory and execution profile for a fixed compiler and program. Source diagnostics and traps inside a standard function MUST identify its stable repository-relative source path (spec 16 §2) and its original line/column, rather than the program's path. `aji lower --annotate` MUST include that path on annotations for imported instructions. AIR locations remain available as in §10.
|
||
|
||
Standard enum types are named by their full path, for example `std.bytes.ReadU32`. In type annotations, constructors and match patterns, that path MUST resolve only to a type from an explicitly imported standard module. An unknown module/type or missing import is `E7002`. Importing a module MUST NOT introduce short type names. Standard declarations with the same short names as user types remain distinct.
|
||
|
||
A constructor or pattern is written `std.bytes.ReadU32::ok(value)` or `std.bytes.ReadU32::short_input`. Constructors, payload typing and exhaustive enum matches obey §5/§6 without a library-specific exception. A wrong payload or variant from another enum is `E7005`, an unknown variant `E7002`, a missing arm `E7004`, and duplicate/wildcard enum arms `E7006`. These are ordinary Copy enum values; this increment does not add a must-use or linear-result rule. Source type diagnostics MUST name standard types by their public qualified source path, including inside compound types; AIR output still uses the generated identifiers. Library source uses the same full type paths in signatures, constructors and matches. Standard types lower with the collision-free naming rule above; their declarations precede function declarations as in §2.
|
||
|
||
The standard registry exports ordinary structs/enums and their generic templates (§15). Qualified named types and enum variants introduce no member methods, reflection, dependency resolution or aliases. Generic standard forms use §15. Package modules and qualified struct literals are specified in §14.
|
||
|
||
## 14. Package source modules
|
||
|
||
### 14.1 Explicit inputs and graph
|
||
|
||
The frontend MUST take an entry source and an explicit mapping of module names to source bytes and diagnostic file paths. Its compilation MUST be a pure function of those inputs and compiler version. The CLI supplies the mapping only from an explicitly selected manifest's `[modules]` (spec 12 §1.3); a file-only invocation has no package mapping and MUST NOT discover a manifest. No parent search, directory scan, environment search path, network access, dependency fetch or build script participates. Standard imports continue to use §13's compiler-pinned registry and MUST NOT be shadowed by the package mapping.
|
||
|
||
Each mapped source MUST declare exactly its mapped module name. An imported source need not define `main`; only the entry's unqualified `main` is the program entry. A module's own function named `main` is an ordinary qualified function. All top-level declarations and fields are available through explicit import; no visibility modifier or re-export is introduced. Modules have no executable top-level initialization.
|
||
|
||
Imports form an acyclic directed graph. The linker MUST parse each reachable module once, reject self-import/cycles, duplicate imports, duplicate mappings and mismatched headers with `E7006`, and unknown imports with `E7002`. Source syntax errors in a package module use `E7001` at that module's file/line/column. Imports are visited in source order for first-error selection; all complete non-generic declarations of reachable modules, including unused functions, enter verification; templates follow §15. Unreachable mapped source is not parsed or linked. Compiler input limits are 1,024 mapped modules and import depth 256; exceeding them is `E7006`. These are fixed implementation input limits, not runtime fuel or semantics-changing flags.
|
||
|
||
Module names use source paths. The first component of a package mapping MUST NOT be `std` or a namespace of a built-in operation (`slice`, `own`, `buffer`, `region`, `cap`, `task`, `channel`, `mutex`, `island`, `frozen`, `arc`, `atomic`, or the first component of a registered intrinsic). Such a mapping is `E7006` (a manifest error at the CLI). Root source names retain their existing grammar; duplicate entry/module identity is rejected when imported.
|
||
|
||
### 14.2 Names and types
|
||
|
||
A module sees its own functions and types by short name, and declarations of directly imported modules by full path. Imports MUST NOT inject short names, aliases or transitive visibility. An entry outside reserved built-in namespaces can also qualify its own declarations with its module name; built-in operations retain precedence. An inaccessible or unknown function/type/member is `E7002`, even if a different module linked the declaration. Qualified names resolve by module identity, independently of local bindings with the same prefix. A value may have a type inferred from a directly imported function contract without importing that type's defining module; spelling the type or its constructors by name still requires a direct import. Module-local calls MUST NOT capture an entry's similarly named function; named types from different modules are nominally distinct.
|
||
|
||
Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals MUST NOT consume the body-opening `{` in `if`/`while` conditions, `match` scrutinees, `for` bounds or `lock` places. Parenthesized expressions, call arguments and index expressions within those headers restore ordinary struct-literal parsing. This adds no methods, reflection or permission to store forbidden borrowed values in aggregates; linear members follow §16. Generic forms are specified separately in §15.
|
||
|
||
A qualified named function MAY be passed as the function operand of `task.spawn(scope, app.work.run, ...)`. Existing Send/effect/structured-lifetime rules still apply; there is no function value, dynamic dispatch or detached task. All other calls use the existing argument, borrow, move, failure and effect rules.
|
||
|
||
### 14.3 AIR, safety and compatibility
|
||
|
||
Entry declarations retain their existing AIR names. Imported declarations use §13's collision-free mangling, with all reachable standard/package modules appended in lexicographic module order and source order within each module. Type declarations still precede functions. Valid canonical AIR MUST be independent of import order, mapping order, directory/profile and source file paths for identical source bytes and module bindings. Whole-graph AIR feature closure is explicit as before. Source provenance MUST use each imported source's supplied file path; the CLI supplies its manifest-relative path. AST module identity is distinct from a diagnostic path, so coinciding file labels cannot change name resolution.
|
||
|
||
The combined AIR MUST pass the ordinary verifier and runs as a single format-0 module. There is no new opcode, AIR feature, verifier state, runtime primitive, initialization, implicit heap allocation or authority. Existing enum/struct layout, alias, initialization, borrow, ownership, resource, task and effect transfer functions apply across module calls unchanged. All return/cleanup paths remain explicit; imported code is not trusted by virtue of its module. Existing file-only and standard-only programs retain their lowering and behavior. Package imports require the new explicit mapping; previous unknown import paths become valid only when supplied.
|
||
|
||
## 15. Explicit source generics
|
||
|
||
### 15.1 Declarations and applications
|
||
|
||
Functions, structs and enums MAY declare 1–8 type parameters immediately after their name, e.g. `fn identity<T>(value: T) -> T effects [] { return value; }`, `struct Pair<T: Copy> { left: T, right: T }`, `enum Option<T: Copy> { some(T), none }`. Parameters MUST be distinct uppercase identifiers, MUST NOT shadow a visible type/builtin type, and have no default. Constraints are optional compiler-known `Copy`, `Send`, `Share`, `Freeze` or `Local`, joined by `+`; repeated/unknown constraints are `E7006`. Generic `main` is forbidden (`E7006`). No user traits, overloads, type inference, const/lifetime/effect parameters or specialization overrides are introduced.
|
||
|
||
Every generic use MUST supply exactly its ordered arguments (type arguments here; static function arguments in §18). Type annotations use `Pair<u64>`; expression applications use `identity::<u64>(42)`, `Pair::<u64> { left: 20, right: 22 }` and `Option::<u64>::some(42)`. Enum patterns use `Option::<u64>::some(value)` and `Option::<u64>::none`. The `::<...>` spelling separates generic application from comparisons; bare `f<T>(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::<u64>, ...)` statically specializes the worker; this creates no function value. Existing `channel.make<T>(...)` retains its spelling and single type argument.
|
||
|
||
Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; type parameters are types, not values or operations; static function parameters are separately defined in §18. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden.
|
||
|
||
Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity and array lengths (1..2^32, `E7005`), effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source.
|
||
|
||
### 15.2 Structural constraints
|
||
|
||
Constraints are requirements on concrete types, not compiler authority to infer effects or repair ownership. `Copy` follows existing value duplication: scalars, built-in enums, capabilities, `iref` and aggregates of Copy values; borrows and linear values are not Copy. `Send` and `Share` use exactly spec 04 §35. In format 0, `Freeze` is exactly `IslandSafe` (spec 03 §22): plain content accepted by deep graph conversion, including `iref`; it does not promise conversion of owners/resources/wrappers. `Local` identifies context-bound `task`, `scope`, `shield` and `guard` (and internal local storage); it propagates through borrows, own/own_array/buffer/mutex wrappers and arrays/aggregates containing Local content. Scalars, authority, resources, regions, endpoints and graph owners/handles are not Local. Local is not the complement of Send. No unsafe/manual property declarations are added.
|
||
|
||
A type can satisfy several constraints; each requirement MUST be checked. Constraints add no operations or trait dispatch: a body using arithmetic with `T: Copy` still requires an arithmetic-compatible concrete specialization. Effects, `from`, `move`, lends and cleanup remain explicit in every specialization.
|
||
|
||
### 15.3 Deterministic monomorphization and safety
|
||
|
||
A specialization is keyed by template module identity, declaration kind/name and the ordered structural identity of concrete arguments. Named arguments use nominal defining-module identity, independent of source filename, short/qualified spelling or import/provider order. Each key MUST emit at most one concrete declaration; repeated same-key recursion reuses it. Type-specialization cycles still obey ordinary finite-layout rules. Expanding specialization is bounded by 4,096 generated declarations and active expansion depth 64 (`E7006`), with structural type traversal bounded at depth 64. These are fixed compiler input limits, not runtime fuel or semantic flags.
|
||
|
||
Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name<T>`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Borrow-return contracts are retained by specialization and checked under §19.
|
||
|
||
## 16. Source linear aggregates
|
||
|
||
Structs, enums and fixed arrays with linear members MUST obey spec 03 §25. Constructors consume linear inputs with explicit `move`; whole aggregate calls/returns/bindings also require `move` on named values. No partial field move is allowed. Copy fields may be read without consumption. `let (a, b, …) = struct.unpack(move value);` and `let (a, b, …) = array.unpack(move value);` bind all fields/elements in order, including a one-element parenthesized binding. `_` is allowed only for Copy components; a linear ignored component MUST reject E3002 through the ordinary verifier. Array literals `[e0, e1, …]` use complete ordered inputs; repeated `[e;N]` remains Copy-only. Existing argument/block limits bound unpacking.
|
||
|
||
`match move value { Enum::Variant(payload) => … }` exhaustively consumes a linear enum and lowers to enum.take. Ordinary Copy matches keep enum.switch. An arm MUST consume or transfer each linear payload, including those named `_`; there is no automatic destructor. Unused payload-free variants still consume the linear enum.
|
||
|
||
`value.swap(mut place, move replacement)` returns the previous complete value and stores the replacement; it lowers to value.swap with the existing borrow scope. The same spelling accepts Copy replacements without move. The caller MUST explicitly consume a returned linear value. `match own.pack(move value, heap) { ok(owner) => …, err(error, value) => … }` makes allocation authority/failure explicit and preserves ownership on both outcomes; `or trap` retains ordinary abnormal-path semantics. own.new/own.array/region storage and local storage remain Copy-only; own.take extracts whole linear content and own.free cannot destroy it.
|
||
|
||
The frontend MUST declare linear_aggregates plus its dependencies whenever any emitted aggregate has linear members or any of the new operations is emitted. Existing Source/AIR diagnostics and deterministic behavior apply. This phase does not implement partial moves, borrowed aggregates, dynamic linear buffers or source from-returns.
|
||
|
||
|
||
## 17. Source dynamic buffers
|
||
|
||
`buffer<T>` is the linear initialized-prefix owner of spec 03 §26. Built-ins use ordinary explicit borrows, moves and outcome matches: `buffer.new<T>(capacity, heap)`, `buffer.len(b)`, `buffer.capacity(b)`, `buffer.reserve(b, capacity, heap)`, `buffer.push(b, move value)`, `buffer.pop(b)` and `buffer.free(move owner)`. Except new/free, b MUST be a named ref/mut<buffer<T>> binding, borrowed first from an owner or aggregate field. Mutating operations require mut. len/capacity accept ref or mut. new/reserve declare mem.alloc explicitly. push requires no heap capability and never grows implicitly.
|
||
|
||
Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error); push has ok()/err(original_value); pop has ok(value)/err(); free has ok()/err(original_buffer). Ordinary exhaustive outcome matching/or trap applies. A returned linear value MUST be explicitly consumed. `ref values = buffer.view(b);` binds a shared slice from ref or mut b; `mut values = buffer.view(b);` requires mut b and binds an exclusive slice. The child borrow lasts for its explicit lexical scope and never escapes through an aggregate. This primitive binding also permits ordinary functions to return retained views under §19. Existing indexing/value.swap provides Copy reading and complete linear element exchange. Views expose only the initialized prefix; mutation/growth/free while a view or task loan is live MUST reject even on a dynamically full/empty/no-op branch.
|
||
|
||
A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows or internal storage/scope/guard/shield handles. A Copy value bound in frame storage remains a Copy value and is loaded normally when transferred. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization.
|
||
|
||
The frontend MUST emit linear_buffers and its full dependencies for buffer types/operations. Existing syntax suffices apart from admitting the buffer wrapper and the typed built-in allocator with the existing channel.make<T> type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added.
|
||
|
||
## 18. Static function parameters
|
||
|
||
Generic structs, enums and functions MAY declare a static function parameter alongside type parameters: `F: fn(ref<T>) -> u64 effects []`. This is a compile-time contract, not a value type. Its ordered parameter types, return type and complete flat effect set MUST be explicit. Static function parameter names MUST be uppercase, distinct, and MUST NOT shadow a visible type or function. All types are checked/substituted like ordinary function signatures; all effect atoms MUST be registered and unique. Static function parameter borrow returns and `from` contracts remain unsupported; ordinary functions use §19. A callable parameter MUST NOT carry structural property constraints or be used as a type. The existing maximum of eight generic parameters counts both kinds.
|
||
|
||
An explicit argument is `fn path`, or `fn path::<arguments>` for a generic function. The path MUST resolve to a directly accessible declared source function. Built-in operation names, runtime values and captures are not function arguments. `fn F` forwards an already bound static parameter; it cannot be specialized again. A type argument in a function position or a function argument in a type position is `E7005`. Wrong generic arity remains `E7006`; unknown/inaccessible functions remain `E7002`. Signature/effect mismatch diagnostics include `parameter`, `function`, `expected` and `found` contracts.
|
||
|
||
After substitution, the selected function MUST have exactly the declared ordered parameter/return types and effect set (`E7005`). Effect order is irrelevant; widening/narrowing of effects or borrow types is not implicit. Exact effect contracts avoid effect shims and ensure that specialization cannot infer effects away from a public contract. Capabilities are ordinary explicit arguments; selecting a function grants no authority. A borrowed input retains ordinary read/exclusive access rules, and linear arguments retain explicit moves and consumption obligations.
|
||
|
||
The bound name MAY occur only as a direct call target or named `task.spawn` worker; normal arguments and explicit moves/borrows still apply. It MUST NOT escape into storage, aggregates, returns or runtime expressions (`E7006`). It MUST NOT be shadowed by a runtime binding in a specialized body or its signature (`E7006`). Static parameters have no runtime representation, capture environment, destructor, heap allocation or indirect dispatch. They are not inferred. Templates remain subject to the header/body distinction of §15.
|
||
|
||
Function identity, including explicit specialization arguments and defining module, MUST participate in the instance identity of both functions and types. In canonical keys a static argument spells `fn ` followed by the full defining-module/function path, including canonical `<...>` arguments when specialized. Thus two container types with different bound hash/equality functions are nominally distinct, even when their storage layouts agree. Linking retains direct-import restrictions and caller-site provenance for explicit arguments. Limits remain depth 64, 4,096 specializations and 16,384-byte instance keys, including argument/contract resolution; unresolved cyclic contracts MUST reject with `E7006`, never recurse without a bound.
|
||
|
||
Lowering MUST replace each bound call/worker with an ordinary named AIR function operand. No new AIR instruction, type, effect, capability, feature or verifier state is added: ordinary `call`, task checking, effects, borrows and ownership validate every resulting specialization. Existing AIR format-0 semantics and type-only source generics are unchanged. AIR equivalence and source rejection tests MUST cover static selection, nominal policy identity, authority, ownership, effects, imports and workers.
|
||
|
||
```aji
|
||
fn identity(value: u64) -> u64 effects [] { return value; }
|
||
fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
|
||
return F(move value);
|
||
}
|
||
// In main: apply::<u64, fn identity>(42u64)
|
||
```
|
||
|
||
General collections MAY use these explicit contracts for hash/equality/order operations. Their algebraic laws remain library preconditions; no compiler magic infers hashing or equality. This facility alone does not complete HashMap/HashSet or resolve their storage/API invariants.
|
||
|
||
## 19. Source borrow returns
|
||
|
||
Source functions MAY return `ref<T>`, `mut<T>`, `slice<T>` or `slice_mut<T>` with an explicit `from p` naming a borrow parameter. A borrow return without `from` is `E7006`; an unknown origin is `E7002`; a non-borrow origin or non-borrow return with `from` is `E7005`. An exclusive return requires an exclusive origin (`E7005`). `main` MUST NOT return a borrow (`E7006`). A borrow-returning function MUST NOT be passed to `task.spawn` (`E7006` at the spawn); `task_borrow_returns` remains reserved (spec 04 §33.1).
|
||
|
||
A borrow-returning call MUST be bound as `ref name = f(...);` for a shared result or `mut name = f(...);` for an exclusive result. The binding mode MUST equal the result mode (`E7005`); there is no implicit mode conversion. The argument in the callee's `from` position MUST be an existing named borrow binding or borrow parameter (`E7006` for an inline borrow, byte string or nested call). Other arguments retain ordinary call rules and their temporary borrows end after the call. This rule makes the retained parent explicit: the result ends with its binding's lexical block, before its parent. A call producing a borrow in an ordinary value expression, `let` or nested argument is `E7006`. Bind the result first, then use its name.
|
||
|
||
A borrow return MUST name a borrow parameter or borrow binding: `return view;`, or `view` as the function body's tail expression. Borrow-producing calls and inline places MUST first be bound (`E7006`). Nested blocks, `if` and `match` MUST NOT yield borrow values; branches MAY return directly. `move` does not apply to borrows (`E7006`). At each normal function return the frontend MUST omit `borrow.end` for the returned borrow and its owned ancestors, and end all other lexical borrows in reverse creation order. This is a transfer to the caller, never a destructor or an inferred resource cleanup. Task scopes, shields and locks retain their existing exit obligations.
|
||
|
||
The output uses the existing AIR `from %p`, `call`, `ret` and borrow instructions; no feature, instruction, effect, capability or runtime rule is added. The ordinary verifier (spec 08 §11.3) MUST reject a returned local-frame view (`E2108`) or a view rooted in another parameter (`E2102`). Shared/exclusive aliasing, task loans, initialization and bounds remain checked, including after a returned view ends. The frontend's ancestry bookkeeping only selects ends; it MUST NOT replace verifier provenance checks. The deterministic interpreter executes the same verified AIR in both execution profiles; invalid memory cannot be exposed by returning a view. Existing source/AIR programs keep their meaning and canonical lowering; previously unimplemented `from` declarations become executable. Static function parameter contracts remain outside this increment (§18); ordinary generic and package functions MAY return borrows. Unused generic signatures MUST still check a spelled borrow return, origin name and known modes; a bare type parameter whose mode is unknown MUST be checked after concrete substitution.
|
||
|
||
Valid:
|
||
|
||
```aji
|
||
fn first(s: slice<u64>) -> ref<u64> from s effects [] {
|
||
ref item = s[0];
|
||
return item;
|
||
}
|
||
fn main() -> u64 effects [] {
|
||
let data = [42u64, 7u64];
|
||
ref s = data;
|
||
ref item = first(s);
|
||
return *item;
|
||
}
|
||
```
|
||
|
||
Rejected: replacing the body of `first` with `let n = 1u64; ref item = n; return item;` MUST produce `E2108`. Calling `first(ref data)` MUST produce `E7006`: bind `ref s = data;` and pass `s`. Mutation through an exclusive parent while the returned view is live MUST produce `E2101`; a live task loan remains `E4101`. Borrow access out of bounds traps `T0008` identically to the existing AIR instruction.
|