# 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` and `Outcome` contains `own`, 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` likewise attempts a forbidden linear load. Existing `borrow.ref` exposes a direct owner's contents but merely reborrows a `ref>` 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`; 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> -> ref` or `ref> -> slice` | 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`. 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` 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

`; `_` 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>` or `ref>`. 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` or `slice`, 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), err(u64) } fn inspect(value: ref) -> 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), err(u64) } fn @content(%value: ref<@Outcome>) -> ref from %value effects [] entry: enum.view @Outcome %value, ok[0] -> @ok, err[] -> @err ok(%owner: ref>): %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>` must block pop/reserve; `mutex>` 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.