# 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 the source: the same module 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. ## 2. Modules and declarations ```aji module demo.echo type Pair = struct { a: u8, b: u8 } type Shape = enum { Empty, Square(u64), Rect(u64, u64) } fn main(input: cap, out: cap) -> void effects [io.read, io.write] { ... } ``` - A file holds one module: `module `, then type and function declarations in any order. - `//` starts a line comment. - 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 optionally `trusted ""` (spec 13 §6), then the body block. - **The entry point** is `main`. Its parameters are capabilities bound by name (spec 05 §10.2). ## 3. Types The AIR spellings are used (spec 07 §8): - integers `u8`…`u128`, `usize`, `i8`…`i128`, `isize`; `bool`, `void`, `never`; - named types; - `ref`, `mut`, `slice`, `slice_mut`; - `own`, `own_array`, `region`; - `cap`; - `file`, `listener`, `stream`; - `task`, `sender`, `receiver`, `mutex`; - the built-in enums `io_error`, `alloc_error`, `cap_error`. Arrays are written `[T; N]`. `scope`, `shield` and `guard` 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 take one. | 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` | | `r.f = e;` | store into a field through `mut` | | `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`). 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`, `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.** `Pair { a: 1, b: 2 }` (every field, in any order); `Shape.Square(4)`; `[e; N]` (`array.splat`). `v.f` on a struct value is `struct.get`. **Calls.** `f(args)` calls a function of the module. 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`. | Source | Meaning | |---|---| | `ref place` | shared borrow (`borrow.ref`, `borrow.field`, `borrow.index`, `slice.make`, `slice.sub` as the place requires) | | `mut place` | exclusive borrow | | `*r` | load through `ref`/`mut` | | `r.f` | load of a field through a borrow of a struct | | `s.len` | `slice.len` of a slice, or the static length of an array | | `s.split_at(k)` | `slice.split`; bound with `let (left, right) = …;` | | `copy(dst, src)` | `slice.copy` | - **Indexing.** `s[i]` is a checked index (`T0008`). Inside the true branch of `if i < s.len`, with `i` and `s` unchanged, the frontend emits `borrow.index.proven`. The verifier confirms the fact; otherwise the index stays checked. - **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. **Moves.** - A named linear value is consumed only by `move x`. Using a named linear value as a consuming operand without `move` is `E7003`. - 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` 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(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; } } ``` - **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`. - **`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 arms its variants, with `_` as default. A `match` over an integer arms literals, with `_` required. ## 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. Inside it: - `task.spawn(s, f, args)` spawns; borrow arguments are lent until the join (spec 04 §34); - `task.join(move t)` joins; - 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(n, mem)`: a match, §6; - `channel.dup(tx)`; - `channel.send(tx, v)` (`move v` for a linear `v`); - `channel.recv(rx)`; - `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) => … } ``` Arms bind the send values not sent on their edge, in the order of first appearance (spec 04 §39). **Mutex:** - `mutex.make(v)`; - `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`; 2. on the `ok` edge: `mutex.borrow` of the guard, bound as `x: mut`; 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: - `file<…>`, `stream`, `listener`, `region`; - `sender`, `receiver`; - `task` 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`. ## 8. Allocation, resources and intrinsics Allocation and resource operations keep their AIR names and operand order: - `own.new(mem, v)` and `own.array(mem, n, v)` (matches, §6); - `own.take(move o)`, `own.free(move o)`; - `region.create(mem)`, `region.new(r, v)`, `region.array(r, n, v)`; - `region.reset(r)`, `region.destroy(move r)`; - `cap.narrow.budget(c, n)`, `cap.narrow.prefix(c, path)`; - intrinsics under their registered names (`reference/intrinsics.md`): `io.stdout_write(out, ref buf[0..n])`, `fs.open_read(c, b"data.txt")`, `fs.close(move f)`, `net.listen(c, b"127.0.0.1:7")`. A byte string or array used where a `slice` is expected is materialized in frame storage and borrowed for the operation. ## 9. Frame storage, borrow scopes and features - **Frame storage.** A variable whose place is borrowed lowers to `local` storage allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation. - **Borrow scopes.** A borrow bound by `let` ends at the end of the block that contains the `let`. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope. 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. `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, reported with `source_location` (file, line, column of the construct the instruction came from) and `air_location` (function, block, instruction) | | syntax, name resolution, lowering and invalid source constructs | `E7xxx`, below | | trap at run time | the trap record also carries `source_location` | | Code | Kind | Meaning | |---|---|---| | E7001 | source.syntax | Malformed `.aji` source | | E7002 | source.unknown_name | Undefined variable, function, type, field or variant | | 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) | ## 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 |