rfc: define shared enum and nested owner observation candidate

This commit is contained in:
dev committed 2026-10-09 09:03:12 +03:00
1 parent a5f84eb170
commit d041c07ad2
4 files changed
+164

No files matched your search

+2
View File
@@ -422,3 +422,5 @@ Current `match *value` with `value: ref<Outcome>` and `Outcome = enum { ok(own<u
These are specified observation limits, not new verifier bugs. A shared linear struct's Copy field is readable (a count probe returns 7); a read-only contract could likewise need to inspect a linear result's success variant or owned nested data without consuming either. RFC 0039's purity candidate cannot supply missing observation semantics, and the full P6-6 gate remains open.
Decide the required source/AIR observation surface. Candidate directions include a shared-view variant operation yielding borrowed payloads and an explicit shared content view through `ref<own<T>>`; neither is adopted here. Any new primitive requires a registered feature, its full AIR contract, ordinary alias/loan/lifetime enforcement, deterministic behavior, format compatibility and vertical source/Quick Reference/conformance coverage. Do not enable consumption, hidden owner copies or unrestricted partial moves to make predicates expressible.
2026-10-09: [RFC 0040](../rfcs/0040-shared-enum-and-owner-views.md) Draft proposes selective `enum.view` edges and shared `own.view` for scalar and array owners, with explicit source `match ref place`. Single-ingress arm blocks create only the chosen edge's dependent views; no general borrow joins or variant proofs are assumed. A current-language probe confirms that a dormant 65-payload variant is legal, while its value match rejects E5101; selecting no payloads or one would avoid that limit in the candidate. Complete unknown `enum.view` spellings currently report E0004 alone, not E0006 for their borrowed parameters. Isolated `own.view` reports E0004; a used result adds E5001, retaining Q-055's dependent-error gate. This is not adoption, implementation or complete contract coverage.
+4
View File
@@ -339,3 +339,7 @@ Q-054/RFC 0039 Draft identifies the missing executable contract model. Public pr
The next design increment prefers leading `contract.pre/old/post` operations, isolated uses currently E0004, with no entry predecessors, contract-only snapshots and per-return access checks. The candidate specifies pending-return dispatch, ordinary fuel/quantum accounting and temporary observations without resurrecting consumed values. Current ordinary observations before returning an owner accept and preserve 42; observing its old binding after a call transfer rejects E2001. Verified invariant probes return width 10 after a repaired exclusive update, expose an invalid mid-update Copy and trap T0003 in a shared reader. Source struct-zero rejects E7006, while AIR struct-zero accepts; Q-056 records that separate surface question. Claude independently reviewed the candidate and identified dispatch/availability clarifications. A body use of an unknown snapshot additionally yields E5001; use only by a post yields E0004s alone. Q-055 retains the invalid body-use rejection-code audit. All twelve targeted probes match their reported results, and local documentation links/diff checks pass. These are current-language probes of design obligations, not conformance tests for an implemented contract feature. Type/module boundaries, predicate closure and status rules remain open; Draft status and the full P6-6 exit criterion are unchanged.
The purity increment supplies a closed opcode/type candidate, authority-free Copy Data (including opaque iref identity), and greatest-fixed-point call closure. Read-only linear-record fields are admitted without loading owners/capabilities; auxiliary mut helpers can write fresh frame scratch, proved from entry signature restrictions and ordinary borrow rules. No write-summary subsystem or totality proof is claimed. Current probes confirm a scratch/helper/hash predicate (1), linear count read (7), identity after graph destruction (1), accepted Copy capability extraction, and E1001 for borrowed linear variant/nested owner inspection. Mutual recursion returns 1; nontermination is stopped by fuel and recursive frame exhaustion by T0007. Claude independently reviewed the freshness proof and identified the need to freeze predicate classification under §8.7; proposed feature dependencies and immutable classifications are explicit. Q-057 records the missing non-consuming observation surface required before full contract coverage. Type/module invariants, audit statuses, diagnostics and vertical implementation remain open; RFC 0039 stays Draft and normative bundles are unchanged.
RFC 0040 Draft develops Q-057 as a separate vertical prerequisite: selective shared enum dispatch and nested scalar/array owner views. Explicit `match ref place` creates only named payload views; skipped payloads stay owned, with no partial moves or general borrowed block joins. Current probes confirm a legal 65-payload enum returning 0 and E5101 for its value match. Unknown enum-view forms report E0004 alone; isolated owner-view forms report E0004, and a used owner-view result also reports E5001. All seven baseline probes are checked with the existing compiler; executed programs use fuel 10,000. Q-055's dependent-error interpretation remains open. These Draft rules allocate no feature/code and change no normative bundle, compiler or conformance fixture; type/module invariants, contract statuses and full P6-6 delivery remain open.
Claude independently reviewed RFC 0040; corrections preserve existing E0004 name lookup, distinguish E2102 SSA origins from E2108 frame roots, count unreachable ingress and clarify unchanged complete-state joins and pattern-binder status. Three further source probes independently confirm both ref-parameter place spellings (combined result 6), wrong SSA-root return E2102 and Copy-frame escape E2108. All ten probes confirm only current-language constraints, not the proposed operations' implementation.
@@ -84,6 +84,8 @@ Additional current-language probes: a slice predicate calling a scratch-mutating
Observation coverage remains a separate gate (Q-057): current `match *ref<LinearEnum>` rejects E1001, and a shared owner field cannot be dereferenced without attempting a forbidden linear load. The allowlist does not manufacture missing tag/payload or owner-content operations. Preconditions/postconditions over the currently readable subset alone do not complete P6-6.
[RFC 0040](0040-shared-enum-and-owner-views.md) Draft supplies a separate candidate for that gate: selective shared enum edges and shared nested-owner content views, including owner arrays. Their classification would be read-only/shared-result at publication, preserving scratch freshness; no new operation is admitted by this Draft's allowlist today. The dependent-error compatibility audit and full vertical delivery remain prerequisites.
## AIR, verifier and runtime candidate
Prefer a feature-gated entry prefix over new function headers. The following spellings are candidates, not registered instructions:
@@ -0,0 +1,156 @@
# RFC 0040: Shared enum and owner views
Status: Draft
Scope: AIR format 0 and source 0.1; non-consuming observations (Q-057)
Language version: 0.1
This is a candidate prerequisite for [RFC 0039](0039-verifier-visible-contracts.md), not an implementation authorization or a complete P6-6 design. Feature names below are proposed, not registered. Acceptance requires integration and vertical delivery in one phase.
## Motivation
Current source `match *value`, where `value: ref<Outcome>` and `Outcome` contains `own<u64>`, rejects E1001 even when both arms return bool. Spec 03 §25 forbids `enum.switch` on linear enums; `enum.take` consumes them. Reading through a shared struct field of type `own<T>` likewise attempts a forbidden linear load. Existing `borrow.ref` exposes a direct owner's contents but merely reborrows a `ref<own<T>>` as that same type.
Predicates need to inspect success variants and nested owned content without consuming the observed value. These primitives improve semantic explicitness, verifier strength and machine repairability. They apply to ordinary code independently of contracts. They introduce no partial moves, mutable payload views or predicate-specific escape from ownership rules.
## Precise invariant
Observation MUST leave the complete enum or owner and every payload owned by its original root. Each resulting shared view MUST be a dependent child in the existing borrow tree. The root cannot be consumed or modified while conflicting descendants live; an enum's active variant therefore stays fixed for the lifetime of its payload views. Views cannot outlive their root, gain mutable access or bypass task loans. Shared observation does not duplicate an owner, allocate program storage, manufacture authority or create holes in an aggregate. Ordinary reads of Copy capabilities remain governed by existing rules; contract closure restrictions are separate.
## Normative rule changes
The MUST rules in this Draft are proposed integration text, not current specification.
### Features and AIR contracts
Register two features together. `enum_views` depends directly on `ownership`; `owner_views` depends directly on `arrays` and `heap`, whose full closure includes `capabilities`, `effects`, `ownership` and `resources`. Each opcode belongs to exactly its feature. Payload types still require their own existing features. Keeping the registrations separate avoids requiring heap semantics for an enum containing only scalars.
| Operation | Operand and results | Ownership and memory | Concurrency, authority and traps |
|---|---|---|---|
| `enum.view E %r, V[indices] -> @arm, ...` | `%r: ref<E>`; exhaustive terminator; selected arm parameters are shared views specified below | instrumented variant read; create dependent views of selected payload places; no owned value read out, copied, moved or destroyed | ordinary borrow/task-loan checks; no synchronization, capability or effect requirement; no new trap or dynamic variant check |
| `%v = own.view %r` | `ref<own<T>> -> ref<T>` or `ref<own_array<T>> -> slice<T>` | instrumented owner-handle read; view existing allocation, or its entire initialized array; no transfer, allocation, retain or release | ordinary borrow/task-loan checks; no synchronization, capability or effect requirement; no new trap |
`E` is a named enum written `@E`, or one of the three existing built-in error enums written by its existing AIR name. Copy and linear enums are both admitted. Both operations require exactly shared operands; AIR `mut` inputs require an explicit ordinary `borrow.ref` first (E1001 otherwise). A direct owned value is not an operand of `own.view`; its contents already use ordinary `borrow.ref`.
### Selective enum edges
Every variant MUST occur exactly once; defaults are forbidden. Every arm MUST write its selector list, including `[]`. Selectors are unsigned u32 decimal literals; the parser accepts the existing integer-literal spelling rules and the serializer emits canonical decimal without leading zeros, separated by `, `. Each list MUST be strictly increasing and every index MUST identify a payload position of that variant. The target's parameters MUST have, in selector order, exactly the types `ref<P_index>`. There are no explicit edge arguments or ordinary SSA results.
For example, `V[0, 2] -> @arm` observes only the first and third payloads. Omitted payloads remain owned inside the untouched enum. This is selective observation, not selective extraction. A tag query selects `[]` in every arm and returns constants in those arms; no separate tag-test instruction is required.
Each target MUST be distinct within the terminator and have exactly one incoming CFG edge, that arm of this `enum.view`. Count edges syntactically over all blocks, including unreachable ones, at CFG-structure stage. A target MUST NOT be entry, the containing block, or receive another ordinary or implicit edge, including a back edge. This is a second, feature-scoped exception to spec 08 §11.6's borrowed-block-parameter gate; existing `region.new`/`region.array` behavior and the reserved `borrow_joins` feature remain unchanged. An ordinary branch cannot transport these borrows as arguments.
Only the chosen edge creates its target's owned shared borrows. Each has the operand's root, the operand as parent, and a conservative overlapping payload path. Different payload indices MUST NOT establish a new disjointness fact. Other arms' views do not become live. Ordinary lifetime, SSA dominance and spec 08 §11.4's complete borrow-state equality apply unchanged. Different arms must end their edge-created views before rejoining; a branch within one arm may retain the same children on both edges with identical complete states. Loop-created views must end before the back edge. No variant facts, new state equivalences or alternate provenance joins are added.
For `own.view`, the result is an owned shared child of the operand with the same provenance root and a conservative overlapping content path, even though its runtime place points into a different allocation. While its content view lives, the wrapper borrow cannot end (E2102), and its root cannot be consumed or modified (E2101). `own_array<T>` retains its existing Copy-content restriction; this operation does not loosen it.
### Source syntax and lowering
Add the explicit form `match ref place { arms }`. Obtain the enum referent through the existing addressable-place rules, then create a shared reborrow for the duration of the match. For either a named ref binding or a ref parameter, `match ref p` and `match ref *p` are equivalent place spellings lowering to the same reborrow child. An exclusive place uses an explicit generated shared reborrow, so writes through its exclusive ancestor remain forbidden until that child ends. Copy SSA values acquire no new addressability or implicit materialization; existing frame-placement policy remains authoritative (Q-049).
Existing qualified enum patterns remain exhaustive and list every payload position. In this mode each name is a shared binding of type `ref<P>`; `_` creates no view. `E::V(a, _, c)` lowers to `V[0, 2]`, with two borrowed target parameters. Reading a scalar binder uses `*a`; borrowing its fields uses existing place operations. More than 64 named payloads in one arm MUST produce the mapped E5101 block-parameter limit, never a silent split. Existing constructor qualification, imports and generic specialization rules apply.
Fresh values and call-returned borrows must be bound first; a call expression is not a place. This form does not handle ephemeral fallible-operation outcomes. `match r` on a ref remains E7005; ordinary Copy value matches, consuming linear matches and `match *r` retain their current rules. Integer/bool referents in `match ref` reject E7005. Missing variants retain E7004; malformed/default/duplicate enum patterns retain E7006 `invalid_match`, and incorrect payload arity retains E7005. Invalid places use existing E7006 `invalid_place`.
Add `ref content = own.view(parent);`, where `parent` MUST name an existing shared binding or shared parameter of type `ref<own<T>>` or `ref<own_array<T>>`. Match-ref pattern binders are shared bindings for this rule. A struct-field owner first needs a named wrapper view: `ref wrapper = p.payload; ref content = own.view(wrapper);`. The result binding has type `ref<T>` or `slice<T>`, respectively. An exclusive wrapper requires a named shared reborrow first. Ordinary `let`, `mut`, inline temporary origins and non-owner arguments are rejected according to spec 15 §19's borrow-result binding/origin rules and §10's source typing policy; this builtin is borrow-producing, not a first-class borrow-valued expression. Existing return rules require a named result and an explicit `from` root.
Lowering MUST end every created view and match scrutinee reborrow on every normal arm exit, including fallthrough, break, continue and early return. End children before parents. A valid borrow return transfers only the returned view and its owned ancestor chain; all siblings end. A trap carries no cleanup obligation. Match/if/block expressions cannot yield a borrow; a direct named return inside an arm is permitted under existing `from` rules. Source positions for conflicts must refer to the actual binder or operation, including imported specializations.
## Verifier implications and diagnostics
The transfer functions above reuse `(mode, root, path, parent)` and ordinary liveness/loan state. Metadata may be prepared statically; creation and liveness are specific to the selected edge. Multiple parameters receive separate child identities. This requires a gated creation rule, not general borrowed block arguments or a variant-proof calculus.
| Failure | Stage and diagnostic |
|---|---|
| undeclared opcode feature or unrelated borrowed block parameters | feature validation, E0006 `feature_not_declared` |
| index literal not representable as u32 | parsing, E0002 |
| more than 64 selectors/target parameters | limits, E5101 (`parameters per block`) |
| unknown enum or variant | name lookup as for `enum.switch`, E0004 |
| missing/duplicate/default variant; unsorted, duplicate or out-of-range selector; arity or target-ingress violation | CFG/structure, E5002 |
| wrong operand or selected parameter type | types, E1001 |
| ancestor mutation or consumption while viewed | ordinary ownership/borrow checks, E2101 |
| parent ended before child / wrong returned parameter or by-value SSA root | E2102 |
| unended child or unequal complete join state (§11.4) / ended child reused | E2105 / E2106 |
| view rooted in this function's `local.alloc` returned | E2108 |
| access conflicting with task loan / ending while lent to task | E4101 / E4302 |
No new code or runtime-check category is allocated. Diagnostics follow spec 08 §14 stage order: a simultaneous 65-selector and ordering failure reports the limit first. Reuse existing structured limit, type, function, block and value facts; identified conflicts retain factual related positions. Exact source boundary/projection tests are delivery requirements.
Existing limits bound this extension: at most 256 variants and 256 payloads per variant, at most 64 selected views per edge. A 65-payload enum can be inspected with no selectors or `[64]`; selecting all 65 exceeds the block-parameter limit. Existing `enum.switch`/`enum.take` already require every payload as a parameter and cannot match that variant within this limit; changing value matches is outside this RFC. Count incoming edges once and validate selector lists against the type table. Added structural work is linear in edges, variants and selectors; existing bounded borrow analysis handles the resulting values.
## Interpreter / runtime implications
`enum.view` reads through the operand's place once, dispatches on the active variant, and binds selected views as `(cell, path + payload_index)`. It MUST NOT copy the aggregate or any payload. Stability follows from ancestor freezing, not a repeated variant check. `own.view` reads the owner handle through its wrapper place and returns the existing heap cell's content place, or an entire initialized array slice. Its verifier parent remains the wrapper borrow. Both reuse ordinary place/slice representation and GC relocation; views retain no new program owner.
Both instrument their initial read for race checking; subsequent loads use ordinary instrumentation on the selected storage. Each operation costs one instruction of fuel and normal scheduler quantum accounting. There is no per-selector instruction charge, heap budget charge or invisible predicate dispatch. Resource limits bound selector work. Deterministic and hosted profiles have identical view semantics. Neither changes cancellation, traps, memory ordering or task lending/Share rules. `aji report` adds no dynamic check for dispatch or projection; normal payload arithmetic/bounds checks remain visible.
At publication, classify both operations as read-only/shared-result observations for RFC 0039's initial predicate closure. Selected shared views into authority-containing values are possible in ordinary code; the contract closure still forbids extracting an owned non-Data result. These primitives cannot produce mutable scratch roots and preserve that RFC's freshness proof. Predicate admissibility alone does not prove a clause true.
## Valid and rejected examples
Candidate source (not accepted by today's compiler):
```aji
enum Outcome { ok(own<u64>), err(u64) }
fn inspect(value: ref<Outcome>) -> u64 effects [] {
match ref value {
Outcome::ok(owner) => {
ref content = own.view(owner);
return *content;
}
Outcome::err(code) => { return *code; }
}
}
```
Candidate AIR for a returned view; the original owner remains in the caller:
```text
module shared_result
air 0
lang 0.1
features [arrays, capabilities, effects, enum_views, heap, linear_aggregates, owner_views, ownership, resources]
type @Outcome = enum { ok(own<u64>), err(u64) }
fn @content(%value: ref<@Outcome>) -> ref<u64> from %value
effects []
entry:
enum.view @Outcome %value, ok[0] -> @ok, err[] -> @err
ok(%owner: ref<own<u64>>):
%content = own.view %owner
ret %content
err:
trap
```
`ret` transfers `%content` and its owned `%owner` ancestor, according to the existing `from` rule. Inserting `borrow.end %owner` before that return rejects E2102. Using a `mut<@Outcome>` directly as the enum operand rejects E1001. An ordinary `br @ok(...)` adds a second ingress and rejects E5002. A mutable store or whole-value consume of the caller's enum while the returned descendant is live rejects E2101. Returning a view rooted in this function's `local.alloc` (a Copy enum) under an unrelated parameter's `from` rejects E2108; a wrong SSA enum/owner root instead rejects E2102. No rejected example depends on treating the owner itself as Copy.
## Compatibility and migration
The existing compiler at `a5f84eb` was probed without new features. A complete `enum.view` spelling with either selected borrowed parameters or only empty selectors reports E0004 alone; the unknown terminator does not currently reach borrowed-parameter validation. Isolated scalar/array `own.view` spellings likewise report E0004. Using its unknown result in a load additionally reports E5001. A valid enum declaration with a dormant 65-payload variant runs and returns 0; matching that variant by value rejects E5101. All executions use fuel 10,000. These are baseline probes, not tests of an implemented feature.
Three additional source probes confirm existing rules: explicit borrows of a ref parameter by name and dereference both work (combined result 6); returning a field view from a by-value linear record under an unrelated `from` rejects E2102; the Copy frame-record counterpart rejects E2108. Claude independently reviewed the proposal; no safety hole was identified, and its diagnostic, ingress and place-binding corrections are reflected above.
The named-opcode E0004 cases are candidates for the spec 07 §8.7 extension exception; after registration, undeclared use requires E0006. The dependent E5001 case still requires Q-055's compatibility interpretation before publication. Do not claim the whole feature AIR0-compatible from its first error alone. Independently invalid SSA must remain invalid. No previously accepted opcode, borrowed-block context, canonical bytes or runtime meaning may change. If this audit cannot establish format-0 compatibility, use a new format rather than weakening the freeze.
Source extensions replace rejection only for the explicit new forms. They do not infer borrowing from the scrutinee's type, materialize new places, change complete-value movement or widen value matches.
## Spec integration and delivery
Acceptance integrates spec 03 §25 and heap content-view rules; spec 07/07a grammar, opcode contracts and canonical text; spec 08 §7/§11.6 and creation transfer functions; spec 10 audit classification; spec 11 fuel/replay; and spec 15 §4/§6/§8/§9/§10/§19. Update both grammars, feature registry, Quick Reference and required bundle inputs. Any contract integration must classify these operations when its purity rules are first published.
Delivery in the same phase includes AIR parsing/serialization, verifier, interpreter, source parsing/formatting/lowering, source coverage and positive/negative AIR/source conformance. Required cases include Copy/linear/built-in/imported/generic enums; shared and explicit exclusive-to-shared roots; named and dereferenced places; nested enum/own/own_array views; scalar and empty-array content; returned ancestors and sibling cleanup; all structured exits; two different parents and local escape; ancestor store/swap/consume; live task loans and payload-specific Share restrictions; invalid selectors and second ingress/back edges; 64/65-selector limits and stage order; GC before every instruction, schedule stress and race-instrumented reads. Existing value matches and direct owner borrows are regression cases. Documentation examples become executable only with that implementation.
Also pin unreachable second ingress (E5002), independently ended per-arm views rejoining successfully, an intra-arm branch retaining identical children, both place spellings for parameters and bindings, and Copy-frame versus SSA-root return diagnostics. Nested views through `buffer<own<T>>` must block pop/reserve; `mutex<own<T>>` views must end before unlocking their guard, with rejected live-child counterparts.
## Agent complexity impact
Two source forms are added: explicit `match ref place` and the `own.view` borrow-producing builtin. Pattern names in the explicitly shared mode are refs; `_` avoids unnecessary views. AIR gains two opcodes and two feature identifiers. Source agents never write those headers. Existing provenance, cleanup, `from`, Share and task-loan concepts remain; new verifier machinery is selected-edge creation plus a restricted borrowed-target gate, without variant facts, ownership holes or new mutable authority.
Existing primitives suffice for direct-owner content and Copy struct fields, but not these nested/shared cases. Explicit projection should replace failed linear loads with ordinary, checkable views; the claimed reduction in repair burden still needs public measurements. No benchmark-specific feature or private evaluation input is used.
This Draft changes no Quick Reference, normative AIR bundle, source bundle or std input: their growth is zero in this change. Before acceptance report actual before/after token counts for `zig build agent-reference`, AIR/source bundles (`tools/agent_bundle_tokens.py`, `--source`) and Quick Reference across all supported tokenizers, including std separately. Keep integration text proportional to the two operations; justify growth rather than copying the RFC into agent inputs.
## Alternatives and open gate
A checked payload projection needs a new wrong-variant trap and redundant checks in every exhaustive source arm; eliminating them would need variant proofs. A separate tag-test opcode is unnecessary because zero-selector dispatch expresses it. An all-payload borrowed match cannot even query the tag of a valid 65-payload variant within current block limits. General borrow joins, implicit owner copies, partial moves and mutable projections impose unrelated semantics and are excluded.
Remaining gates: the dependent-error compatibility audit (Q-055), exact source diagnostic/binding integration, complete vertical tests and measured documentation cost. Q-057 remains unresolved until adoption. RFC 0039 still needs type/module invariant boundaries, status/proof rules and its own diagnostics/runtime design; this prerequisite does not complete contracts or Phase 6.