From 41b764ccfdbd18dea40e093cdbc54992e5353b53 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 12:14:25 +0300 Subject: [PATCH] spec: Phase 0 spec gate (P0-1, P0-2, P0-3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - text AIR format 0: grammar (reference/air-text.ebnf) and module, block, SSA, type and canonical-form rules (spec 07 §8) - instruction contracts for format 0 (new spec 07a) - traps: stable T0xxx codes and trap records (spec 01 §6) - integer edge cases and explicit casts (spec 02 §2.1) - fixed verifier resource limits (spec 08 §7) - target description with pointer_bits (spec 09 §9) - new codes E0001-E0006, E1003, T0001-T0007 - resolves Q-001, Q-003..Q-008, Q-018; Q-002 resolved for format 0 --- docs/design/open-questions.md | 34 +++- docs/plan/README.md | 2 +- docs/plan/phase-0-semantic-skeleton.md | 12 +- docs/plan/phase-1-ownership-and-memory.md | 2 +- docs/reference/air-text.ebnf | 95 +++++++++++ docs/reference/error-codes.md | 26 +++ docs/spec/01-language-overview.md | 2 + docs/spec/02-types-and-values.md | 10 ++ docs/spec/07-air.md | 46 ++++++ docs/spec/07a-air-instructions.md | 183 ++++++++++++++++++++++ docs/spec/08-verifier.md | 16 +- docs/spec/09-runtime-and-abi.md | 12 ++ docs/spec/README.md | 3 +- 13 files changed, 425 insertions(+), 18 deletions(-) create mode 100644 docs/reference/air-text.ebnf create mode 100644 docs/spec/07a-air-instructions.md diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 7087a02..417b5bf 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -6,14 +6,14 @@ Status values: `open`, `resolved`. | ID | Status | Blocks | Question | |---|---|---|---| -| Q-001 | open | P0 | Text AIR grammar | +| Q-001 | resolved | P0 | Text AIR grammar | | Q-002 | open | P0 | Instruction contract tables | -| Q-003 | open | P0 | Diagnostic codes for parse errors | -| Q-004 | open | P0 | Observable trap semantics | -| Q-005 | open | P0 | Verifier resource budget values | -| Q-006 | open | P0 | Target description for `usize` and layout in the interpreter | -| Q-007 | open | P0 | Integer edge cases besides overflow | -| Q-008 | open | P0 | How `hello` writes output before capabilities exist | +| Q-003 | resolved | P0 | Diagnostic codes for parse errors | +| Q-004 | resolved | P0 | Observable trap semantics | +| Q-005 | resolved | P0 | Verifier resource budget values | +| Q-006 | resolved | P0 | Target description for `usize` and layout in the interpreter | +| Q-007 | resolved | P0 | Integer edge cases besides overflow | +| Q-008 | resolved | P0 | How `hello` writes output before capabilities exist | | Q-009 | open | P1 | Borrow lifetimes in AIR | | Q-010 | open | P1 | Region generation checks: static, dynamic, or both | | Q-011 | open | P2 | Effect hierarchy and discharge | @@ -23,7 +23,7 @@ Status values: `open`, `resolved`. | Q-015 | open | P5 | Operational weak-memory model for the interpreter | | Q-016 | open | P0 | Floating-point determinism | | Q-017 | open | P5 | Replay file format | -| Q-018 | open | P2 | Runtime diagnostics (traps) vs verifier diagnostics | +| Q-018 | resolved | P2 | Runtime diagnostics (traps) vs verifier diagnostics | ## Q-001 — Text AIR grammar @@ -31,36 +31,52 @@ Spec 07 shows illustrative AIR but no grammar. Undecided: comment syntax; consta Proposed home: `docs/reference/air-text.ebnf` plus normative text in spec 07. +**Resolved (P0-1):** `docs/reference/air-text.ebnf` and spec 07 §8. Comments use `;`; opcodes carry the type suffix (`add.checked.u64`, `const.u64 5`); the module header is four lines (`module`, `air`, `lang`, `features`). + ## Q-002 — Instruction contract tables Spec 07 §4 and RFC 0004 require per-opcode contracts (operands, results, ownership/borrow transition, memory set, sync, effects, capabilities, traps, transfer function, interpreter behavior). None are written. Each phase must write the contracts for the opcodes it introduces before implementing them. Proposed home: a normative `docs/spec/07-air.md` appendix or `docs/spec/air/` per instruction family. +**Partially resolved (P0-3):** format-version-0 instructions are specified in spec 07a. Stays open for the instructions of later phases. + ## Q-003 — Diagnostic codes for parse errors The registry has no codes for malformed AIR text. Options: a new `E0xxx` range for syntax, or `E50xx` under AIR/verifier. +**Resolved (P0-1):** new range `E0xxx` (E0001–E0006) for text and module errors. Undefined values and unknown block labels use the semantic codes `E5001` and `E5002`. + ## Q-004 — Observable trap semantics Spec 01 §6 defines a trap as termination "according to runtime policy". The interpreter needs: trap kinds (overflow, assert, bounds, explicit, …), how a trap is reported (exit status, structured record), and whether the trap location is observable. +**Resolved (P0-2):** spec 01 §6. Traps terminate the program and produce a record with a stable `T0xxx` code, function, block and instruction index. + ## Q-005 — Verifier resource budget values Spec 08 §7 says budgets are "configured/spec-defined". A user-configurable budget would let a flag change which programs are accepted, which conflicts with "no compiler flags that change language semantics". Proposal: fixed spec-defined budgets per profile, reported in `E5101`. +**Resolved (P0-2):** fixed, non-configurable limits in spec 08 §7. + ## Q-006 — Target description in the interpreter `usize`/`isize` match the target pointer width (spec 02 §1) and struct layout is implementation-defined (spec 02 §7). For determinism the interpreter must run against an explicit target description. Undecided: format, default, and whether it is part of the AIR module (spec 00 §5 "optional target requirements"). +**Resolved (P0-2):** spec 09 §9. Target description with `pointer_bits`; the interpreter defaults to `air64`. `usize`/`isize` are never `widen` operands, so verification is target-independent. + ## Q-007 — Integer edge cases besides overflow Unspecified: division and remainder by zero; signed `MIN / -1`; shift amounts ≥ bit width; signed right shift; casts between widths and signedness (spec 01 §2 forbids implicit conversion but explicit cast semantics are absent). +**Resolved (P0-2):** spec 02 §2.1 and spec 07a. + ## Q-008 — `hello` before capabilities Phase 0's exit criterion runs AIR `hello`, but `io.stdout_write` needs `cap` (Phase 2). Options: bring a minimal `io.write` capability and intrinsic into Phase 0, or define Phase 0 `hello` as a function whose return value the test harness checks. +**Resolved (P0-2):** Phase 0 `hello` is a `@main` that returns a value which `aji run` reports (spec 07a "Run result"). A `hello` that writes to stdout moves to P2-11, after slices (P1) and capabilities (P2). + ## Q-009 — Borrow lifetimes in AIR Spec 03 §4 shows `'a` lifetimes in source; AIR has `borrow.ref`/`borrow.end` but no notation for lifetime relationships across function signatures. Undecided: explicit lifetime parameters in AIR signatures vs scope-based borrows only. @@ -100,3 +116,5 @@ Spec 11 §4 mentions `.ajr` files without a format or compatibility rule. ## Q-018 — Runtime diagnostics The error registry covers verifier/compiler errors. Traps and runtime check failures (bounds, generation, overflow) need stable machine-readable records too, either in the same registry (e.g. `R` codes) or a separate one. + +**Resolved (P0-2):** traps share the registry in a separate `T0xxx` range (`docs/reference/error-codes.md`). diff --git a/docs/plan/README.md b/docs/plan/README.md index ba7d317..5231f43 100644 --- a/docs/plan/README.md +++ b/docs/plan/README.md @@ -93,5 +93,5 @@ These run through all phases rather than belonging to one. | Phase | Status | |---|---| -| P0 | not started | +| P0 | in progress: spec gate (P0-1…P0-3) done | | P1–P8 | not started | diff --git a/docs/plan/phase-0-semantic-skeleton.md b/docs/plan/phase-0-semantic-skeleton.md index 8a90585..14ec6d9 100644 --- a/docs/plan/phase-0-semantic-skeleton.md +++ b/docs/plan/phase-0-semantic-skeleton.md @@ -4,7 +4,7 @@ Non-normative. Part of the [implementation plan](README.md). **Goal:** an executable core: AIR data model, text parser and serializer, CFG/SSA/type verification, and a deterministic interpreter for integer programs. -**Exit criterion:** AIR `hello` and arithmetic tests execute identically across runs. +**Exit criterion:** AIR `hello` and arithmetic tests execute identically across runs. Per Q-008, Phase 0 `hello` is a `@main` returning a value; output to stdout arrives in P2-11. **Spec inputs:** spec 00 §5–6, 01 §6, 02 §1–3, 07, 08 §1–2, §7, 10 §2, 11 §1. RFC 0004 moves to Accepted at the end of this phase. @@ -12,17 +12,17 @@ Non-normative. Part of the [implementation plan](README.md). ## Scope -In: integer types, `bool`, `void`, `never`; structs, enums, fixed arrays as values; functions and direct calls; `br`, `cbr`, `switch`, `ret`, `trap`, `assert`; checked and wrapping arithmetic, bitwise ops, comparisons, explicit casts. +In: integer types, `bool`, `void`, `never`; structs and enums as values; functions and direct calls; `br`, `cbr`, `switch`, `ret`, `trap`, `assert`; checked and wrapping arithmetic, bitwise ops, comparisons, explicit casts. -Out: floats (deferred until Q-016 is answered), borrows, memory, effects other than `[]`, concurrency. +Out: floats (reserved until Q-016 is answered), fixed arrays (moved to P1 with slices and bounds), borrows, memory, effect checking, concurrency. ## Tasks | ID | Status | Task | Depends | Output | Done when | |---|---|---|---|---|---| -| P0-1 | todo | Specify text AIR grammar (Q-001) and parse-error codes (Q-003) | — | `docs/reference/air-text.ebnf`, spec 07, error-codes.md | grammar covers module header with version/feature bits, type declarations, functions, `effects`, blocks with parameters, instructions, comments; seed tests in `tests/conformance/phase0` conform to it | -| P0-2 | todo | Specify traps (Q-004), integer edge cases and casts (Q-007), target description (Q-006), verifier budget (Q-005), `hello` strategy (Q-008) | — | spec 01, 02, 08, 11 | each question marked resolved in `open-questions.md` | -| P0-3 | todo | Write contract tables for Phase 0 opcodes; add aggregate opcodes (struct/enum construct and access) if needed, via RFC 0004 amendment | P0-1 | spec 07 appendix | every in-scope opcode has all fields required by spec 07 §4 | +| P0-1 | done | Specify text AIR grammar (Q-001) and parse-error codes (Q-003) | — | `docs/reference/air-text.ebnf`, spec 07, error-codes.md | grammar covers module header with version/feature bits, type declarations, functions, `effects`, blocks with parameters, instructions, comments; seed tests in `tests/conformance/phase0` conform to it | +| P0-2 | done | Specify traps (Q-004), integer edge cases and casts (Q-007), target description (Q-006), verifier budget (Q-005), `hello` strategy (Q-008) | — | spec 01, 02, 08, 11 | each question marked resolved in `open-questions.md` | +| P0-3 | done | Write contract tables for Phase 0 opcodes; add aggregate opcodes (struct/enum construct and access) if needed, via RFC 0004 amendment | P0-1 | spec 07 appendix | every in-scope opcode has all fields required by spec 07 §4 | | P0-4 | todo | AIR data model | P0-1 | `src/air/{types,module,ops}.zig` | unit tests build the seed-test modules programmatically | | P0-5 | todo | Text AIR lexer and parser | P0-4 | `src/air/parse.zig` | all seed tests parse; malformed input yields registered diagnostics with spans | | P0-6 | todo | Canonical serializer | P0-4 | `src/air/print.zig` | `print(parse(x))` is a fixed point after one round; fuzz test on parser round-trip | diff --git a/docs/plan/phase-1-ownership-and-memory.md b/docs/plan/phase-1-ownership-and-memory.md index 27068b2..5c316ac 100644 --- a/docs/plan/phase-1-ownership-and-memory.md +++ b/docs/plan/phase-1-ownership-and-memory.md @@ -12,7 +12,7 @@ Non-normative. Part of the [implementation plan](README.md). ## Scope -In: `move`, `copy`; `borrow.ref`, `borrow.mut`, `borrow.end`; `load`, `store`; `own.alloc`, `own.free`; `region.create`, `region.alloc`, `region.alloc_uninit`, `region.reset`, `region.destroy`; `slice.make`, `slice.sub`, split operations; `mem.copy`, `mem.zero`; `guard`; `Uninit`; `Option>`. +In: `move`, `copy`; `borrow.ref`, `borrow.mut`, `borrow.end`; `load`, `store`; `own.alloc`, `own.free`; `region.create`, `region.alloc`, `region.alloc_uninit`, `region.reset`, `region.destroy`; `slice.make`, `slice.sub`, split operations; `mem.copy`, `mem.zero`; `guard`; fixed arrays `[T; N]` with checked indexing (moved from P0); `Uninit`; `Option>`. Out: islands, `Arc`, `Pin`, raw addresses (beyond rejecting them in safe code). diff --git a/docs/reference/air-text.ebnf b/docs/reference/air-text.ebnf new file mode 100644 index 0000000..3059408 --- /dev/null +++ b/docs/reference/air-text.ebnf @@ -0,0 +1,95 @@ +(* Aji text AIR, format version 0. + Normative together with docs/spec/07-air.md §8 and docs/spec/07a-air-instructions.md. + + Lexical conventions + ------------------- + - A comment starts with ";" and runs to the end of the line. + - Line breaks are significant: each header line, declaration header, + block label and instruction ends with NL. Line breaks inside "(" ")", + "[" "]" and "{" "}" are ignored. + - Spaces and tabs separate tokens and are otherwise insignificant. + - Opcodes are written as one dotted word, e.g. "add.checked.u64". + + Name spaces + ----------- + - "%name" SSA value, scoped to its function. + - "@name" function, type or block label. Functions and types share the + module scope; block labels are scoped to their function. A label + reference appears only in branch targets, so it never clashes + with a function name. + - bare field names, variant names, module path segments, effect names. +*) + +module = { NL } header { NL } { declaration { NL } } ; + +header = "module" path NL + "air" int_lit NL (* AIR text format version; this file defines 0 *) + "lang" version_lit NL (* Aji semantic version, e.g. 0.1 *) + "features" "[" [ path_list ] "]" NL ; (* required feature names; empty in format 0 *) + +declaration = type_decl | function ; + +type_decl = "type" global "=" ( struct_type | enum_type ) NL ; +struct_type = "struct" "{" [ field { "," field } [ "," ] ] "}" ; +field = ident ":" type ; +enum_type = "enum" "{" variant { "," variant } [ "," ] "}" ; +variant = ident [ "(" [ type { "," type } ] ")" ] ; + +function = "fn" global "(" [ param_list ] ")" "->" type NL + "effects" "[" [ path_list ] "]" NL + block { block } ; +param_list = param { "," param } ; +param = local ":" type ; + +block = ident [ "(" [ param_list ] ")" ] ":" NL { instruction NL } ; + (* The first block is the entry block and takes no parameters. *) + +instruction = [ local "=" ] operation ; + +operation = "const." int_type int_lit + | "const.bool" ( "true" | "false" ) + | "copy" local + | arith_op local "," local + | "assert" local + | "cast." cast_mode "." int_type local + | "struct.make" global "(" [ local_list ] ")" + | "struct.get" global "." ident "," local + | "enum.make" global "." ident "(" [ local_list ] ")" + | "call" global "(" [ local_list ] ")" + | terminator ; + +arith_op = ( "add" | "sub" | "mul" ) "." ( "checked" | "wrap" ) "." int_type + | ( "div" | "rem" ) ".checked." int_type + | ( "and" | "or" | "xor" ) "." ( int_type | "bool" ) + | ( "shl" | "shr" ) "." int_type + | ( "eq" | "ne" ) "." ( int_type | "bool" ) + | ( "lt" | "le" | "gt" | "ge" ) "." int_type ; + +cast_mode = "checked" | "wrap" | "widen" ; + +terminator = "br" target + | "cbr" local "," target "," target + | "switch." int_type local "," { int_lit "->" target "," } "default" "->" target + | "enum.switch" global local "," enum_arm { "," enum_arm } [ "," "default" "->" target ] + | "ret" [ local ] + | "trap" ; +enum_arm = ident "->" global ; (* target block receives the variant payload as parameters *) +target = global "(" [ local_list ] ")" ; + +type = int_type | "bool" | "void" | "never" | global ; +int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize" + | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ; + (* "f32" and "f64" are reserved; see spec 07 §8.4. "byte" is not an AIR type: frontends lower it to u8. *) + +local_list = local { "," local } ; +path_list = path { "," path } ; +path = ident { "." ident } ; + +local = "%" name_char { name_char } ; +global = "@" ident ; (* no dots inside a global name *) +ident = ( letter | "_" ) { name_char } ; +name_char = letter | digit | "_" ; + +int_lit = [ "-" ] ( dec_digits | "0x" hex_digits | "0b" bin_digits ) ; + (* "_" may separate digits; it carries no meaning. *) +version_lit = digit { digit } "." digit { digit } ; diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md index 2aa159e..20a5a53 100644 --- a/docs/reference/error-codes.md +++ b/docs/reference/error-codes.md @@ -2,12 +2,24 @@ Draft registry. Codes are stable once released in a tagged compiler version. +## E0xxx — AIR text and module + +| Code | Kind | Meaning | +|---|---|---| +| E0001 | parse.unexpected_token | Token not allowed by the text AIR grammar here | +| E0002 | parse.invalid_literal | Literal malformed or not representable in its type | +| E0003 | parse.duplicate_name | Function, type, block, field or variant name defined twice | +| E0004 | parse.unknown_name | Unknown opcode, type, function, field or variant | +| E0005 | module.unsupported_version | AIR format or language version not implemented | +| E0006 | module.unsupported_feature | Required feature or reserved type not implemented | + ## E1xxx — Types and values | Code | Kind | Meaning | |---|---|---| | E1001 | type.mismatch | Operand/result type mismatch | | E1002 | type.invalid_cast | Cast not permitted by safe semantics | +| E1003 | type.recursive | Aggregate type contains itself by value | | E1010 | init.read_uninitialized | Read from uninitialized storage | ## E2xxx — Memory and ownership @@ -59,3 +71,17 @@ Draft registry. Codes are stable once released in a tagged compiler version. |---|---|---| | E6001 | unsafe.required | Operation requires explicit unsafe boundary | | E6101 | abi.unaligned_reference | Normal reference requested from insufficiently aligned storage | + +## T0xxx — Runtime traps + +Reported in trap records (spec 01 §6), not by the verifier. + +| Code | Kind | Meaning | +|---|---|---| +| T0001 | trap.explicit | `trap` instruction executed | +| T0002 | trap.assert | Assertion failed | +| T0003 | trap.overflow | Checked arithmetic result not representable | +| T0004 | trap.division_by_zero | Division or remainder by zero | +| T0005 | trap.shift_out_of_range | Shift amount negative or not less than bit width | +| T0006 | trap.cast_out_of_range | Checked cast value not representable in target type | +| T0007 | trap.call_depth | Call depth limit (1 024 frames) exceeded | diff --git a/docs/spec/01-language-overview.md b/docs/spec/01-language-overview.md index a48fb04..6bc6e08 100644 --- a/docs/spec/01-language-overview.md +++ b/docs/spec/01-language-overview.md @@ -88,6 +88,8 @@ Common trap sources: Safe programs SHOULD prefer `Result` for expected failures. +Every trap has a stable code in the `T0xxx` range of [`../reference/error-codes.md`](../reference/error-codes.md). A trap terminates the program; in format version 0 there is no way to observe a trap from inside the program. The implementation reports a trap record containing the code, kind, function, block and the zero-based index of the trapping instruction within its block. Trap records are deterministic: the same module and inputs produce the same record. + ## 7. Generics Aji supports monomorphized generics. diff --git a/docs/spec/02-types-and-values.md b/docs/spec/02-types-and-values.md index d075802..2c84624 100644 --- a/docs/spec/02-types-and-values.md +++ b/docs/spec/02-types-and-values.md @@ -50,6 +50,16 @@ checked_add(a, b) // Option Release/debug modes MUST NOT change these semantics. +### 2.1 Edge cases + +- Division and remainder truncate toward zero; the remainder has the sign of the dividend. +- Division or remainder by zero traps (`T0004`). Signed `MIN / -1` and `MIN % -1` trap as overflow (`T0003`). +- `shl` and `shr` take a shift amount of the same type as the shifted value. An amount that is negative or not less than the bit width traps (`T0005`). `shl` discards bits shifted out; `shr` is arithmetic for signed types and logical for unsigned types. +- There are no implicit conversions. Explicit integer casts: + - `widen`: only between types where every source value is representable in the target (unsigned to wider unsigned or wider signed, signed to wider signed); anything else is rejected statically (`E1002`). `usize` and `isize` are never valid `widen` operands or targets, so verification stays independent of the target; use `checked`. + - `checked`: converts the numeric value; traps (`T0006`) if it is not representable in the target type. + - `wrap`: takes the two's-complement bit pattern modulo 2^N of the target width. + ## 3. Composite types ```aji diff --git a/docs/spec/07-air.md b/docs/spec/07-air.md index 880dedf..d75be2f 100644 --- a/docs/spec/07-air.md +++ b/docs/spec/07-air.md @@ -182,3 +182,49 @@ Every binary must encode version and required feature bits. Native code must not be produced from unverified safe AIR. Unsafe AIR modules are allowed only through explicit trusted/unsafe boundaries and must appear in the unsafe dependency report. + +## 8. Text AIR, format version 0 + +The grammar is [`../reference/air-text.ebnf`](../reference/air-text.ebnf). Instruction semantics are in [`07a-air-instructions.md`](07a-air-instructions.md). + +### 8.1 Module header + +Every text module MUST begin with: + +```text +module +air 0 +lang 0.1 +features [] +``` + +An implementation MUST reject a module whose `air` format version or `lang` version it does not implement (`E0005`), and a module that lists a feature it does not implement (`E0006`). Format version 0 defines no features. + +### 8.2 Functions and blocks + +- A function body is a non-empty sequence of blocks. The first block is the entry block; it MUST NOT declare parameters. Function parameters are in scope in the entry block and every block it dominates. +- Every block MUST contain at least one instruction, MUST end with exactly one terminator, and MUST NOT contain a terminator before its last instruction (`E5002`). +- A branch target MUST name a block of the same function and pass exactly as many arguments as the block declares parameters (`E5002`). Argument binding is simultaneous: all arguments are read before any parameter is written. +- Every `%name` MUST be defined exactly once per function, as a function parameter, a block parameter or an instruction result (`E5001`). Every use MUST be dominated by its definition (`E5001`); a use in the same block MUST come after the defining instruction. Uses in blocks unreachable from the entry block are only checked within their own block. +- Function and type names MUST be unique within a module, and block labels within a function (`E0003`). Field names MUST be unique within a struct and variant names within an enum (`E0003`). + +### 8.3 Types + +- Integer types, `bool`, `void` and `never` are built in. `usize`/`isize` are distinct from all fixed-width types; their width comes from the target description (spec 09 §9). +- `type @T = struct { … }` and `type @T = enum { … }` declare nominal aggregate types. An aggregate MUST NOT contain itself by value, directly or through other aggregates (`E1003`). +- In format version 0 every value is copyable; ownership categories arrive with format version 1 (Phase 1). +- `void` is only valid as a function return type. A `void` function returns with `ret` without operand; a call to it MUST NOT bind a result. A `never` function MUST NOT contain `ret`. + +### 8.4 Reserved + +`f32` and `f64` are reserved until floating-point determinism is specified (open question Q-016). A module that uses them MUST be rejected with `E0006`. + +### 8.5 Canonical form + +The canonical serialization of a module is: the four header lines; one blank line; type declarations in declaration order, one per line; for each function, a blank line, the signature line, the `effects` line, then each block label at column 0 followed by its instructions indented by four spaces. Separators are `", "` between list items and single spaces elsewhere. Comments are not preserved. Value, block, function and type names are preserved. + +Serializing a parsed module and parsing the result MUST yield an equal module. + +### 8.6 Diagnostic order + +Verification stops after the first stage that reports an error, in this order: parsing and name resolution, resource limits, CFG structure, SSA, types. Within a stage, diagnostics are ordered by source position. The result is therefore deterministic for a given input. diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md new file mode 100644 index 0000000..7d9ffd1 --- /dev/null +++ b/docs/spec/07a-air-instructions.md @@ -0,0 +1,183 @@ +# 07a. AIR Instruction Contracts + +Normative. Each instruction lists the fields required by spec 07 §4. Syntax is in [`../reference/air-text.ebnf`](../reference/air-text.ebnf). + +This file covers format version 0 (Phase 0). Later phases add instructions here before implementing them. + +## Common contract for format version 0 + +All format-version-0 instructions operate on copyable values only. Unless an entry says otherwise: + +| Field | Value | +|---|---| +| Ownership transition | none; operands remain available | +| Borrow transition | none | +| Memory reads/writes | none | +| Synchronization | none | +| Effects required | none | +| Capabilities required | none | +| Traps | none | + +Notation: `T` is the type suffix of the opcode; `I` ranges over integer types; `type(%x)` is the type of value `%x`. "Rejects with E1001" means the verifier reports `type.mismatch` at the instruction. + +## Values + +### `const.T lit` + +- Operands: an integer literal (`T` ∈ `I`) or `true`/`false` (`T` = `bool`). +- Result: `T`. +- Verifier: the literal MUST be representable in `T`, otherwise `E0002`. +- Interpreter: produces the literal value. + +### `copy %a` + +- Operands: any value. +- Result: `type(%a)`. +- Interpreter: produces a value equal to `%a`. + +## Integer arithmetic + +### `add|sub|mul.checked.I %a, %b` + +- Operands: `type(%a) = type(%b) = I`, otherwise `E1001`. +- Result: `I`. +- Traps: `T0003` if the mathematical result is not representable in `I`. +- Interpreter: mathematical result. + +### `add|sub|mul.wrap.I %a, %b` + +- Operands and result as above. No traps. +- Interpreter: mathematical result modulo 2^N, reinterpreted in `I`. + +### `div|rem.checked.I %a, %b` + +- Operands and result as above. +- Traps: `T0004` if `%b = 0`; `T0003` for signed `MIN` divided by `-1`. +- Interpreter: truncating division; remainder has the sign of the dividend (spec 02 §2.1). + +## Bitwise + +### `and|or|xor.T %a, %b` + +- Operands: `T` ∈ `I ∪ {bool}`; both operands of type `T`, otherwise `E1001`. +- Result: `T`. +- Interpreter: bitwise operation (logical for `bool`). + +### `shl|shr.I %a, %b` + +- Operands: both of type `I`, otherwise `E1001`. +- Result: `I`. +- Traps: `T0005` if `%b < 0` or `%b ≥ N`. +- Interpreter: spec 02 §2.1. + +## Comparisons + +### `eq|ne.T %a, %b` + +- Operands: `T` ∈ `I ∪ {bool}`; both of type `T`, otherwise `E1001`. +- Result: `bool`. + +### `lt|le|gt|ge.I %a, %b` + +- Operands: both of type `I`, otherwise `E1001`. +- Result: `bool`. Signed comparison for signed `I`, unsigned otherwise. + +## Casts + +### `cast.widen.I %a` + +- Operands: `type(%a)` ∈ `I`; the conversion MUST be lossless for every value (spec 02 §2.1), otherwise `E1002`. +- Result: `I`. + +### `cast.checked.I %a` + +- Operands: `type(%a)` ∈ `I`, otherwise `E1002`. +- Result: `I`. +- Traps: `T0006` if the value of `%a` is not representable in `I`. + +### `cast.wrap.I %a` + +- Operands: `type(%a)` ∈ `I`, otherwise `E1002`. +- Result: `I`, the low N bits of the two's-complement representation of `%a`. + +## Assertions + +### `assert %c` + +- Operands: `type(%c) = bool`, otherwise `E1001`. +- Result: none. +- Traps: `T0002` if `%c` is false. + +## Aggregates + +### `struct.make @S(%f1, …, %fn)` + +- Operands: `@S` is a struct type with exactly n fields (`E1001` otherwise); `type(%fi)` equals the type of field i. +- Result: `@S`. + +### `struct.get @S.f, %s` + +- Operands: `@S` is a struct type with a field `f` (`E0004` otherwise); `type(%s) = @S` (`E1001` otherwise). +- Result: the type of field `f`. + +### `enum.make @E.V(%p1, …, %pn)` + +- Operands: `@E` is an enum type with a variant `V` (`E0004` otherwise) whose payload has exactly n types; `type(%pi)` equals payload type i (`E1001` otherwise). +- Result: `@E`. + +## Calls + +### `call @f(%a1, …, %an)` + +- Operands: `@f` is a function of the module (`E0004` otherwise) with n parameters; `type(%ai)` equals parameter type i (`E1001` otherwise). +- Result: the return type of `@f`. A result MUST be bound unless the return type is `void` or `never`, and MUST NOT be bound when it is `void` (`E1001`). +- Effects: the callee's effect set (checked from Phase 2). +- Traps: whatever the callee traps; `T0007` if the call would exceed the call-depth limit of 1 024 active frames. +- Interpreter: evaluates the callee with fresh parameter bindings; returns its result. + +## Terminators + +A terminator ends a block (spec 07 §8.2). Terminators bind no result. + +### `br @b(%a1, …, %an)` + +- Operands: `@b` has n parameters (`E5002`); `type(%ai)` equals parameter type i (`E1001`). +- Interpreter: binds the arguments simultaneously and continues at `@b`. + +### `cbr %c, @t(…), @f(…)` + +- Operands: `type(%c) = bool` (`E1001`); both targets as for `br`. +- Interpreter: continues at `@t` if `%c` is true, otherwise at `@f`. + +### `switch.I %v, k1 -> @b1(…), …, default -> @d(…)` + +- Operands: `type(%v) = I` (`E1001`); each `ki` representable in `I` (`E0002`); case values pairwise distinct (`E5002`); targets as for `br`. +- Interpreter: continues at the case whose value equals `%v`, otherwise at `default`. + +### `enum.switch @E %v, V1 -> @b1, …[, default -> @d(…)]` + +- Operands: `type(%v) = @E` (`E1001`); each `Vi` is a variant of `@E` (`E0004`) and appears at most once (`E5002`); every variant appears unless `default` is present (`E5002`); the parameters of `@bi` MUST equal the payload types of `Vi` in number (`E5002`) and type (`E1001`). +- Interpreter: continues at the arm for the active variant, binding its payload to the target block's parameters; otherwise at `default`. + +### `ret [%v]` + +- Operands: `type(%v)` equals the function's return type (`E1001`). Without operand only in `void` functions (`E1001`). Not allowed in `never` functions (`E1001`). +- Interpreter: returns from the function. + +### `trap` + +- Traps: `T0001`, always. + +## Run result + +`aji run` executes the function `@main`, which MUST take no parameters. On return it reports `{"status":"returned","value":V}` where `V` renders the returned value as JSON: + +| Type | Rendering | +|---|---| +| integer | decimal number | +| `bool` | `true` / `false` | +| `void` | `null` | +| struct | object of fields in declaration order | +| enum | `{"variant":"Name","payload":[…]}` | + +On a trap it reports `{"status":"trapped", "code":…, "kind":…, "function":…, "block":…, "inst":…}` (spec 01 §6). diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md index c981182..94ffd7b 100644 --- a/docs/spec/08-verifier.md +++ b/docs/spec/08-verifier.md @@ -85,7 +85,21 @@ It may justify elimination of later runtime checks. Verifier algorithms must have deterministic resource budgets. -If verification exceeds configured/spec-defined complexity bounds, the verifier emits a stable failure rather than silently weakening checks. +If verification exceeds the spec-defined complexity bounds, the verifier emits a stable failure (`E5101`) rather than silently weakening checks. + +Bounds are fixed by this specification, not configurable: a configurable bound would let a flag change which programs are accepted. Format version 0 defines: + +| Limit | Value | +|---|---| +| functions per module | 65 536 | +| type declarations per module | 65 536 | +| fields per struct, variants per enum, payload values per variant | 256 | +| parameters per function or block, arguments per call or branch | 64 | +| blocks per function | 16 384 | +| instructions per function | 262 144 | +| cases per `switch` | 4 096 | + +The `E5101` diagnostic carries the fields `limit` (name of the limit), `max` and `found`. ## 8. Contracts diff --git a/docs/spec/09-runtime-and-abi.md b/docs/spec/09-runtime-and-abi.md index 7a2c2e0..846133d 100644 --- a/docs/spec/09-runtime-and-abi.md +++ b/docs/spec/09-runtime-and-abi.md @@ -70,3 +70,15 @@ Signal and interrupt handlers use restricted capabilities/effects. Allocation, o The initial native backend should lower AIR to LLVM IR. A custom native backend is deferred until AIR and verifier semantics stabilize. + +## 9. Target description + +Every execution, interpreted or native, runs against an explicit target description. Target-dependent semantics come only from it. + +Format version 0 defines one field: + +| Field | Meaning | +|---|---| +| `pointer_bits` | width of `usize`/`isize` in bits: 32 or 64 | + +The reference interpreter uses the target `air64` (`pointer_bits = 64`) unless a module declares target requirements (a later format version). diff --git a/docs/spec/README.md b/docs/spec/README.md index cb7e99d..b0c9962 100644 --- a/docs/spec/README.md +++ b/docs/spec/README.md @@ -15,7 +15,8 @@ The specification is split by semantic domain. Rationale for major decisions liv | [04-concurrency-and-atomics.md](04-concurrency-and-atomics.md) | Normative draft | Tasks, synchronization, memory model, atomics | | [05-effects-and-capabilities.md](05-effects-and-capabilities.md) | Normative draft | Authority and effect tracking | | [06-resources-and-errors.md](06-resources-and-errors.md) | Normative draft | Linear resources and error handling | -| [07-air.md](07-air.md) | Normative draft | Canonical IR | +| [07-air.md](07-air.md) | Normative draft | Canonical IR, text format | +| [07a-air-instructions.md](07a-air-instructions.md) | Normative draft | Per-instruction contracts | | [08-verifier.md](08-verifier.md) | Normative draft | Verification rules | | [09-runtime-and-abi.md](09-runtime-and-abi.md) | Normative draft | Runtime, FFI, MMIO/DMA | | [10-diagnostics-and-agent-protocol.md](10-diagnostics-and-agent-protocol.md) | Normative draft | Stable diagnostics and `ajid` |