Files
aji/docs/design/contract-source-and-module-state.md
T

19 KiB

Contract source elaboration and rooted module-state candidate

Non-normative continuation of RFC 0039, checked representations and proof/report rules, at 8260d35. This proposal adds no implemented syntax, feature or normative rule. It preserves full P6-6, including type/module claims and all four statuses. Hidden globals, visibility, property/ABI auditing, diagnostics/dispatch integration, adoption and vertical delivery are not established here.

Module invariant and identity

Propose that a module may name its explicitly rooted persistent state with a narrow declaration:

module account
struct Rep { balance: u64, limit: u64 }
fn within(r: ref<Rep>) -> bool effects [] { return r.balance <= r.limit; }
invariant State = type.checked<Rep, fn within>;

invariant is contextual only at item start. State is a type binding for exactly the structural checked<R,p> identity; it is not an ordinary struct with a public rep field. Its defining module owns the declaration, while callers own each value. All exposed State values/shared content views satisfy p, even in unlisted functions/importers, because creation and updates use checked.make/modify and ordinary operations cannot manufacture it or mutate representation observations admitted by p. Interior-mutable interfaces may still change ignored members, as required by S. Extraction returns ordinary R with no claim. Neither a singleton nor an invocation of a module constructor is implied.

Correlated owners belong in one representation State: its borrow ancestry protects the joint relation while views are shared. A relation over independently owned roots instead remains a pre/post boundary claim; it can fail between calls. This is not a module-wide persistent guarantee. No new named boundary-group metadata is proposed: listing functions cannot establish that all mutators are listed when fields are public. Ordinary prefix coverage is still checked independently by the AIR verifier.

Choosing rooted state as spec 13's module-invariant model is an owner decision. If hidden module-global state is required, this candidate does not provide it and a separate state/encapsulation abstraction is needed. The module requirement is not silently replaced with function contracts.

Two invariant names with the same resolved R and p denote the same type. Distinct nominal representations remain distinct. This is a narrow checked-type binding, not a general alias facility. Direct type.checked<Rep, fn within> type expressions remain available. A generic declaration uses existing type/static-function parameters, for example invariant State<T: Copy> = type.checked<Rep<T>, fn within::<T>>;. Predicates specialize explicitly and must have exactly ref -> bool, no captures, and S membership after substitution. A binding's constraints restrict its use; direct checked types still follow their own R/p validity rules, not an unrelated alias's constraints.

Resolve these bindings before equality, property tests and specialization-key construction. The canonical type key spells checked<canonical-R,fn canonical-function-identity>; an alias spelling does not create a different container specialization. Existing type/function keys are unchanged. Imports retain direct-import lookup; no module name is inferred from AIR mangling. Alias-resolution cycles fail with a stable E7006 reason; expansion depth, specialization count and key bytes use the existing 64/4096/16384 compiler bounds. Nominal representation references stop alias expansion; ordinary recursive-layout validation remains independent.

Every concrete declaration must reach AIR type verification even when no value is constructed. Candidate lowering emits a generated identity witness fn @w(%value: checked<R,@p>) -> checked<R,@p> effects [] { ret %value }. It is never implicitly invoked, holds no global state and validates the type/predicate through its signature. Linear values transfer on its ordinary ret. Its declaration appears in canonical AIR and the report's ordinary functions list, with no calls or check rows. Generic witnesses are emitted for concrete specializations; known template restrictions still check before substitution. This needs a complete representation/type-position audit: the witness must not invent an invalid parameter/return position for a type otherwise admitted by the final checked feature.

Source grammar and explicit operations

Proposed additions to the existing grammar: new clause/declaration introducers are contextual; type/fn reuse existing reserved keywords.

checked_type   = "type" "." "checked" "<" type "," "fn" name_path [ application ] ">" ;
invariant_decl = "invariant" ident [ type_params ] "=" checked_type ";" ;
checked_op     = "type" "." "checked" "." ( "make" | "view" | "take" | "modify" )
                 [ application ] call_args ;
contract_mode  = "assume" | "document" ;
contract_block = "{" expr ";" { expr ";" } "}" ;
requires_group = "requires" [ contract_mode ] contract_block ;
ensures_group  = "ensures" [ contract_mode ] contract_block ;
fn_tail        = "effects" "[" [ path { "," path } [ "," ] ] "]"
                 { requires_group } { ensures_group } block ;

Groups are nonempty, use bool expressions with terminators, and appear after effects. Requires groups precede all ensures groups; relative source order within each class is preserved. No trailing expression substitutes for the semicolon and no clause occurs in the body. Requires/ensures/assume/document remain identifiers outside this header position; old/result remain ordinary names outside ensures. This deliberately replaces spec 13's illustrative clause placement, not today's implemented grammar.

Use existing explicit static-function argument syntax for checked operations:

let s: State = type.checked.make::<Rep, fn within>(Rep { balance: 0u64, limit: 10u64 });
ref whole = s;
ref raw = type.checked.view(whole);
// A later exclusive scope, after both shared views end:
type.checked.modify::<fn update>(state_borrow, amount);
let plain = type.checked.take(value); // use move value when it is linear

Make has two static arguments, representation and predicate. Modify has one explicit static function selection; its first runtime operand is a named exclusive checked borrow, followed by callback extras. View uses a named shared/exclusive checked borrow and returns a shared child; take uses an ordinary whole checked value with the existing move discipline. View/take have no static arguments. The :: application form is chosen because selecting a static function uses the existing generic-argument syntax; channel.make/buffer.new's type-only dot-step syntax is unchanged. Built-in operations are not selectable function arguments. No runtime function value or special fn expression argument is introduced. Whole-value literals initialize R, not State: State { ... }, zero State and direct mutable content projections reject. Construction validation is visible in type.checked.make rather than hidden in a struct literal.

The reserved type keyword anchors these new forms. Ordinary modules/functions/types named checked, including user generic checked<R, fn f> and self-qualified checked.make, retain ordinary lookup. Using checked.* as the built-in namespace would hijack accepted programs; no such reservation or context-sensitive fallback is proposed. Exact source spelling uses type.checked, while AIR operations/type constructors retain checked.* / checked<...>. Grammar integration adds checked_type to types, checked_op to expression primaries, and the view form to borrow-binding calls; it does not admit type names or other checked operations as borrow results.

Clause roots, result and snapshots

A clause is checked in a separate lexical environment containing original header parameters and directly accessible functions/types; it cannot capture a body local or a reassigned/shadowing body binding. Data parameters may be read by value. Borrow parameters expose a temporary read-only view (mut becomes ref; slice_mut becomes slice), not their writable mode. Owned/authority-containing non-Data values require an explicit shared root observation, such as valid(ref owner) or a nested expression block with ref r = owner;; they cannot be passed/loaded by value. Ordinary owner unwrap and whole-array/slice argument rules remain explicit. There is no new implicit owner dereference.

Expression blocks may use fresh Data scratch and ordinary P helper calls, including loops. Inline clause/old expressions cannot return from the surrounding function or the generated collector: reject return statements with a stable contract-context reason; break/continue target only loops inside the expression. Named predicate/Data helpers retain ordinary returns. Writing through a header root, synchronization, authority, ambient observations or ownership transfer remains forbidden. The helper is independently checked by AIR P membership; a source purity annotation is not evidence. Capture keys are (original parameter ordinal, value/shared-root form), with projections/adapters inside the helper. Repeated equal keys share an argument; value precedes shared-root form for each ordinal. Old's helper uses the same deduplicated union of captures across all executable old expressions. Post appends its one snapshot-record argument when used, then result observations (value before ref) when used. More than 64 helper arguments, including these, reports the mapped E5101 parameter/argument bounds; do not split a clause silently. This fixes AIR n/E/W independently of syntax repetition. Complete materialization and helper-frame budgets still apply; new observational root shapes require a separate addressability/loan audit rather than assuming that ordinary body SSA becomes addressable.

Inside ensures, unqualified result is the actual return observation, not a body variable or an entry capture. A header parameter or clause-local binder named result conflicts when ensures is present; reject with a stable source reason at the conflicting binder. Ordinary body bindings named result and functions without ensures keep their existing meaning. Void has no result; never has no postcondition. old(expr) is recognized as snapshot notation only as the unqualified one-argument call in ensures. If old is also visible there as a local function, parameter or clause binder, the unqualified call rejects with a source name-conflict reason; self-qualified/import-qualified old functions remain ordinary calls. Outside ensures, old calls use ordinary name resolution, not snapshot semantics. Result inside old, nested old and non-Data old results reject. Old's free value roots must be original header parameters; clause locals declared outside expr are unavailable at entry and reject. Local scratch binders declared inside expr remain allowed.

Every runtime/assumed old occurrence is evaluated once, in lexical clause/expression order, after all preconditions and before the body. Even an occurrence in a short-circuited post branch is captured eagerly. It may trap or exhaust fuel before the body; old is not observationally free. Distinct executable occurrences remain distinct slots, even with identical text; no optimizer deduplication changes fuel. All slots lower to one bounded Data record and one contract.old helper. Since ordinary struct.make has a 64-operand bound as well as the 256-member bound, package slots by greedy left-full chunking: zero-based group i holds slots 64i through min(64i+63, last). Only the final group may be short; always wrap it in a record, even when it has one slot. Recursively apply this same rule to child records until one root remains. Evaluate all expressions first, then construct each record level left to right, bottom up. A count at most 64 uses one direct record. Fields use their zero-based positions within each record; projection paths follow this fixed tree. Snapshot-record name keys extend the function/specialization key with zero-based level (leaves are 0) and group index. No padding, partial initialization or program heap allocation is introduced; existing type/value/frame/function/instruction bounds still apply.

A documented old(expr) must refer to an equal executable capture already present in this function; choose the first matching executable occurrence. Equality is structural over the typed expression tree, ignoring spans/comments/parentheses, retaining internal local binder spellings and resolved parameter/function/type identities. It is alpha-sensitive: changing an internal scratch binder's name does not match. It is not algebraic equivalence or hash equality. A document cannot add snapshot work of its own. No matching executable capture rejects with a stable source reason; deleting the last executable use must not silently retain a snapshot for documentation alone. This refines the AIR rule allowing documented binding of an existing executable snapshot.

Post helpers receive the snapshot record and result only when needed, alongside original roots. Snapshot field projection happens inside the helper. Original body SSA never enters the prefix binding list. Parameter-free predicates remain possible on main. Generic/static/package calls, recursive calls and spawned workers use the callee's same prefix; returns, implicit tails and ordinary cleanup lead to the same enforced post boundary. Source loan/cleanup machinery must retain required original roots without extending loans past ret or resurrecting consumed values; exact integration tests remain mandatory.

Generated helper/witness/snapshot names use collision-free deterministic keys containing the defining function/declaration identity, concrete specialization and clause/old ordinal. Original/generated names are reserved before choosing the smallest free suffix, and the emitted generated declarations are sorted by their keys. Existing contract-free specialization ordering/bytes stay unchanged. Exact mangling tags/serializer placement still need integration with spec 15 §15.

Declared claims in the report

Make/modify rows alone omit a library invariant whose type has no construction site. Propose an additional contracts field types after rows/totals: distinct checked identities in first structural occurrence order across declarations, signatures, blocks and typed instruction operands. Traverse wrappers/member graphs once with visited identities; do not expand occurrences exponentially or parse a module name out of a generated symbol. The identity witness ensures concrete unused source declarations are represented. Its ordinary return is not an extra invariant-check row.

For each identity record the canonical checked type, predicate, status, proof, enforcement and supplied declaration provenance. Proposal: classify p universally over one shared R observation, using the same closed normal form as a pre (B=1, n=1, D=O=0). Predicate truth is not inferred from a successful make. Proven yields PROVEN_STATICALLY, otherwise CHECKED_AT_RUNTIME with runtime enforcement by construction/update; type invariants have no assumed/documented mode. Instance sites retain their own classifications, so a universally unproved Range predicate can coexist with a proven constant make. Type records do not contribute to row totals and have no separate status totals initially. Concrete universal-root term identity, canonical inventory schema/provenance order and property/ABI rules remain integration gates; this is not today's report output.

Valid target: a module exports State holding two correlated counters; unrelated imported code can share it, exchange it, or update it through a callback, and the persistent relation survives every successful update. An in-place update of a borrowed linear buffer representation needs no replacement allocation. Rejected targets: public field writes into State; callback returning a borrow from R; overlapping update arguments; predicate with mutable atomic observations; zero construction; an invariant declaration with wrong predicate signature even when unused. A boundary relation over separate mutable roots remains valid only at its explicit pre/post boundaries.

Compatibility and delivery

No new AIR header/type-declaration kind is used. Identity witnesses use ordinary function declarations; checked type operands and operations retain the unknown-constructor/opcode E0004 path, subject to Q-055's dependent-error audit. The evidence below pins complete current spellings without claiming full format-0 compatibility. Source item/header, reserved expression and reserved type positions have the separately recorded E7001/E7002 transitions; existing ordinary identifiers/namespaces are preserved. Wrong static selections/argument types and invalid type positions follow existing E7002/E7005 rules; new source-context conflicts need stable E7006 reasons, not message parsing.

Costs: one narrow named declaration, clause groups, contextual result/old, four explicit checked operations, capture/snapshot elaboration, identity witnesses and type-level audit records. No module-global instance, hidden checking constructor, general alias system, new runtime function values or boundary-group verifier state is introduced. Compare this against inline checked types and nominal checked-struct syntax before adoption. Measure final Quick Reference/source/AIR growth; this research is outside the bundles. Remaining gates include exact alias/property/ABI/mangling/schema rules, source/semantic diagnostic order, traps and pending dispatch, RFC 0040, owner model selection and full source/AIR/package/generic/GC/schedule validation.

Verified source compatibility constraints

Nineteen current-language probes at 8260d35 contain no implemented contracts. All source fixtures include main, so unknown-name cases do not accidentally measure a missing entry point. Executions use fuel 10,000.

Cases Current result
Ordinary functions/parameters named old, result, requires, ensures, invariant, assume, document and checked accepts; returns 6
Existing explicit static-function application accepts; returns 6
Invariant declaration / clause header E7001
Unresolved unprefixed checked type / make / modify E7002, naming checked / checked.make / checked.modify
User module checked calling make/view/take/modify by self-qualified name accepts; returns 10
User generic struct checked<R, fn p> accepts
Reserved type.checked type position E7002, naming type.checked
Reserved type.checked.make / modify expressions E7001
A module or type binding named type E7001
Ordinary Copy / linear AIR identity witnesses accepts
Complete checked AIR identity witness E0004 alone
Flat AIR struct.make with 65 fields/operands E5101: arguments per call, found 65, max 64
Same 65 values packed into 64/1 leaf records and a two-field root accepts; returns last value 64

The reserved-prefix choice is justified by inability to bind its first component, not by assuming every type position is a syntax rejection. The proposed type form changes an E7002 rejection to acceptance; the expression/item/header forms change E7001 rejections. Existing module checked and generic checked types must keep their meaning. Witness acceptance on ordinary R does not prove all checked type/property positions valid. Claude independently read the recorded results and reviewed name/capture/snapshot rules; no language feature or owner policy is adopted.