diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md index 6cbb7dc..ec7ef2f 100644 --- a/docs/reference/error-codes.md +++ b/docs/reference/error-codes.md @@ -78,6 +78,20 @@ Draft registry. Codes are stable once released in a tagged compiler version. | E6001 | unsafe.required | Operation requires explicit unsafe boundary; field `reason`: `outside_boundary`, `trusted_declares_unsafe` | | E6101 | abi.unaligned_reference | Normal reference requested from insufficiently aligned storage | +## E7xxx — Source language `.aji` (spec 15 §10) + +Only problems that exist because of the frontend. Everything the verifier decides keeps its AIR code, reported at the 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 | +| E7007 | source.ambiguous | Source meaning cannot be determined | + ## T0xxx — Runtime traps Reported in trap records (spec 01 §6), not by the verifier. diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index d0b0110..ebe9b6c 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -1,51 +1,94 @@ -(* Aji draft grammar sketch. This is intentionally incomplete until syntax stabilizes. *) +(* Aji source language `.aji` 0.1 (Phase 6A). Normative together with + docs/spec/15-source-language.md. Decision record: RFC 0013. -program = { module_decl | import_decl | type_decl | function_decl } ; + Lexical conventions + ------------------- + - `//` starts a comment that runs to the end of the line. + - Whitespace and line breaks separate tokens and are otherwise insignificant. + - Keywords: module type struct enum fn effects trusted from let var zero + if else while for in loop break continue return trap match select + scope shield lock as cancelled ref mut move unchecked or and not + true false recv send. + - Every construct has one canonical spelling (spec 15 §1). +*) -module_decl = "module" qualified_name ";" ; -import_decl = "use" qualified_name [ "as" identifier ] ";" ; +module = "module" path { item } ; +item = type_decl | fn_decl ; +path = ident { "." ident } ; -function_decl = [ "pub" ] [ "unsafe" ] "fn" identifier - [ generic_params ] - "(" [ parameter_list ] ")" - [ "->" type ] - effect_decl - [ contract_block ] - block ; +type_decl = "type" ident "=" ( struct_body | enum_body ) ; +struct_body = "struct" "{" [ field { "," field } [ "," ] ] "}" ; +field = ident ":" type ; +enum_body = "enum" "{" [ variant { "," variant } [ "," ] ] "}" ; +variant = ident [ "(" type { "," type } ")" ] ; -effect_decl = "effects" "[" [ effect_list ] "]" ; +fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" ident ] + "effects" "[" [ path { "," path } ] "]" + [ "trusted" string ] + block ; +param = ident ":" type ; -parameter_list = parameter { "," parameter } ; -parameter = identifier ":" param_type ; -param_type = [ "move" ] type - | "ref" "<" type ">" - | "mut" "<" type ">" ; +type = int_type | "bool" | "void" | "never" | ident + | "[" type ";" int_lit "]" + | wrapper "<" type ">" + | "cap" "<" path ">" + | "file" "<" ( "read" | "write" | "append" ) ">" ; +wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array" + | "task" | "sender" | "receiver" | "mutex" ; +int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize" + | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ; + (* `region`, `listener`, `stream`, `io_error`, `alloc_error`, + `cap_error` are built-in type names (ident). *) -type = primitive_type - | qualified_name - | "Option" "<" type ">" - | "Result" "<" type "," type ">" - | "Own" "<" type ">" - | "Island" "<" type ">" - | "Frozen" "<" type ">" - | "Arc" "<" type ">" - | "slice" "<" type ">" - | "slice_mut" "<" type ">" - | "ref" "<" type ">" - | "mut" "<" type ">" - | "[" type ";" integer_literal "]" ; +block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *) +statement = "let" binding [ ":" type ] "=" expr ";" + | "var" ident ":" type "=" ( expr | "zero" ) ";" + | place "=" expr ";" + | "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";" + | expr ";" + | block_stmt ; +binding = ident | "(" ident "," ident ")" ; (* the pair form only for `split_at` *) +block_stmt = if_expr | match_expr | select_stmt | block + | "while" expr block + | "for" ident "in" expr ".." expr block + | "loop" block + | "scope" ident block + | "shield" block + | "lock" "ref" place "as" ident block "cancelled" block ; -primitive_type = "bool" | "byte" | "void" | "never" - | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" - | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" - | "f32" | "f64" ; +if_expr = "if" expr block [ "else" ( if_expr | block ) ] ; +match_expr = "match" expr "{" { arm } "}" ; +arm = pattern "=>" ( block | expr "," ) ; +pattern = "_" | int_lit + | ident [ "(" ident { "," ident } ")" ] ; (* variant or outcome: ok(n), closed, Shape.Rect(w, h) is written Rect(w, h) *) -block = "{" { statement } "}" ; -statement = let_stmt | var_stmt | return_stmt | expr_stmt | block ; -let_stmt = "let" identifier [ ":" type ] "=" expression ";" ; -var_stmt = "var" identifier [ ":" type ] "=" expression ";" ; -return_stmt = "return" [ expression ] ";" ; -expr_stmt = expression ";" ; +select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ; +select_arm = "recv" "(" ident ")" "{" { arm } "}" + | "send" "(" ident "," expr ")" "{" { arm } "}" ; -qualified_name = identifier { "." identifier } ; -identifier = letter { letter | digit | "_" } ; +expr = or_expr ; +or_expr = and_expr { "or" ( and_expr | "trap" ) } ; (* `e or trap`: the only fallible shorthand *) +and_expr = cmp_expr { "and" cmp_expr } ; +cmp_expr = bit_expr [ ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) bit_expr ] ; +bit_expr = shift_expr { ( "&" | "|" | "^" ) shift_expr } ; +shift_expr = add_expr { ( "<<" | ">>" ) add_expr } ; +add_expr = mul_expr { ( "+" | "-" | "+%" | "-%" ) mul_expr } ; +mul_expr = cast_expr { ( "*" | "/" | "%" | "*%" ) cast_expr } ; +cast_expr = unary { ( "as" | "as!" | "as%" ) type } ; +unary = ( "-" | "not" | "*" ) unary + | ( "ref" | "mut" ) [ "unchecked" ] place + | "move" ident + | postfix ; +postfix = primary { "." ident | "[" expr [ ".." expr ] "]" | call_args } ; +call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ; +primary = int_lit | "true" | "false" | string + | ident [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *) + | "[" expr ";" int_lit "]" + | "(" expr ")" + | if_expr | match_expr | block ; +field_init = ident ":" expr ; +place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ; + +int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ; +string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \t \\ \" \xHH *) +ident = ( letter | "_" ) { letter | digit | "_" } ; diff --git a/docs/rfcs/0013-source-language-6a.md b/docs/rfcs/0013-source-language-6a.md index 5a4fe7d..d287cd6 100644 --- a/docs/rfcs/0013-source-language-6a.md +++ b/docs/rfcs/0013-source-language-6a.md @@ -1,6 +1,7 @@ # RFC 0013: The `.aji` Source Language, Phase 6A -Status: Proposed +Status: Accepted (owner decisions D1–D7 and the boundary rule; normative text in spec 15) +Integrated into: spec 15 (new); `reference/grammar.ebnf`; `reference/error-codes.md` (E7001–E7007); spec 05 / verifier (`E3101` `suggested_effects`); spec README Scope: source language `.aji` 0.1 for the semantics of AIR format 0 features of Phases 0–3; no change to AIR, the verifier or the runtime Language version: 0.1 Supersedes: the grammar sketch in `reference/grammar.ebnf` @@ -325,15 +326,37 @@ The frontend lives in `src/frontend/`: `lex`, `parse`, `resolve`, `check`, `lowe - **Inferring effects:** violates "effects are part of the public contract" (AGENTS.md). - **A new surface unlike any known language:** wastes the agents' priors and makes the bundle bigger. -## Decisions requested +## Decisions (owner) -- **D1 — lock as a block** (`lock ref m as x { … } cancelled { … }`, unlock at block exit). The alternative is explicit `unlock(move g)` with guard values. Proposal: the block. It makes the guard lexical, which matches the critical-section rule, and removes a leak class. -- **D2 — lexical borrow scopes.** A borrow ends at the end of its block; earlier ends use an inner block. The alternative is an explicit `end(r)`. Proposal: lexical, with no explicit end in 6A. -- **D3 — `move` required for every consumption of a linear value.** Proposal: yes. Ownership transfer is the reasoning Aji externalizes. -- **D4 — frame storage chosen by the frontend for borrowed variables.** Proposal: yes. Frame storage is static and not an allocation in the sense of spec 01 §2. -- **D5 — effects stay explicit.** Proposal: yes, with `E3101` naming the full list the function needs. -- **D6 — Rust/Zig-like surface** to use model priors, with keywords where the meaning differs (`ref`, `mut`, `move`, `or trap`, `as!`, `as%`, `+%`). Proposal: yes. -- **D7 — the `E7xxx` range** for source-only diagnostics, and the AIR codes for everything the verifier decides. Proposal: yes. +All seven accepted, with these refinements (normative in spec 15): + +- **Boundary rule.** Source syntax may hide representation mechanics: + - SSA; + - the CFG and block arguments; + - `borrow.end`; + - `local.alloc`; + - `features [...]`. + + It must not hide authority, allocation, ownership transfer, synchronization, external effects or recoverable failure. +- **D1 — lock block, accepted.** `lock ref m as x { … } cancelled { … }` is a syntactic lowering: + 1. `mutex.lock`; + 2. `mutex.borrow` bound as `x: mut`; + 3. the body; + 4. `borrow.end` and `mutex.unlock` at every normal exit, including `return`, `break` and `continue` that leave the block. + + Nothing happens on a trap, because there is no unwinding. The guard is never a source value. +- **D2 — lexical borrows, accepted.** A borrow ends at the end of its block. An earlier end needs an inner block. There is no last-use inference: lexical source lifetime maps to an exact explicit lifetime in AIR. NLL may be discussed separately if benchmarks show its cost. +- **D3 — explicit `move`, accepted.** It is required when consuming a **named** linear value. A temporary needs none: `consume(make_value())`. +- **D4 — compiler-managed frame storage, accepted.** There is no hidden heap allocation, and the frame-size limit and address stability are preserved. +- **D5 — explicit effects, accepted.** "Explicit effects, assisted bookkeeping": `E3101` carries `suggested_effects`, the complete sorted list the function needs. +- **D6 — Rust/Zig familiarity, accepted.** A familiar operation gets a familiar form, and different semantics get their own word or operator. Every construct has **one canonical spelling**, with a minimum of alternatives. 6A has no compound assignment (`+=`): `x = x + 1;` is the only form. +- **D7 — `E7xxx` for frontend diagnostics only, accepted.** It covers syntax, names, lowering, invalid and ambiguous constructs (`E7001`–`E7007`). Verifier findings keep their AIR codes, with `source_location` (primary) and `air_location` (metadata). + +Further spec-15 choices made while writing the normative text: + +- built-in operations are called by their AIR names (`channel.send`, `own.new`, `task.spawn`), a one-to-one map to AIR; +- resource and endpoint operands are borrowed for the duration of an operation, while data borrows are always written; +- a mutex is borrowed explicitly (`lock ref m`). ## Open questions diff --git a/docs/spec/01-language-overview.md b/docs/spec/01-language-overview.md index 6bc6e08..05db3e5 100644 --- a/docs/spec/01-language-overview.md +++ b/docs/spec/01-language-overview.md @@ -26,7 +26,7 @@ The compiler MAY provide source syntax that lowers to explicit AIR, but the sema Illustrative source: ```aji -module example; +module example fn add(a: u64, b: u64) -> u64 effects [] @@ -35,6 +35,8 @@ effects [] } ``` +The normative source language is specified in spec 15. + A program is composed of: - modules; @@ -63,12 +65,12 @@ AIR lowers these constructs to basic blocks, branches, block parameters and term Aji has no exceptions. -Fallible operations return `Result`. +Fallible operations have explicit outcomes. In `.aji` 0.1 every outcome is an arm of a `match` (spec 15 §6): ```aji -match fs.read(file, buffer) { - Ok(n) => consume(n), - Err(e) => return Err(e), +match fs.read(file, mut buffer) { + ok(n) => { consume(n); } + err(e) => { return Status.ReadFailed; } } ``` diff --git a/docs/spec/05-effects-and-capabilities.md b/docs/spec/05-effects-and-capabilities.md index 4c8e6f1..f73b047 100644 --- a/docs/spec/05-effects-and-capabilities.md +++ b/docs/spec/05-effects-and-capabilities.md @@ -152,6 +152,7 @@ In a module that declares `effects`: - For every `intrinsic` in `f` (§11): the intrinsic's effect is in `effects(f)`, otherwise `E3101`. - For every other instruction whose contract names an effect (for example `task.spawn`, `channel.make`, and in a module declaring `cancellation` every suspending operation, spec 04 §37.4): that effect is in `effects(f)`, otherwise `E3101`. - Because every function is checked against its direct callees, the rule holds transitively, including for recursion. +- Each `E3101` carries `suggested_effects`: the function's declared effects plus every missing one, sorted. Effects stay declared by the programmer; the suggestion only makes the repair mechanical. **Indirect calls (normative for future features).** When function values are introduced, the effect set MUST be part of the function type, for example `fnptr<(u8) -> void effects [io.write]>`, and an indirect call is checked against that set exactly like a direct call. Otherwise dynamic calls would break transitivity. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md new file mode 100644 index 0000000..63bb223 --- /dev/null +++ b/docs/spec/15-source-language.md @@ -0,0 +1,292 @@ +# 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, move 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 | diff --git a/docs/spec/README.md b/docs/spec/README.md index 6833d01..d8c4c4e 100644 --- a/docs/spec/README.md +++ b/docs/spec/README.md @@ -24,6 +24,7 @@ The specification is split by semantic domain. Rationale for major decisions liv | [12-packages-and-build.md](12-packages-and-build.md) | Normative draft | Manifest/build model | | [13-contracts-and-unsafe.md](13-contracts-and-unsafe.md) | Normative draft | Contracts, proof status and unsafe boundaries | | [14-agent-efficiency.md](14-agent-efficiency.md) | Normative draft (design objectives) | Agent efficiency, Model Capability Compression, design review requirement | +| [15-source-language.md](15-source-language.md) | Normative draft | The agent-facing source language `.aji` 0.1 (Phase 6A), lowering to AIR | ## Reading order diff --git a/src/diag.zig b/src/diag.zig index 6e7cb40..aceaf9f 100644 --- a/src/diag.zig +++ b/src/diag.zig @@ -64,6 +64,13 @@ pub const registry = [_]Code{ // E6xxx — Unsafe/ABI .{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary; field `reason`: `outside_boundary`, `trusted_declares_unsafe`" }, .{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" }, + .{ .id = "E7001", .kind = "source.syntax", .meaning = "Malformed `.aji` source" }, + .{ .id = "E7002", .kind = "source.unknown_name", .meaning = "Undefined variable, function, type, field or variant" }, + .{ .id = "E7003", .kind = "source.missing_move", .meaning = "Named linear value consumed without `move`" }, + .{ .id = "E7004", .kind = "source.not_exhaustive", .meaning = "`match` misses an outcome, variant or default" }, + .{ .id = "E7005", .kind = "source.type_mismatch", .meaning = "Expression has the wrong type in a source position" }, + .{ .id = "E7006", .kind = "source.invalid_construct", .meaning = "Construct not allowed here" }, + .{ .id = "E7007", .kind = "source.ambiguous", .meaning = "Source meaning cannot be determined" }, // T0xxx — Runtime traps (reported in trap records, not by the verifier) .{ .id = "T0001", .kind = "trap.explicit", .meaning = "`trap` instruction executed" }, .{ .id = "T0002", .kind = "trap.assert", .meaning = "Assertion failed" }, diff --git a/src/verifier/effects.zig b/src/verifier/effects.zig index b8711ba..e12e567 100644 --- a/src/verifier/effects.zig +++ b/src/verifier/effects.zig @@ -10,11 +10,14 @@ const air = @import("../air.zig"); const verifier = @import("../verifier.zig"); const Context = verifier.Context; +const diag = @import("../diag.zig"); pub fn check(c: *Context) !void { const m = c.module; if (!m.declares("effects")) return; for (m.functions) |f| { + const first = c.diags.items.len; + defer suggest(c, f, first) catch {}; for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) { .task_spawn => |x| { if (!contains(f.effects, "task.spawn")) try c.report("E3101", inst.span, "task.spawn requires the effect task.spawn", &.{ @@ -65,6 +68,35 @@ pub fn check(c: *Context) !void { } } +/// Adds `suggested_effects` to every E3101 reported for `f` since diagnostic +/// `first`: the complete, sorted effect list the function needs (its declared +/// effects plus every missing one). Effects stay declared by the programmer; +/// the suggestion makes the repair mechanical. +fn suggest(c: *Context, f: air.Function, first: usize) !void { + var list: std.ArrayList([]const u8) = .empty; + for (f.effects) |e| if (!contains(list.items, e)) try list.append(c.arena, e); + const new = c.diags.items[first..]; + for (new) |d| if (std.mem.eql(u8, d.code.id, "E3101")) for (d.fields) |fld| { + if (std.mem.eql(u8, fld.name, "effect") and !contains(list.items, fld.value.str)) try list.append(c.arena, fld.value.str); + }; + if (list.items.len == f.effects.len) return; + std.mem.sort([]const u8, list.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + return std.mem.lessThan(u8, a, b); + } + }.lt); + var w: std.Io.Writer.Allocating = .init(c.arena); + w.writer.writeAll("[") catch return error.OutOfMemory; + for (list.items, 0..) |e, i| w.writer.print("{s}{s}", .{ if (i == 0) "" else ", ", e }) catch return error.OutOfMemory; + w.writer.writeAll("]") catch return error.OutOfMemory; + for (new) |*d| if (std.mem.eql(u8, d.code.id, "E3101")) { + const fields = try c.arena.alloc(diag.Field, d.fields.len + 1); + @memcpy(fields[0..d.fields.len], d.fields); + fields[d.fields.len] = .{ .name = "suggested_effects", .value = .{ .str = w.written() } }; + d.fields = fields; + }; +} + fn need(c: *Context, f: air.Function, inst: air.Inst, effect: []const u8) !void { if (contains(f.effects, effect)) return; try c.report("E3101", inst.span, "instruction requires an effect the function does not declare", &.{