From 48bb50724fcf542e381eca3908f6c75c83dbcd6d Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 13:10:08 +0300 Subject: [PATCH] spec: accept RFC 0005 and integrate Phase 1 memory model (P1-1, P1-2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RFC 0005 Accepted (revision 2) - spec 07 §8.8 types and syntax; spec 07a contracts for features ownership and arrays; spec 08 §11-§14 borrows, facts, initialization, stage order; spec 03 frame storage, second-class borrows, static region generations - grammar: from-returns, multi-result, new types and opcodes - feature registry: ownership and arrays published; heap added and regions moved to Phase 2; borrow_joins reserved and unscheduled - codes E2105-E2108, T0008 - Q-009, Q-010 resolved; Phase 1 and Phase 2 plans updated; Own test moved to phase 2 --- docs/design/open-questions.md | 8 +- docs/plan/README.md | 15 +-- docs/plan/phase-1-ownership-and-memory.md | 42 ++++---- .../phase-2-effects-capabilities-resources.md | 6 +- docs/reference/air-features.md | 10 +- docs/reference/air-text.ebnf | 34 ++++++- docs/reference/error-codes.md | 5 + .../rfcs/0005-frame-storage-borrows-arrays.md | 3 +- docs/spec/03-memory-model.md | 8 +- docs/spec/07-air.md | 21 ++++ docs/spec/07a-air-instructions.md | 47 ++++++++- docs/spec/08-verifier.md | 97 +++++++++++++++++++ src/air/features.zig | 19 ++-- src/diag.zig | 5 + .../reject/use_after_move.air | 4 +- 15 files changed, 269 insertions(+), 55 deletions(-) rename tests/conformance/{phase1 => phase2}/reject/use_after_move.air (79%) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 4b73eeb..9087ee3 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -14,8 +14,8 @@ Status values: `open`, `resolved`. | 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-009 | resolved | P1 | Borrow lifetimes in AIR | +| Q-010 | resolved | P1 | Region generation checks: static, dynamic, or both | | Q-011 | open | P2 | Effect hierarchy and discharge | | Q-012 | open | P2 | Capability representation and host instantiation | | Q-013 | open | P3 | Deterministic `select` rule and scheduler seed | @@ -82,10 +82,14 @@ Phase 0's exit criterion runs AIR `hello`, but `io.stdout_write` needs `cap`, `ref`/`mut`, slices, initialization tracking, regions with generations, bounds and range facts. +**Goal:** safe single-threaded memory without a heap: frame storage, initialization tracking, second-class borrows, arrays and slices, bounds checks and bounds proofs. Features `ownership` and `arrays` (RFC 0005). -**Exit criterion:** the file-copy core (buffer handling, regions, slices) is implemented in AIR, and the verifier rejects representative use-after-move, aliasing and out-of-bounds cases. +**Exit criterion:** the file-copy core — copying between slices of a local buffer in chunks — runs in the interpreter, and the verifier rejects representative aliasing (E2101), dangling and escaping borrows (E2102, E2108), uninitialized reads (E1010), unended borrows (E2105) and unproven element access (E2103). -**Spec inputs:** spec 02 §4–5, 03 §1–11, 08 §3–6, 13 §2. RFC 0001 memory sections are proposed for acceptance (owner decision; island sections may wait until P4); acceptance integrates them into the spec. +**Spec inputs:** spec 03 §4, §6; spec 07 §8.8; spec 07a (features `ownership`, `arrays`); spec 08 §11–§14. Decision record: RFC 0005 (Accepted). -**Blocking questions:** Q-009 borrow lifetimes in AIR, Q-010 region generation checks. +**Moved to Phase 2 (owner decision):** `Own`, heap allocation and regions, together with E2001, E2002 and E2104 — they need allocation authority (`cap`). ## 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`; fixed arrays `[T; N]` with checked indexing (moved from P0); `Uninit`; `Option>`. +In: `local`, `ref`, `mut`, `[T; N]`, `slice`, `slice_mut`; `local.alloc/store/zero/load`, `borrow.ref/mut/field/end`, `load`, `store`, `array.splat`, `borrow.index[.proven]`, `slice.make/len/sub/split/copy`, `guard`; `from` returns; multi-result syntax; feature gating (`feature_not_declared`). -Out: islands, `Arc`, `Pin`, raw addresses (beyond rejecting them in safe code). +Out: heap, regions, move-only values, borrow-typed block parameters (`borrow_joins`). ## Tasks | ID | Status | Task | Depends | Output | Done when | |---|---|---|---|---|---| -| P1-1 | todo | Resolve Q-009 and Q-010; propose RFC 0001 memory sections for acceptance | — | spec 03, 07, RFC 0001 | questions resolved; RFC ready for the owner, rules integrated on acceptance | -| P1-2 | todo | Contract tables for Phase 1 opcodes, grouped by feature (`arrays`, `ownership`, `regions`) | P1-1 | spec 07a | every in-scope opcode has all spec 07 §4 fields, including verifier transfer function, and names its feature | -| P1-2a | todo | Feature gating in the parser: constructs of an undeclared feature report `E0006` reason `feature_not_declared`; publish `arrays`, `ownership`, `regions` in the registry and add them to `supported` once implemented | P1-2 | `src/air/features.zig`, `src/air/parse.zig`, `reference/air-features.md` | reject test per feature for `feature_not_declared` and `missing_dependency`; `aji features` lists the three | -| P1-3 | todo | Interpreter memory: allocations, provenance, bounds, region generations, uninitialized bytes | P1-2 | `src/interp/memory.zig` | unit tests: every access checks provenance; reading uninitialized bytes is detected in interpreter debug checks | -| P1-4 | todo | Initialization verifier | P1-2 | `src/verifier/init.zig` | E1010 accept/reject (scalar, struct field, array prefix) | -| P1-5 | todo | Ownership state machine | P1-2 | `src/verifier/ownership.zig` | E2001, E2002 accept/reject, including across branches and loops | -| P1-6 | todo | Borrow/alias verifier | P1-5 | `src/verifier/borrow.zig` | E2101, E2102 accept/reject; borrow ending on all paths | -| P1-7 | todo | Region lifetime and generation verifier | P1-6 | `src/verifier/region.zig` | E2104 accept/reject; reset with live reference rejected (spec 03 §8.2) | -| P1-8 | todo | Bounds and range facts; path sensitivity; `guard` | P1-6 | `src/verifier/bounds.zig` | E2103 accept/reject; check elimination after `if i < len` and after `guard` | -| P1-9 | todo | Slices and disjoint partitioning facts (`split_mut`) | P1-8 | verifier + interpreter | two disjoint `slice_mut` usable simultaneously; overlapping ones rejected with E2101 | -| P1-10 | todo | Structured diagnostic fields and repair candidates for E2xxx | P1-5…P1-9 | `src/diag.zig`, spec 10 | snapshot tests on full JSON for each E2xxx code, matching the spec 10 §2 example shape | -| P1-11 | todo | Report: remaining runtime checks and eliminated bounds checks | P1-8 | `src/report/checks.zig` | `aji check --report` lists checks per function, deterministic order | -| P1-12 | todo | Phase exit review | all | `tests/programs/file-copy-core/` | file-copy core runs; negative corpus for use-after-move, overlapping borrows, region reset with live reference, prior generation use, OOB all pass | - -## Conformance tests to add - -Negative corpus entries from `conformance-suite.md` owned by this phase: use after move, overlapping mutable borrows, region reset with live reference, use of prior region generation. Plus E1010, E2002, E2102, E2103. +| P1-1 | done | Resolve Q-009 and Q-010; RFC 0005 accepted | — | RFC 0005 | owner accepted revision 2 | +| P1-2 | done | Integrate RFC 0005 into the spec and registries | P1-1 | spec 03/07/07a/08, reference files | features `ownership`, `arrays` published | +| P1-3 | todo | Data model, parser and printer: new types, `from`, multi-result, opcodes; feature gating | P1-2 | `src/air/` | round-trip fuzz covers new forms; `feature_not_declared` tests | +| P1-4 | todo | Type rules: second-class rule, borrow/slice typing, zeroable types, `from` mode | P1-3 | `src/verifier/types.zig` | E1001 accept/reject pairs for each rule | +| P1-5 | todo | Frame rules: `local.alloc` only in entry (E5002), frame size limit (E5101) | P1-3 | `cfg.zig`, `budget.zig` | reject tests for both | +| P1-6 | todo | Initialization verifier | P1-4 | `src/verifier/init.zig` | E1010 accept/reject, including joins | +| P1-7 | todo | Borrow verifier | P1-6 | `src/verifier/borrow.zig` | E2101, E2102, E2105–E2108 accept/reject; path linearity across branches; join state equality | +| P1-8 | todo | Bounds facts for `borrow.index.proven` | P1-7 | `src/verifier/bounds.zig` | every row of the fact table accepted; `le i n` and other non-facts rejected (E2103) | +| P1-9 | todo | Interpreter: frame storage, borrows, slices, bounds traps (T0008) | P1-4 | `src/interp/` | run tests for every instruction; T0008 for each checked operation | +| P1-10 | todo | `aji features` lists `arrays`, `ownership`; conformance corpus for Phase 1 | P1-7…P1-9 | `tests/conformance/phase1/` | accept/reject/run tests for every new code and trap | +| P1-11 | todo | Phase exit review | all | plan status | exit criterion passes | diff --git a/docs/plan/phase-2-effects-capabilities-resources.md b/docs/plan/phase-2-effects-capabilities-resources.md index 133107d..29c86f2 100644 --- a/docs/plan/phase-2-effects-capabilities-resources.md +++ b/docs/plan/phase-2-effects-capabilities-resources.md @@ -2,7 +2,7 @@ Non-normative. Part of the [implementation plan](README.md). -**Goal:** authority and external resources become verifiable: effect sets, unforgeable capabilities with narrowing, linear resources with typestate, capability-gated runtime intrinsics, unsafe boundaries. +**Goal:** authority, allocation and external resources become verifiable: heap allocation (`Own`) and regions (moved here from Phase 1, RFC 0005), effect sets, unforgeable capabilities with narrowing, linear resources with typestate, capability-gated runtime intrinsics, unsafe boundaries. **Exit criterion:** safe file-copy and a basic (single-task) TCP echo run in the interpreter. @@ -23,6 +23,10 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7). | P2-1 | todo | Resolve Q-011, Q-012, Q-018 | — | spec 05, 07, 10 | questions resolved; runtime record format defined | | P2-2 | todo | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) | | P2-2a | todo | Publish features `effects` and `capabilities` (spec text, registry status, `supported`); effect checking applies to modules declaring `effects` | P2-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests; baseline modules unaffected | +| P2-2b | todo | Specify and publish `heap` (`Own`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published | +| P2-2c | todo | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) | +| P2-2d | todo | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject | +| P2-2e | todo | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer | | P2-3 | todo | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present | | P2-4 | todo | Effect verifier | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees | | P2-5 | todo | Capability verifier: unforgeability, narrowing, transfer rules | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject | diff --git a/docs/reference/air-features.md b/docs/reference/air-features.md index c2b4ebf..bd1f130 100644 --- a/docs/reference/air-features.md +++ b/docs/reference/air-features.md @@ -30,14 +30,16 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It | Feature | Status | Phase | Depends on | Semantic block | |---|---|---|---|---| -| `arrays` | reserved | 1 | — | fixed-size arrays `[T; N]`, checked indexing | +| `arrays` | published | 1 | `ownership` | `[T; N]`, `slice`, `slice_mut`, `array.splat`, `borrow.index[.proven]`, `slice.*`, `guard`, bounds facts (spec 07a, spec 08 §12) | | `atomics` | reserved | 5 | `ownership` | atomic types, the five orderings, fences, `atomic.*` instructions | | `capabilities` | reserved | 2 | `effects`, `ownership` | `cap<…>` values, narrowing, delegation, capability-gated intrinsics | +| `borrow_joins` | reserved | — | `ownership` | borrow-typed block parameters (spec 08 §11.6); unscheduled | | `channels` | reserved | 3 | `ownership` | bounded and rendezvous channels with ownership transfer | | `effects` | reserved | 2 | — | effect checking of `effects [...]` lists (E3101) | -| `islands` | reserved | 4 | `ownership`, `regions` | `Island`, `iref`, transfer, freeze, `Frozen` | -| `ownership` | reserved | 1 | — | `Own`, `move`, `ref`/`mut` borrows, slices, initialization, linearity | -| `regions` | reserved | 1 | `ownership` | `Region`, generations, region allocation, reset and destroy | +| `heap` | reserved | 2 | `capabilities`, `effects`, `ownership` | `Own`, `own.alloc`, `own.free`, move-only values | +| `islands` | reserved | 4 | `capabilities`, `effects`, `ownership`, `regions` | `Island`, `iref`, transfer, freeze, `Frozen` | +| `ownership` | published | 1 | — | frame storage `local`, second-class borrows `ref`/`mut`, `from` returns, initialization (spec 07 §8.8, spec 07a, spec 08 §11, §13) | +| `regions` | reserved | 2 | `capabilities`, `effects`, `ownership` | `Region`, static generations, region allocation, reset and destroy | | `sync` | reserved | 3 | `ownership` | `Mutex`, `RwLock`, linear guards | | `tasks` | reserved | 3 | `ownership` | structured task scopes, spawn/join/cancel, `Send`/`Share` | diff --git a/docs/reference/air-text.ebnf b/docs/reference/air-text.ebnf index 3059408..75dcf92 100644 --- a/docs/reference/air-text.ebnf +++ b/docs/reference/air-text.ebnf @@ -35,7 +35,7 @@ field = ident ":" type ; enum_type = "enum" "{" variant { "," variant } [ "," ] "}" ; variant = ident [ "(" [ type { "," type } ] ")" ] ; -function = "fn" global "(" [ param_list ] ")" "->" type NL +function = "fn" global "(" [ param_list ] ")" "->" type [ "from" local ] NL (* from: feature ownership *) "effects" "[" [ path_list ] "]" NL block { block } ; param_list = param { "," param } ; @@ -44,7 +44,8 @@ param = local ":" type ; block = ident [ "(" [ param_list ] ")" ] ":" NL { instruction NL } ; (* The first block is the entry block and takes no parameters. *) -instruction = [ local "=" ] operation ; +instruction = [ local { "," local } "=" ] operation ; + (* More than one result only for instructions specified with several results (slice.split). *) operation = "const." int_type int_lit | "const.bool" ( "true" | "false" ) @@ -56,8 +57,32 @@ operation = "const." int_type int_lit | "struct.get" global "." ident "," local | "enum.make" global "." ident "(" [ local_list ] ")" | "call" global "(" [ local_list ] ")" + | ownership_op + | arrays_op | terminator ; +(* Feature ownership (spec 07a). *) +ownership_op = "local.alloc" type + | "local.store" local "," local + | "local.zero" local + | "local.load" local + | "borrow.ref" local + | "borrow.mut" local + | "borrow.field" global "." ident "," local + | "borrow.end" local + | "load" local + | "store" local "," local ; + +(* Feature arrays (spec 07a). *) +arrays_op = "array.splat" type local + | ( "borrow.index" | "borrow.index.proven" ) local "," local + | "slice.make" local + | "slice.len" local + | "slice.sub" local "," local "," local + | "slice.split" local "," local + | "slice.copy" local "," local + | "guard" local ; + arith_op = ( "add" | "sub" | "mul" ) "." ( "checked" | "wrap" ) "." int_type | ( "div" | "rem" ) ".checked." int_type | ( "and" | "or" | "xor" ) "." ( int_type | "bool" ) @@ -76,7 +101,10 @@ terminator = "br" target enum_arm = ident "->" global ; (* target block receives the variant payload as parameters *) target = global "(" [ local_list ] ")" ; -type = int_type | "bool" | "void" | "never" | global ; +type = int_type | "bool" | "void" | "never" | global + | ( "local" | "ref" | "mut" ) "<" type ">" (* feature ownership *) + | "[" type ";" int_lit "]" (* feature arrays *) + | ( "slice" | "slice_mut" ) "<" type ">" ; (* feature arrays *) 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. *) diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md index 28f59d8..a2c9673 100644 --- a/docs/reference/error-codes.md +++ b/docs/reference/error-codes.md @@ -33,6 +33,10 @@ Draft registry. Codes are stable once released in a tagged compiler version. | E2103 | memory.out_of_bounds | Access not proven in bounds | | E2104 | memory.region_generation | Reference belongs to invalidated region generation | | E2110 | island.escape | Island-internal reference escapes island | +| E2105 | borrow.not_ended | Owned borrow live at `ret`, or borrow state differs between edges into a block | +| E2106 | borrow.use_after_end | Borrow used or ended after it was ended | +| E2107 | borrow.not_owned | Lent (parameter) borrow ended by the callee | +| E2108 | borrow.escapes_frame | Borrow derived from frame storage returned from its function | | E2111 | island.foreign_mutable_edge | Island graph points to forbidden foreign mutable storage | ## E3xxx — Resources/capabilities/effects @@ -85,3 +89,4 @@ Reported in trap records (spec 01 §6), not by the verifier. | 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 | +| T0008 | trap.out_of_bounds | Runtime bounds check failed | diff --git a/docs/rfcs/0005-frame-storage-borrows-arrays.md b/docs/rfcs/0005-frame-storage-borrows-arrays.md index 22f1751..fe83579 100644 --- a/docs/rfcs/0005-frame-storage-borrows-arrays.md +++ b/docs/rfcs/0005-frame-storage-borrows-arrays.md @@ -1,8 +1,9 @@ # RFC 0005: Frame Storage, Second-Class Borrows and Arrays -Status: Proposed (revision 2: owner review items 1–5 applied) +Status: Accepted (revision 2, after owner review items 1–5) Scope: AIR format 0, features `ownership` and `arrays` Language version: 0.1 +Integrated into: spec 03 §6, §4, §8.1; spec 07 §8.8; spec 07a; spec 08 §11–§14; `reference/air-text.ebnf`, `reference/air-features.md`, `reference/error-codes.md` Supersedes: — Decisions already taken by the language owner (2026-10-04) and recorded here: diff --git a/docs/spec/03-memory-model.md b/docs/spec/03-memory-model.md index 174c055..07a0ebd 100644 --- a/docs/spec/03-memory-model.md +++ b/docs/spec/03-memory-model.md @@ -58,6 +58,8 @@ Conceptually: fn first<'a, T>(values: slice<'a, T>) -> Option> ``` +In AIR, borrows are second-class (spec 07 §8.8): they live only in SSA values and call arguments, never in aggregates, and a function returns a borrow only with an explicit `from %param` naming the borrow parameter it derives from (spec 08 §11.3). Every borrow created in a function is ended explicitly on every normal path (`borrow.end`). Source-level lifetimes lower to this form; source programs that need more are rejected by the frontend. + ## 5. Provenance Every safe reference has logical provenance including: @@ -78,6 +80,8 @@ Normal locals live in the current activation frame. Their references cannot escape the frame unless the language proves that the target execution context completes before the frame ends, as with structured child tasks. +In AIR, frame storage is `local.alloc`, permitted only in a function's entry block so the frame size is known before execution and bounded (spec 08 §11.5). A borrow derived from frame storage never leaves its call (`E2108`, spec 08 §11.3). + ## 7. Own `Own` is a move-only handle to an individually allocated object. @@ -123,9 +127,7 @@ region.destroy(move r); A reset logically increments the region generation. -Any borrow or reference associated with a prior generation becomes invalid. - -Optimized builds may remove generation checks when statically proven unnecessary. +Any borrow or reference associated with a prior generation becomes invalid. Generations are checked statically only: a region cannot be reset or destroyed while a borrow derived from it is live, and use of a borrow from a prior generation is rejected (`E2104`). Safe code performs no runtime generation checks. Cyclic or arena-style graphs use `Island` or indices (§14). (Decision Q-010; specified with the `regions` feature in Phase 2.) ### 8.2 Reset precondition diff --git a/docs/spec/07-air.md b/docs/spec/07-air.md index 1a19d02..453254a 100644 --- a/docs/spec/07-air.md +++ b/docs/spec/07-air.md @@ -253,3 +253,24 @@ A change is permitted under `air 0` only if all of the following hold: A published feature's semantics are immutable. Extending a feature with new semantics is not permitted; register a new feature instead. Any other change to format 0 — a different meaning, typing rule, trap behavior, diagnostic code or canonical spelling for an existing construct — requires a new format version (`air 1`) introduced by an RFC. An implementation that supports several format versions selects the semantics by the module's `air` line; it never mixes them. + +### 8.8 Types and syntax of the features `ownership` and `arrays` + +Feature membership: `local`, `ref`, `mut` and the `from` clause belong to `ownership`; `[T; N]`, `slice`, `slice_mut` and multi-result binding belong to `arrays`. Using them without declaring the feature is `E0006` reason `feature_not_declared`. + +| Type | Class | Notes | +|---|---|---| +| `local` | storage | frame storage holding a `T`; only an operand of `local.*` and `borrow.*` | +| `ref` | borrow | shared borrow | +| `mut` | borrow | exclusive borrow | +| `[T; N]` | value | array of `N` values, `1 ≤ N ≤ 2^32`; copyable when `T` is | +| `slice` | borrow | shared borrow of a contiguous range | +| `slice_mut` | borrow | exclusive borrow of a contiguous range | + +`T` in these types is a value type: not `void`, `never`, a storage type or a borrow type. + +**Second-class rule.** Storage and borrow types MUST NOT appear as struct fields, enum payloads, array elements or the `T` of another storage or borrow type (`E1001`). A storage type MUST NOT appear as a function parameter, return type or block parameter (`E1001`). A borrow type MAY appear as a function parameter and, with `from`, as a return type (spec 08 §11.3). As a block parameter type it requires the reserved feature `borrow_joins` (spec 08 §11.6). + +All value types of format 0 and Phase 1 are copyable. Move-only values arrive with `heap` in Phase 2. + +Syntax additions (reference/air-text.ebnf): `-> type from %param` on function signatures, the type forms above, and `%a, %b = op` for instructions specified with two results (only `slice.split`). diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md index 2af3ecc..de3cf04 100644 --- a/docs/spec/07a-air-instructions.md +++ b/docs/spec/07a-air-instructions.md @@ -2,7 +2,7 @@ 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. +This file covers the format-0 baseline (Phase 0) and the features `ownership` and `arrays` (Phase 1). Later phases add instructions here, grouped by feature, before implementing them. An instruction of a feature is only valid in a module that declares the feature (spec 07 §8.1). ## Common contract for format version 0 @@ -168,6 +168,51 @@ A terminator ends a block (spec 07 §8.2). Terminators bind no result. - Traps: `T0001`, always. +## Feature `ownership` and feature `arrays` + +Types, borrow rules and bounds facts used below: spec 07 §8.8 (types), spec 08 §11 (borrows), spec 08 §12 (facts), spec 08 §13 (initialization). Decision record: RFC 0005. + +Common contract unless stated: no effects, no capabilities, no synchronization. "Owned borrow" means a borrow created in the current function (§5.1). + +### `ownership` + +| Instruction | Operands → result | Verifier | Runtime | +|---|---|---|---| +| `%s = local.alloc T` | → `local` | only in the entry block (`E5002`); storage is uninitialized; counts toward the frame limit (spec 08 §11.5) | allocates frame storage once per call, freed at return | +| `local.store %s, %v` | `local`, `T` | no live borrow of `%s` (`E2101`); initializes `%s` | writes `%v` | +| `local.zero %s` | `local` | `T` zeroable: integers, `bool`, arrays and structs of zeroable types (`E1001`); no live borrow (`E2101`); initializes | writes all-zero value | +| `%v = local.load %s` | `local` → `T` | initialized (`E1010`); no live `mut` borrow of `%s` (`E2101`) | reads | +| `%r = borrow.ref %x` | `local`, `ref`, `mut` → `ref`; `slice`, `slice_mut` → `slice` | spec 08 §11.2; locals must be initialized (`E1010`); child of `%x` unless `%x` is a local | shared view of the same place | +| `%m = borrow.mut %x` | `local`, `mut` → `mut`; `slice_mut` → `slice_mut` | spec 08 §11.2; locals must be initialized (`E1010`); child of `%x` unless `%x` is a local | exclusive view of the same place | +| `%f = borrow.field @S.f, %b` | `ref<@S>`/`mut<@S>` → `ref`/`mut` | child of `%b`; distinct fields are disjoint | reference to the field | +| `borrow.end %b` | owned borrow | no live children (`E2102`); not a parameter (`E2107`); not already ended (`E2106`) | none | +| `%v = load %b` | `ref`/`mut` → `T` | `%b` usable for reading (spec 08 §11.2) | reads | +| `store %b, %v` | `mut`, `T` | `%b` usable for writing (spec 08 §11.2) | writes | + +### `arrays` + +| Instruction | Operands → result | Verifier | Runtime | +|---|---|---|---| +| `%a = array.splat [T; N] %v` | `T` → `[T; N]` | — | every element is `%v` | +| `%e = borrow.index %b, %i` | `ref`/`mut` of `[T; N]`, or `slice`/`slice_mut` of `T`; `usize` → `ref`/`mut` | child of `%b` | traps `T0008` if `%i ≥ length` | +| `%e = borrow.index.proven %b, %i` | as above | `%i < length` proven (spec 08 §12), otherwise `E2103` | no check | +| `%s = slice.make %b` | `ref<[T; N]>`/`mut<[T; N]>` → `slice`/`slice_mut` | child of `%b` | whole array | +| `%n = slice.len %s` | `slice`/`slice_mut` → `usize` | — | length | +| `%t = slice.sub %s, %start, %len` | slice, `usize`, `usize` → same slice type | child of `%s` | traps `T0008` unless `start ≤ slice.len(s)` and `len ≤ slice.len(s) − start` (evaluated without overflow); result covers `[start, start + len)` | +| `%l, %r = slice.split %s, %at` | slice, `usize` → two slices of the same type | two children of `%s`, disjoint | traps `T0008` unless `at ≤ slice.len(s)`; `l` covers `[0, at)`, `r` covers `[at, len)` | +| `slice.copy %dst, %src` | `slice_mut`, `slice`/`slice_mut` | both usable (spec 08 §11.2); overlapping operands are rejected by the aliasing rules (spec 08 §11.2), so this is never a `memmove` | traps `T0008` unless `len(dst) ≥ len(src)`; copies exactly `len(src)` elements into the start of `dst` | +| `guard %c` | `bool` | adds a fact (spec 08 §12) | traps `T0002` if false | + +New trap code: `T0008 trap.out_of_bounds`. + +`slice.make` creates a slice only from an existing borrow of an array, covering exactly that array and inheriting its provenance. No instruction creates a slice from an address and a length. An overlap-safe copy, if ever needed, will be a separate instruction (`slice.move`). + +### Runtime + +- Frame storage is allocated by `local.alloc` and released at return; no code runs at release. +- The interpreter represents a borrow as (storage, path) and a slice as (storage, path, offset, length). It performs no alias or liveness checks at runtime: the verifier guarantees them. Bounds checks run exactly where §4 says. +- Behavior is deterministic; storage addresses are never observable. + ## 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: diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md index 94ffd7b..0e4aaab 100644 --- a/docs/spec/08-verifier.md +++ b/docs/spec/08-verifier.md @@ -131,3 +131,100 @@ The verifier must reject: Every normative verifier rejection has a stable machine-readable code. Diagnostics should include enough structured state for an agent to repair the program without parsing prose. + +## 11. Borrow verification (feature `ownership`) + +Normative rules for frame storage and second-class borrows. Decision record: RFC 0005. + +### 11.1 Owned and lent borrows + +- A borrow created in the function (`borrow.*`, `slice.make`, `slice.sub`, `slice.split`, or the result of a `call` to a function with `from`) is **owned** by the function. +- A borrow-typed function parameter is **lent**: the caller keeps it alive for the whole call. A lent borrow is never ended by the callee (`E2107`) and need not be ended. +- **Path linearity.** On every reachable normal path from the creation of an owned borrow to a `ret`, the borrow MUST be either ended exactly once or transferred to the caller by a valid `ret … from` (§11.3); otherwise `E2105`. The rule is per path, not per instruction text: a borrow may have several `borrow.end` instructions in different branches, as long as each path executes exactly one. +- `trap` ends a path abnormally. Aji has no unwinding, so paths ending in `trap` carry no obligation. +- Using or ending a borrow on a path where it has already been ended is `E2106`. + +### 11.2 Places, overlap and access + +Every borrow has a **root** (a `local` or a lent parameter), a **path** from the root (field names, a slice range, or an element), a **mode** (`ref`/`mut`) and a **parent** (none for borrows taken directly from a local or a parameter). + +- Two paths overlap unless they diverge at different fields of the same struct, or they are the two results of one `slice.split` (and descendants of each). +- Element borrows (`borrow.index`) and sub-slices of the same parent all overlap each other. +- Creating a borrow conflicts with every live borrow whose path overlaps when either is `mut` (`E2101`). +- A borrow with live children is **frozen**: it may still create further children that do not conflict, but it cannot be read, written or ended while a live child conflicts with that use (`E2101`, `E2102` for ending). +- A `ref` borrow is usable for reading; a `mut` borrow is usable for reading and writing, in both cases only if not frozen by a conflicting child. +- There is no implicit conversion between borrow types: a `mut`/`slice_mut` borrow is passed where a shared one is expected only through an explicit `borrow.ref` (`E1001` otherwise). +- `call`: each borrow argument is lent to the callee for the duration of the call. Arguments are checked as if each were a new borrow of its operand at the call: a `mut` argument conflicts with any other argument that overlaps it (`E2101`). + +### 11.3 Returning a borrow + +`fn @f(…, %p: slice, …) -> ref from %p` declares that the result borrows from the argument passed for `%p`. + +- `from` names a borrow-typed parameter; its mode must allow the result mode (`mut` result needs a `mut`/`slice_mut` parameter) (`E1001`). +- A borrow-typed return without `from` is `E2102`. +- `ret %b` in such a function requires `%b` to be `%p` or a descendant of `%p`. If `%b`'s provenance leads to a `local.alloc` of this function, the return is `E2108` (frame escape); if it leads to another parameter, `E2102`. At `ret`, the only live owned borrows may be `%b` and its owned ancestors, which are transferred to the caller with it; any other live owned borrow is `E2105`. +- Escape through aggregates is impossible by construction: borrow types cannot be fields, payloads or array elements (spec 07 §8.8), so `struct.make`, `enum.make` and returned aggregates never contain a borrow. +- `from` may name only a borrow parameter. Later features may add other escapable sources (for example region-derived borrows in Phase 2); frame-derived borrows never escape. +- At the call site, the result is a new owned borrow whose parent is the argument passed for `%p`; the argument cannot be ended before the result (`E2102`). + +### 11.4 Joins and loops + +The complete borrow state MUST be identical on every edge into a block (`E2105`, reported at the block). The state of each borrow consists of its identity (SSA value), kind (`ref`/`mut`), provenance (root), path, parent borrow, and whether it is live or ended. In particular a borrow created inside a loop body is ended before the back edge. + +Only the set of accepted programs is normative. Because states must match exactly at joins, an implementation can verify a function in one pass over a reverse postorder with one comparison per back edge, but it is not required to work that way. + +### 11.5 Frame size + +Each function's frame storage is the sum of the accounted sizes of its `local.alloc` types. It MUST NOT exceed `max_local_frame` = 1 048 576 bytes (`E5101`, limit `local frame bytes`). Accounted size is a normative counting rule, not a memory layout: + +| Type | Accounted bytes | +|---|---| +| `u8`/`i8`/`bool` | 1 | +| `u16`/`i16` | 2 | +| `u32`/`i32` | 4 | +| `u64`/`i64` | 8 | +| `u128`/`i128` | 16 | +| `usize`/`isize` | 8 (the largest supported pointer width, so the result is target-independent) | +| struct | sum of its fields | +| enum | 4 + the largest sum over a variant's payload | +| `[T; N]` | `N ×` accounted size of `T` | + +### 11.6 Borrow-typed block parameters + +Borrow-typed block parameters are reserved for the feature `borrow_joins`. Without it they are rejected with `E0006` reason `feature_not_declared`. Using a feature gate, rather than a permanent type error, keeps the door open without breaking the format-0 freeze (spec 07 §8.7). + +## 12. Bounds facts (feature `arrays`) + +A **fact** `%i < %n` is established only by the following table. `%i` and `%n` are SSA values of type `usize`; `%c` is the comparison result. + +| Comparison defining `%c` | Established by | Fact | +|---|---|---| +| `%c = lt.usize %i, %n` | true edge of `cbr %c`, or `guard %c` | `%i < %n` | +| `%c = gt.usize %n, %i` | true edge of `cbr %c`, or `guard %c` | `%i < %n` | +| `%c = ge.usize %i, %n` | false edge of `cbr %c` | `%i < %n` | +| `%c = le.usize %n, %i` | false edge of `cbr %c` | `%i < %n` | + +Nothing else establishes a fact. In particular `le.usize %i, %n` and `ge.usize %n, %i` (that is, `i ≤ n`) do not, since `i = n` is out of bounds; comparisons of other types do not; and no arithmetic is performed. + +Scope of a fact: + +- from a `cbr` edge: the target block and every block it dominates, provided the target block's only predecessor is the block containing the `cbr` (so the edge is the only way in); +- from `guard %c`: the instructions after the `guard` in its block and every block that block dominates. + +`borrow.index.proven %b, %i` is **proven** exactly when one of these holds at the instruction: + +| Case | Condition | +|---|---| +| fact on the same slice | a fact `%i < %n` holds where `%n = slice.len %b`, with `%i` and `%b` the same SSA values as the operands | +| constant index | `%i = const.usize k` and `%b` has a static length `N` (a borrow of `[T; N]`) with `k < N` | +| fact against a constant | a fact `%i < %n` holds where `%n = const.usize k`, `%b` has a static length `N` and `k ≤ N` | + +This is the complete normative analysis: an implementation MUST NOT accept more or fewer programs. + +## 13. Initialization (feature `ownership`) + +A `local` is uninitialized after `local.alloc` and becomes initialized by `local.store` or `local.zero`. `local.load`, `borrow.ref` and `borrow.mut` of a local require it to be initialized on every path from the entry block (`E1010`). Initialization is tracked for the whole local; there is no partial initialization in format 0. + +## 14. Stage order + +Verification stages run in this order, stopping after the first stage that reports an error (spec 07 §8.6): resource limits (including frame size), CFG structure (including `local.alloc` placement), SSA, types, initialization, borrows, bounds. diff --git a/src/air/features.zig b/src/air/features.zig index 27b7f08..af3f5ab 100644 --- a/src/air/features.zig +++ b/src/air/features.zig @@ -17,19 +17,21 @@ pub const Feature = struct { name: []const u8, depends: []const []const u8, status: Status, - /// Plan phase that publishes the feature. - phase: u8, + /// Plan phase that publishes the feature; null if unscheduled. + phase: ?u8, }; pub const registry = [_]Feature{ - .{ .name = "arrays", .depends = &.{}, .status = .reserved, .phase = 1 }, + .{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 }, .{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 }, + .{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null }, .{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 2 }, .{ .name = "channels", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, .{ .name = "effects", .depends = &.{}, .status = .reserved, .phase = 2 }, - .{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .reserved, .phase = 4 }, - .{ .name = "ownership", .depends = &.{}, .status = .reserved, .phase = 1 }, - .{ .name = "regions", .depends = &.{"ownership"}, .status = .reserved, .phase = 1 }, + .{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 }, + .{ .name = "islands", .depends = &.{ "capabilities", "effects", "ownership", "regions" }, .status = .reserved, .phase = 4 }, + .{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 }, + .{ .name = "regions", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 }, .{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, }; @@ -142,7 +144,7 @@ test "registry is sorted, closed under dependencies and acyclic" { const dep = find(®istry, d) orelse return error.UnknownDependency; // Dependencies are themselves closed: a feature lists its full closure. for (dep.depends) |dd| try std.testing.expect(contains(f.depends, dd)); - try std.testing.expect(dep.phase <= f.phase); + if (f.phase) |fp| try std.testing.expect(dep.phase != null and dep.phase.? <= fp); try std.testing.expect(!contains(dep.depends, f.name)); } } @@ -160,7 +162,8 @@ test "registry mirrors docs/reference/air-features.md" { var cols = std.mem.tokenizeScalar(u8, line, '|'); const name = std.mem.trim(u8, cols.next().?, " `"); const status = std.mem.trim(u8, cols.next().?, " "); - const phase = try std.fmt.parseInt(u8, std.mem.trim(u8, cols.next().?, " "), 10); + const phase_text = std.mem.trim(u8, cols.next().?, " "); + const phase: ?u8 = if (std.mem.eql(u8, phase_text, "—")) null else try std.fmt.parseInt(u8, phase_text, 10); const deps_text = std.mem.trim(u8, cols.next().?, " "); const f = find(®istry, name) orelse { std.debug.print("feature {s} is in air-features.md but not in the registry\n", .{name}); diff --git a/src/diag.zig b/src/diag.zig index da325cf..2f439dd 100644 --- a/src/diag.zig +++ b/src/diag.zig @@ -35,6 +35,10 @@ pub const registry = [_]Code{ .{ .id = "E2102", .kind = "borrow.outlives_owner", .meaning = "Borrow may outlive backing storage" }, .{ .id = "E2103", .kind = "memory.out_of_bounds", .meaning = "Access not proven in bounds" }, .{ .id = "E2104", .kind = "memory.region_generation", .meaning = "Reference belongs to invalidated region generation" }, + .{ .id = "E2105", .kind = "borrow.not_ended", .meaning = "Owned borrow live at `ret`, or borrow state differs between edges into a block" }, + .{ .id = "E2106", .kind = "borrow.use_after_end", .meaning = "Borrow used or ended after it was ended" }, + .{ .id = "E2107", .kind = "borrow.not_owned", .meaning = "Lent (parameter) borrow ended by the callee" }, + .{ .id = "E2108", .kind = "borrow.escapes_frame", .meaning = "Borrow derived from frame storage returned from its function" }, .{ .id = "E2110", .kind = "island.escape", .meaning = "Island-internal reference escapes island" }, .{ .id = "E2111", .kind = "island.foreign_mutable_edge", .meaning = "Island graph points to forbidden foreign mutable storage" }, // E3xxx — Resources/capabilities/effects @@ -66,6 +70,7 @@ pub const registry = [_]Code{ .{ .id = "T0005", .kind = "trap.shift_out_of_range", .meaning = "Shift amount negative or not less than bit width" }, .{ .id = "T0006", .kind = "trap.cast_out_of_range", .meaning = "Checked cast value not representable in target type" }, .{ .id = "T0007", .kind = "trap.call_depth", .meaning = "Call depth limit (1 024 frames) exceeded" }, + .{ .id = "T0008", .kind = "trap.out_of_bounds", .meaning = "Runtime bounds check failed" }, }; pub fn lookup(id: []const u8) ?*const Code { diff --git a/tests/conformance/phase1/reject/use_after_move.air b/tests/conformance/phase2/reject/use_after_move.air similarity index 79% rename from tests/conformance/phase1/reject/use_after_move.air rename to tests/conformance/phase2/reject/use_after_move.air index d50c45f..1defa2f 100644 --- a/tests/conformance/phase1/reject/use_after_move.air +++ b/tests/conformance/phase2/reject/use_after_move.air @@ -1,11 +1,11 @@ ; %p is moved into %q and then used again. ; expect: reject E2001 -; phase: 1 +; phase: 2 ; spec: docs/spec/03-memory-model.md module test.use_after_move air 0 lang 0.1 -features [] +features [capabilities, effects, heap, ownership] fn @f(%p: Own) -> Own effects []