<!-- description: Use the HoldFast mathematical elaborator to check dependent and graded definitions, inspect compiler obligations, and replay emitted Gallina in Rocq. -->

# HoldFast mathematical elaboration prototype

## Elaboration boundary

The elaborator interprets supported schema-2 syntax by translating it to
Gallina. A digest binds the exact source bytes. Kernel replay checks the
generated term. [Menhir surface parser](../parser/) ·
[Source and machine correspondence](../../extensions/unified-source-contract/)

The prototype supports type-valued parameters, definitional reduction and
compositional constants. The metaprogramming design covers general descriptor
reflection and generated declarations. [Metaprogramming](../../extensions/metaprogramming/)

## Default grade checking

Ordinary `holdfast-parser elaborate` and locked builds replay explicit
`NatExact` or `NatBound` annotations across a pure definition's graded
dependencies before emission. The fragment covers dependent functions,
type-valued polymorphism over predicative `Type` / `Type<n>`, calls to earlier
definitions, natural indices, `let` and indexed records. A typed `let`
supplies its declared callable type to an initializer lambda, including
dependent parameter and result types. Tuples supply component types to
lambdas. Indexed record matches specialize those types by branch motive.
Tuple `let` bindings infer field computation demand using the enclosing
callable interfaces, including repeated uses advertised by callbacks.
The locked frame client checks exact and bounded callables and replays the
emitted callback behavior in Rocq.
[Locked frame controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_indexed_record_callbacks)

Locked modules can export a record with a natural index and a vector indexed
by it. The vector element is `Nat` or the record's single type parameter.
Clients construct it by qualified name, supply the element type for a generic
constructor, pass and return it through imported callables, and specialize
match motives from its fields. Construction and constructor patterns accept
a positional prefix followed by field labels in provider declaration order.
An irrefutable `let` in an expression or a pure function body uses the same
checked field demands as `match`. A `let` or a match with an omitted motive
can specialize the expected result type for a record variable using the bound
index. Without an expected type, either form can infer a result type independent
of its pattern bindings.
Replay binds declaration identity and exact provider source, checks labels,
element type and extent, and refuses identical shapes from other declarations.
[Exported record replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_exported_indexed_record) ·
[Type-parametric replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_polymorphic_indexed_record) ·
[Call labels](../../language/surface-grammar/#concise-authoring-syntax) ·
[Pattern labels](../../language/surface-grammar/#ergonomic-authoring-and-bounded-collection-iteration)

A client can project the declared natural index of an indexed record from a
variable, constructor, imported function or callback. A computed receiver is
evaluated once and contributes its full computation demand, including when
the projection appears in natural addition. Its dependent callable interface
tracks type use in separate rows.
[Locked index projection replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_indexed_record_projection)

A canonical `Box` keeps grade and payload distinct. Clients can construct,
open, pass and return it across graded callables and public locked-module
interfaces. A `.Value` projection on a box returned by a function or callback
checks the call and consumes one use of its payload under the box's grade.
For a natural payload, `match` and irrefutable `let` can specialize the expected
result type of a box variable at its bound payload, including in the branches
of a sum index case. Without an expected type, either form can infer a result
independent of the payload binder.
Calling a graded `Box` or callback interface requires a grade-checked caller.
Unsupported grades yield located refusals before publication.
[Locked box projection and elimination replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_box_result_projection)

A two-constructor sum match supplies each branch with its specialization of
the motive, including nested index cases over the same sum. For a stable sum
variable, the expected result type can supply that motive. With neither an
explicit motive nor an expected type, the match can infer a shared result type
independent of the branch binders. Locked clients use these rules to construct
callbacks with indexed vector parameters and results. Computation and type-use
allowances are checked separately.
[Locked sum callback replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_sum_callback_elimination)

For Booleans and local two-constructor enums without payloads, graded replay
checks `is`, `is not` and unguarded alternative patterns. The scrutinee
contributes demand once. Each distinct alternative checks the shared arm under
the domain's ordinary branch rule. Bounded replay of the concise and explicit
forms produces identical graded terms and demand rows.
[Pattern contract](../../language/surface-grammar/#concise-syntax-refinements) ·
[Graded pattern replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_patterns.py)

Grade receipts bind source, certificate and Rocq support. Locked build identity
also binds support sources. `check-grades` reports separate demand rows and the
certificate. Pure graded callers can use public first-order, type-polymorphic,
box and higher-order definitions by name, module alias or selected alias, and
pass imported definitions as callbacks. Replay uses the provider's grade
domain for arguments. Nested calls retain labels through partial application
and dependent specialization. An imported canonical `Box` and its qualified
constructor projections use the resolved domain in computation and natural type
indices. The grade receipt binds the declaration's locked identity and source
digest. Caller receipts bind every reached provider's locked identity and grade
receipt, including through private helpers in other modules. General grade
domains need further qualification.
[First-release contract](../../language/first-release/#default-graded-checking)

## Pure graded source replay

Run `python tools/run.py holdfast-parser check-grades tools/tests/fixtures/graded-dependent.hf Specialize`
to check a definition and its same-module dependencies in the
[pure graded calculus](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_pure.v). This investigation accepts
lambdas with typed parameters and pure `Fn` telescopes over `Type`, `Type<n>`,
type variables, `Nat` and `Vec<Nat, n>` with explicit
`@ NatExact(n)` computation allowances. Dependent application indices use
variables, decimal literals and addition. Type arguments use `type ...` or a
bound type variable and enforce predicative universe levels. Application checks
the argument's type, including its grades, up to renaming of binders. A label
must match the next named callable parameter. This value
rule requires a codomain well formed without the applied binder. The checker
computes type use separately from the computation demand and checks the
specialized codomain.
[Application fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-application.hf) ·
[Type-identity fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-type-identity.hf)

A natural `let` accepts a stable initializer of names, natural literals and
addition. Count the initializer once, check the allowance against body demand,
and substitute into the result type and type-use row. A local with zero
computation use can still determine a vector extent.
[Natural let fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-let.hf)

Symbolic natural grade reconstruction checks each `let` and lambda binder
under its own allowance, including binders inside conditional and match arms.
Product and record elimination checks each pattern field's computation demand
against its reconstructed allowance. An insufficient allowance reports the
local binder's span.
[Nested binder replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_nested_symbolic_binders) · [Product and record replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_symbolic_pair_and_record_payloads)

Reports bind source digest and declaration span to Rocq replay and support
digests. Replay proves the reported exact computation and type rows, including
binder annotation and final result dependencies. In `Specialize`, `n + n`
contributes zero computation uses of `n` and two type uses each in the returned
parameter and result types.
[Source fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-dependent.hf) ·
[Core source replay predicate](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_source.v)

For a concrete `NatExact` or `NatBound` definition whose body begins with
local lambda bindings, `check-grades` includes `capture_demand`. The report
lists parameters and local closures in declaration order with their source
spans, allowances, computation demand and direct captures. Each capture
names its binding by zero-based position. The `result` row records direct
uses in the rest of the body. In `NatBound`, a closure initializer's
captures are scaled by the declared allowance, including when later code
does not use the closure. Rocq checks the initializer and result rows from
the emitted term. The report checks propagated parameter demand against
Rocq's computation row. Locked package admission uses the existing grade
certificates.
[Capture graph replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_demand_graph.py)

### Bounded natural grades

Run `python tools/run.py holdfast-parser check-grades tools/tests/fixtures/graded-bounded.hf Specialize --domain NatBound`
to replay explicit `@ NatBound(n)` allowances on all binders in the definition
and its dependencies. Rocq checks reconstructed computation demand against the
allowance. The report gives the order in `domain` and the advertised allowance
in each `computation` entry. Calls scale demand by the advertised bound.
Type-use and telescope rows remain exact in both natural domains.
[`NatBound` admission order](../../extensions/graded-foundation/#dimensions-and-lawful-domains)

In `Specialize`, `n` has computation bound zero and four type uses. The returned
function uses `values` once against a bound of two. Replay rejects a third use
and catches changed type rows by equality.
[Bounded source fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-bounded.hf) ·
[Core source replay predicate](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_source.v)

### Graded box source replay

Run `python tools/run.py holdfast-parser check-grades tools/tests/fixtures/graded-modal.hf PromoteAndOpen`
to replay promotion and an explicitly motivated match over a natural-valued
box. The input declares the ordinary `Box<T, grade q : NatExact>` record with
one `T Value @ q` field. The replay checks that declaration shape. Construction
uses `Box<Nat, q>(value)` with a literal grade and a pure natural index.
Elimination uses `match (box) as whole : TYPE { Box(value) => BODY, }`.
Type indices can observe `whole.Value` or the value of a promoted index.
Pair results let an example expose both a computation and a dependent type.
[Dependent elimination](../../extensions/graded-foundation/#dependent-data-and-elimination)

The checker specializes the motive for both the branch and the actual
scrutinee. It checks the grade of the branch binder and both resulting type
demand rows. The report records the exact source bytes by digest, the box record
dependency, the declaration and binder spans, and the telescope demand rows.
`PromoteAndOpen` uses its input `n` four times in computation and eight times in
the result type. `KeepShape` uses its box only in the next parameter's type and
the result type, with one use in each row.
[Modal source fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-modal.hf) ·
[Core source replay predicate](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_source.v)

#### Bounded graded box replay

Run `python tools/run.py holdfast-parser check-grades tools/tests/fixtures/graded-modal-bounded.hf OpenBounded --domain NatBound`
to check the same modal fragment with `record Box<T, grade q : NatBound>` and
explicit `@ NatBound(n)` computation allowances. Rocq checks bounds at the
definition parameters, lambda binders and the match payload. The
`computation` field gives the declared allowance. Motive specialization and
telescope and result type demand retain their exact natural counts.

`OpenBounded` uses its box once with allowance two, reads the payload twice
with allowance three and returns a function that uses its argument once with
allowance two. The result type uses the box twice. `PromoteBounded` scales the
computation demand of `n + n` by the box grade to six and records twelve uses
of `n` in the result type. An over-budget branch, an inconsistent motive or
an altered type-demand row fails replay.
[Bounded modal fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-modal-bounded.hf)

When the box grade `q` is symbolic, Rocq replays the payload computation
allowance `q` and type-use allowance `q * kappa` for the motive allowance
`kappa`. Both checks cover every natural grade assignment. A refusal points to
the payload binder.
[Symbolic payload replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_symbolic_box_payload)

### Graded dependent pair replay

Run `python tools/run.py holdfast-parser check-grades tools/tests/fixtures/graded-dependent-pair.hf OpenIndexed`
to check a match on `record Indexed(Nat Length, Vec<Nat, (Length)> Payload)`.
The replay accepts named records with a `Nat` field followed by a natural
vector. The vector extent can use the first field, natural literals and
addition. Construction checks the vector against the extent instantiated at the
first argument. Matching checks the record identity and binds the vector at the
extent instantiated at the first pattern binder. An explicit motive can
project the record's first field. The checker specializes the motive at both
the pattern and the scrutinee and checks the two type-use rows.

One computation grade governs both fields. Under `NatExact` the field counts
must agree. Under `NatBound` the checker uses the least common upper bound
of the two natural counts. This grade scales the scrutinee's computation
row. The motive scales its type-use row independently. `OpenIndexed` checks
two computation uses and two type uses of `packed`. `BuildAndOpen` keeps
the length and payload in the result type with zero computation demand.
Use `OpenBounded --domain NatBound` with the same fixture to replay
an asymmetric body under a shared bound. `OpenStereo` constructs and opens a
record whose vector has extent `Ticks + Ticks + 1`. The extent contributes
two type uses in the vector parameter's annotation, and the specialized motive
contributes two more uses of the index without any computation demand.
[Dependent pair fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-dependent-pair.hf) ·
[Elimination rules](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_modal.v)

Flat product patterns with three or more binding names use nested eliminations
of the right-associated product. Each pair applies the same computation rule,
and Rocq checks the dependent result type. The locked exact and bounded replay
checks both a computed `let` scrutinee and a parameter matched in place.
[Locked triplet replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py#_locked_wide_tuple)

### General modal domains, sums and type-grade replay

`holdfast-parser check-grades` replays projected source in the Rocq
`GradedCore` calculus. It checks separate type-use and computation rows for
functions, lambdas, let bindings and dependent eliminators. Its source
fragment includes `Box`, `Sigma`, `Sum`, records, indexed
`inductive` families, dependent motives and predicative universes.
The grade-domain fragment supports `JoinDomain` ordered semirings,
symbolic grade polynomials, custom `domain` declarations and
`<grade q : D>` polymorphism. Failures identify the relevant source spans.
[Unified graded replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_domains_and_grade_polymorphism) · [General modal replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_modal.py#_general_modal_source_replay) · [Sums and presence replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_modal.py#_sums_and_presence_modal_replay)

Symbolic `NatBound` demand takes the maximum of branch demands. Rocq checks
the bound under every grade assignment, including when a callable consumes
`q` uses in one branch and `r` in the other. An allowance of `q + r` admits
that demand. An allowance of `q` requires evidence that it also bounds `r`.
Failed symbolic checks report the binder's source span.
[Branch replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_symbolic_bound_branches) · [Bound checker soundness](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_domain_exprs.v#bound_expr_allows_sound)

The frontend checks up to 256 pairs of demand and allowance polynomial
alternatives per symbolic `NatBound` obligation. Each demand alternative
needs an allowance alternative whose polynomial coefficients bound its own.
Above the limit, the frontend reports an unresolved obligation at the
affected binder before expanding the joins. Expressions without joins use
the direct polynomial check.
[Expansion budget controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_symbolic_bound_comparison_budget)

Symbolic `NatExact` checks agreement of the two branch demands before using
their common demand. Rocq accepts equal polynomials such as `q + r` and
`r + q` and reports an obligation at the affected binder when equality fails.
[Exact branch controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_symbolic_exact_branches)

For natural grades, Rocq checks that a symbolic sum match has positive demand
under every assignment. Addition, multiplication and bounded branch maxima
are monotone, so a positive demand at the all-zero assignment establishes the
premise. A demand such as `q + 1` passes, and `q` leaves a located obligation
at the match. For the finite-carrier modal domains (`Presence`, `Linear`,
`Affine`, `SecurityLoHi`), Rocq checks symbolic sum-match demands with the
decidable all-zero monotonicity checkers (`gexpr_nonzero_presenceb`,
`gexpr_nonzero_linearb`, `gexpr_nonzero_affineb`, `gexpr_nonzero_securityb`)
and their zero-axiom soundness theorems (`gexpr_nonzero_*_sound`): expressions
that vanish at zero (such as bare `q`) fail with a located `grade` error,
while provably nonzero expressions (such as `q + 1`, `LOne + q`, or `true`)
pass. Custom `domain` declarations without built-in nonzero theorems still
receive an `unsupported` refusal.
[Sum demand replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_modal.py#_symbolic_sum_demand) · [Finite-domain nonzero checkers](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_domain_exprs.v#gexpr_nonzero_presence_sound)

When `<grade q : D>` grade variables are in scope, `check-grades` structurally
compares inferred and expected types across `Box`, `Fn` arrow domains and
codomains, dependent pairs, `Vec` indices, records, and sums
(`_collect_symbolic_type_obligations`) and replays the resulting symbolic
equality (`@gexpr_eqb`) and subgrading (`@gexpr_allowsb`, `bound_expr_allowsb`)
obligations in Rocq (`source_symbolic`). Returning `Box<Nat, q>` where
`Box<Nat, r>` is declared is refused, while valid subgraded weakening and
dependent substitution replay cleanly in Rocq. Generic records parameterized by
`<grade q : D>` substitute concrete and symbolic grade arguments into their
field allowances during both construction and `let`/`match` pattern-demand
checking.
[Symbolic type correspondence](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_modal.py#_symbolic_type_correspondence) · [Generic record grade substitution](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_generic_record_grade_substitution) · [Graded frontend record](../../assurance/completion-log/#q25bj-reconstruct-checked-graded-domain-evidence)

Use `--infer-grades` to infer omitted local grades and `@ _`
placeholders, including parameter allowances, before replay. The `derive-combinator` and
`synthesize-graded` commands exercise bounded derivation and search.
[Grade inference replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_inference.py) · [Derived combinators](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_combinators.py) · [Grade-directed synthesis](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_synthesis.py)

Bounded natural inference propagates lower bounds through inequalities between
metavariables, including constant offsets on either side. For `3 <= a` and
`a + 2 <= b`, the least assignment is `a = 3`, `b = 5`. A positive offset cycle
has no finite assignment. Conflicts retain the source constraints that
contributed to the bound, and propagation counts against the solver budget.
Ambiguous arithmetic remains an explicit obligation. Replay checks that the
Rocq certificate binds the original constraints, domain, assignments and
theorem inventory before checking the proofs.
[Bound propagation and replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_inference.py)

Separate Rocq trials cover metatheory, call-by-value erasure and skipping
substitution when the type-use row establishes zero demand. The locked client
replay checks the projected callable and record interfaces against an importing
client. The extension qualification governs the remaining correspondence duties.
[Metatheory](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_metatheory.py) · [Erasure replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_cbv.py) · [Zero-type-use benchmark](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_q25cb_zero_type_use_skip_and_benchmark) · [Client replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py) · [Extension qualification](../../extensions/graded-foundation/#extension-selection-and-qualification)

In the mathematical `Span<byte>` model, an argument that writes through nested
loans supplies a record extent with zero computation demand. A later argument
reborrows the same byte in the owner after both loans restore and reads the
first write.
The checked exact and bounded consumers erase the extent while retaining its
type dependencies. Rocq checks the result, ordered restoration, frame and
writeback, including failure during either argument. A first-argument
failure skips the reborrow.
[Reborrow replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_metatheory.py#_source_scoped_record_reborrow_replay)

An exact and bounded sum consumer keeps the selected alternative when it
erases a box payload that indexes the parameter and result types of a vector
callback. The other alternative uses its payload twice. Rocq checks both
results against the checked source and preserves scoped writeback, owner
restoration and the untouched frame, including an argument failure before
the sum is opened.
[Sum replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_metatheory.py#_source_scoped_sum_replay)

## Client upgrade replay

`python tools/run.py holdfast-parser check-upgrade old.hf new.hf --client client.hf`
compares revisions of one named module. Repeat `--client` and `--dependency` as
needed. Each client must transitively import the module. Success records SHA-256
for both revisions and all fixed sources. Failure names the revision, module
and position. Clients can rely on exported proofs, public `definition` equations
and `const` static computations. Imported ordinary function bodies and
post-state computations are opaque.

Nested imported calls match instantiated premises against local proof context
and call guarantees in the goal, within the elaboration budget. A provider
promising positivity can feed a function requiring and preserving it. The
proof uses both public theorems with both bodies opaque. A function that
returns a callable contracts the original call. Applying its result still
requires a witness for each premise.

The result covers the supplied clients in this mathematical fragment. The
[release contract](../../language/first-release/#public-api-evolution) also
accounts for separately compiled consumers, ABI, and replayed kernel evidence.

## Supported mathematical increment

Elaboration checks exact syntax bytes under work and reduction budgets and emits
hygienic Gallina names. Unresolved types, obligations and unsupported constructs
yield located refusals.
[Surface grammar](../../language/surface-grammar/) · [Elaborator](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/elaborate.py)

### Types, calls and proofs

- Generic telescopes can bind types and ghost values. The elaborator keeps
  parameters rigid inside the declaration and instantiates them explicitly or
  through bounded unification at calls. Mathematical `definition` bodies
  can compute with ghost indices. Executable bodies cannot use erased values or
  specification-only operations.
- Predicative `Type` and `Type<n>` levels 0 through 8, dependent
  `Fn` signatures, type-valued parameters and computed types use
  capture-avoiding substitution. Universes must match exactly. Proof
  polymorphism uses an explicit `<P : Prop>` binder.
- Expected types guide lambdas, immutable locals, tuples and omitted generic
  arguments. `_` requests inference. Unresolved or escaping metavariables
  fail the check. Calls keep their declared arity, so `Fn() -> Unit`
  and `Fn(Unit) -> Unit` are distinct.
- A call can use a positional prefix followed by labels in declaration order.
  The checker instantiates types and preconditions left to right. Named
  `Fn` parameters can accept labels. A function passed to a plain
  callable type must accept any argument allowed by that type.
- The prototype checks unary effect-free contracted callbacks supplied as
  named functions or contracted parameters. Their requirements and guarantees
  must satisfy the receiving contract. Aliases, captures and nonempty callback
  effects need the broader callable checker.
- `requires` and multiple `ensures` clauses express assumptions
  and guarantees. Proofs can use immutable locals, existential witnesses,
  inductive matches and `assert ... by` with a term, tuple of facts or
  block. Equality in expression position returns `bool`. Equality in
  proposition position denotes an equality proposition.
- Natural recursion on a smaller `Succ` binder lowers to Gallina
  `fix`. Definitions and functions can name the decreasing parameter.
  Recursive calls must retain the generic arguments and fully apply the
  recursive definition. Represented packet calls must form an acyclic graph.
  [Proof replay](#commands-and-acceptance) · [Packet qualification](../../language/first-release/#first-slice-qualification)

### Values and control flow

- The mathematical carriers include `Nat`, `bool`, Unicode scalar
  `char`, `Unit`, fixed-width words, products, `Vec<T, n>`
  and `Seq<T>`. Structural equality also covers non-dependent nominal
  records and unions. Word operations use the declared width in literal and
  conversion checks. Partial operations need bounds such as masks, widenings,
  branch guards or explicit requirements. Wrapping, saturating and checked
  variants are available where defined by the primitive. [Primitive semantics](../../language/first-release/#primitive-semantics)
- Regular and raw UTF-8 literals lower to byte vectors of at most 256 bytes.
  `TextBuilder<capacity>` supports the format specifiers `:x2`,
  `:x4`, `:x8`, `:d` and `:b`. A symbolic `byte` or `u8` with the
  default or `:d` format contributes one to three decimal digits. The `:b`
  format emits one to eight binary digits. Both formats spell zero as `0`.
  When used with a byte
  vector, the caller proves `ValidUtf8(bytes.Model)`. Interpolation holes
  evaluate once from left to right under the builder loan before the capacity
  check. Exhaustion sets `Fits` false and preserves prior bytes.
  [Bytes and text](../../language/first-release/#bytes-and-text)
- Typed required-static constants use earlier constants and pure calls on
  static arguments or parameters. Their dependencies must qualify before
  reduction, including those in dead branches. Runtime calls to `const`
  functions are permitted. Their `const` parameters must receive static
  arguments, including through callable values.
  [Required-static rules](../../language/surface-grammar/#required-static-constants) · [Frozen tables](#frozen-static-tables)
- Exhaustive matches cover the supported scalars, natural vectors, products,
  and nominal records and unions. Patterns can use literals, tuple and
  constructor patterns, declaration-order labels and bounded `Nat`
  patterns. A match can state a dependent motive with `as name : Type`.
  Irrefutable product and record patterns also work in `let` bindings.
  The mathematical checker also accepts nonrecursive unions with uniform type
  parameters, one trailing `ghost Nat` index, and an explicit constructor
  result for every constructor. Indexed matches use a direct scrutinee and an
  expected type in `Type<0>` or `Prop` independent of the scrutinee. The
  expected type can mention its surrounding index. The case tree rejects a
  missing possible constructor and emits a contradiction proof for each
  impossible branch. A named or computed value can be transported in either
  direction across a checked branch index equality, including one obtained by
  projecting equal successors. For example, a callback can take an enclosing
  vector at the constructor's index and return a vector at the enclosing index.
  Contextual checks of tuple components, conditional results,
  callback bodies and nested matches retain that equality. Nested matches can
  compose constructor equalities when a computed result depends on more than
  one refined index, such as the sum of two vector lengths. Each equality is
  scoped to its branch. The composed search bounds the number of intermediate
  types and reports exhaustion at the branch expression.
  [Indexed match fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/indexed-union.hf) · [Rocq replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_indexed_union.py)
- Conditional expressions, pattern tests and `let ... else` carry
  facts and bindings into the appropriate branch. Postfix `?` propagates
  through the checked two-variant `Option<T>` and `Result<T, E>`
  shapes, including in a short-circuited operand. Extract earlier sibling
  calls, moves and blocks to locals before propagation. Compound pattern tests
  in Boolean expressions require read-only calls. Executable bodies must
  handle or explicitly transfer `Result<T, E>` values on each
  reachable path. Proof assertions supply no runtime handling credit.
  [Pattern scope](../../language/surface-grammar/#pattern-test-scope) · [Failure semantics](../../language/reference/#errors-and-failure)
- Mutable locals, fields and indexed targets support assignment and compound
  assignment. Non-terminal branches carry the new state into subsequent
  statements. Bounded `foreach` and `while` loops support checked
  invariants, decreasing measures and exits in the supported fragment.
  Symbolic ranges use folds, counters and contiguous fill rules. Symbolic
  `while` uses a decreasing bound as fuel. Some early exits and
  writebacks require explicit control flow.
- The `|>` pipeline binds its left operand once as the value of `$`.
  The placeholder works in calls, labeled arguments and expressions, including
  `move $` and `in $`. A `using let` or `using var`
  declaration schedules disposal in reverse declaration order on fallthrough,
  early return and propagation after initialization. The checker refuses
  escaping borrows, moves or returns of managed resources and loop exits that
  cross a `using` boundary. [Scoped cleanup](../../language/first-release/#scoped-cleanup-and-receiver-calls)

### Nominal types, resources and modules

- Nominal records use ordinary products or dependent pairs in Gallina.
  Properties are read-only, and record methods can use an implicit receiver.
  When changing a field with `with`, include fields whose dependent
  types change. A `distinct Name = T` wrapper has a transparent Gallina
  carrier and its own constructor, `Value` projection and optional
  invariant and members.
- Record construction and updates establish invariants. An `open` block
  can lift selected invariant clauses for an update. The block must restore
  them before completion and refuses an early exit. Proofs over a record receive
  its invariant as a premise, and
  successful initialization establishes it for an `out` parameter.
- The `Span<byte>`, `Slots<T, capacity>` and pure sequence carriers
  expose abstract models, checked indexing, slicing and updates in their
  supported fragment. Vector reads use a proof-backed `Fin` index.
  `old(...)` selects entry-state facts, and a `ref` span or slot
  parameter automatically preserves its descriptor. General deferred
  `restores` predicates are unsupported.
  [Resource and loan semantics](../../language/reference/#loans-and-parameter-modes)
- Slot relocation splits the checked operation into
  `CopyRepresentation` and `TransferType<T>`. The checker uses
  region-wide bounds and vacancy facts independent of capacity. Moving an
  initialized region requires source write permission, and publishing the
  initialized destination prefix requires read permission.
  [Relocation contract](../../language/first-release/#relocation-and-storage-reuse)
- Path-sensitive initialization tracks `out` parameters through
  branches, loops and exits. Reads and partial mutations need a prior
  initialization. `ensures` observes the final value. A standalone
  `Unit` call can introduce a fresh `out var` through a concrete
  update.
- Ownership transfers require `move`. Shared and exclusive loans
  restrict conflicting access until their last use and permit access to
  disjoint sibling fields. Mutations invalidate overlapping mutable facts and
  preserve checked snapshots and disjoint facts. Receiver reservations for
  implicit `ref` interface calls and `slots.Write(...)` can permit
  temporary reads while evaluating arguments and check remaining overlaps at
  activation. [Borrow analysis](../../language/core-design/#borrow-analysis-promotion) · [Two-phase receiver borrows](../../language/core-design/#two-phase-receiver-borrows)
- Closed effects track reads, writes and calls. Named effect sets can combine
  entries, prohibit effects and bound a local block. Private functions and
  methods and package-internal functions infer from checked calls, receiver
  access, invoked callback parameters and callable fields. Structural
  self-calls can reuse the body's footprint when effect-bearing arguments
  keep their identity. Inference tracks transient writes and resolved call
  identities across imports. A concrete interface call, including implicit
  `IDispose.Dispose` on scope exit, uses the selected implementation's checked
  footprint within the locked package. Dispatch through a generic witness or
  an external instance without a published footprint cannot establish a
  closed bound. Release exports publish authored bounds.
  [Package effect contracts](../../language/first-release/#package-effect-contracts)
- Explicit nonoverlapping interface implementations check requirements,
  guarantees and abstract proof laws. `where T : ISized` supplies a
  checked dictionary for static or receiver dispatch. Blanket and computed
  implementation heads are unsupported.
  [Interface resolution](../../language/first-release/#interface-constraints-and-dispatch)
- Plain, aliased and selective imports resolve across an acyclic module graph
  with checked visibility. Emission distinguishes lookalike module spellings,
  including `A.B` and `A_B`. Locked source provenance follows the
  defining module, including through private helpers.
  [Locked packages](#locked-mathematical-packages)

## Natural arithmetic

`Nat` subtraction, division and remainder need checked premises. For
`total - used`, `requires used <= total`, closed operands or branch facts
can prove the bound. Missing premises point to the operation.
`Nat.SaturatingSub(a, b)` is total. Unconstrained function values still
check partial operations in their bodies.
[Natural operation rules](../../language/reference/#expressions-and-operators)

## Frozen static tables

A mathematical `const` stores static scalar or nested vectors or UTF-8 byte
strings. Its initializer requires empty transitive effects across helpers,
receivers, both branches and callbacks. The 64-slot budget counts every level,
so two 31-element rows use 64 slots. Symbolic initializers evaluate at closed
specialization.

Emission includes a `_freeze` equality checked by Rocq conversion and
a `holdfast_freeze_observe` transport term. Locked builds bind the
frontend, parser, target and transitive sources.
[Locked builds](#locked-mathematical-packages)

## Commands and acceptance

Run `holdfast-parser elaborate SOURCE` to parse and elaborate a module.
Use `--output FILE` to publish atomically after validation. Publication
refuses source aliases and preserves the existing output on an elaboration
error. The playground console uses the bounded closed-expression evaluator.
[Playground console](../playground/#dependent-mathematics-increment)

Run `holdfast-parser elaborate-qualify` to build the pinned parser and
replay the examples and independent controls in the locked Rocq environment.
The replay checks Gallina against the minimal CIC profile, compares canonical
statements, audits assumptions and runs `rocqchk -silent -o` in a scrubbed
environment. Refusal controls must reach their intended semantic failures.
The report binds the source, parser, elaborator, proof tools and OCaml, Zarith
and GMP runtime. A late input change withdraws the receipt.
[Kernel qualification](../../assurance/verification-strategy/)

The composed Span fixture holds a read-only slice live across a disjoint
owner write. It passes the observed bytes through a graded function whose
length indexes its input and output vectors with zero computation demand,
then selects an element with a bounded index. Rocq checks both selections
and the caller's post-state. Three source edits exercise an insufficient
grade, a mismatched index and a write overlapping the live slice.
[Replay fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/elaboration_check.py#fixtures)

The indexed variant selects a different read-only slice on each branch and
updates a disjoint owner byte before reading the slice. Each indexed-union
arm transports the sampled vector to its constructor's extent before calling
the exact-grade function. Rocq checks the selected byte and all three owner
bytes for both branches. The nearby refusals change the computation allowance,
the constructor-specific extent or the write's byte offset.
[Replay fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/elaboration_check.py#fixtures)

Each `assert`, including its `by` steps, emits a span-indexed
Gallina definition for the assumption audit. The natural-bound checker
combines comparisons in scope, including negated guards, through Rocq
monotonicity and transitivity lemmas. Inside the true branch of
`if (n < 5)`, it can derive `n <= 4`. In the other branch, it
can derive `5 <= n`. An arithmetic assertion can also use a bound
obtained by adding or canceling a common addend. The checker tries up to
256 candidate joins per assertion. Exhaustion leaves an outstanding
proposition at the assertion, where an explicit `by` proof can supply
it.

Inline `Nat` comparisons that need several bounds can use an affine
fallback. It searches for nonnegative integer weights that combine scoped
inequalities and the negated assertion into a contradiction. The generated
Gallina term applies the weighted inequalities and checks cancellation of
the symbolic coefficients in Rocq. It uses the evidence for the actual
guard arm, including strict and false comparisons.

The fallback allows up to 256 pair combinations per assertion and bounds
the input size and certificate weights. It reduces addition, successors
and multiplication by small constants. Literals above 256 and products of
symbolic terms are opaque, so they can cancel when identical. If the
relaxation yields no certificate or the search exhausts its budget, the
assertion needs another proof. [Proof search and replay under change](../../assurance/workflow-contract/#proof-search-and-replay-under-change)

Equality and propositional checks also use bounded e-graph saturation,
reflective natural semiring normalization and propositional search. A
`by (h1, h2, ...)` proof can supply several facts. The generated term
is the subject of replay.

A guard on a stable immutable local can contribute a scoped Boolean equality
when its initializer is an unreduced conditional or match. An explicit `by`
proof can use literal `Nat` and `bool` equalities to specialize fixed-result
matches in its obligation. It composes the resulting equality proofs with
the existing bound reconstruction. Mutation, joins, missing premises and
exhausted search cannot supply an equality witness.
[Refinement and normalization controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_refinement_normalization.py)

Run `holdfast-parser check-arithmetic SOURCE` to replay the supported
word-operation equations. Each emitted theorem equates a checked operation to
`Ok` of the ordinary operation, including shift-count checking for
`WrappingShiftLeft`. The replay covers closed operands at all widths,
exhaustive one-byte symbolic cases and supported wider symbolic operations
under checked guards. Wider cases include signed and unsigned addition,
subtraction, quotient and remainder, signed negation, and supported shifts.
Named scalar constants can supply word operands and comparison bounds.
For an unsigned `ShiftLeft` of a widened byte by a literal count, the replay
checks the count and result bounds and proves checked and ordinary execution
agree for every byte, including bytes read from a span.
The replay also proves unsigned multiplication of a losslessly widened word
by a constant when the full source range fits after scaling, in either operand
order.
Unsupported operands receive no equation verdict.
[Replay fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/elaboration_check.py)

### Elaboration performance trials

Run `holdfast-parser trace-elaboration SOURCE --measure-terms` for an input-bound
report of definition unfoldings by source declaration. The optional term
measurements distinguish expanded tree size, existing object sharing and
structurally distinct terms. The report records truncated data and located
refusals. Run `holdfast-parser benchmark-elaboration --replay-rocq --conversion-trial`
to compare generated dependent workloads and replay accepted outputs. The lazy
comparison trial interleaves unfolding and structural comparison on closed pure
terms. The standard elaborator continues to make the compilation decision.
[Performance controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_elaboration_trace.py)

## Named goals

The native checker reports `?name` sites with an expected type and the
local context, including branch facts, loans and the enclosing return type.
For example, `assert n == 4 by ?bound;` expects `Eq(Nat, n, 4)`.
Other sites can constrain the inferred type. Earlier errors can leave an
incomplete report. Inspection is limited to 128 sites and 65,536 UTF-8 bytes.

Outstanding goals block compilation, evaluation and package builds. The
playground ties reports to the active buffer. Goal inspection retains the
obligations imposed by copying, cleanup and returned views.
[Playground reports](../playground/#browser-behavior) · [Diagnostic contract](../../language/core-design/#typed-holes-and-invalidation)

Run `holdfast-parser motive-preview SOURCE --line N --column N` at the start
of a failing Boolean expression match with two unguarded arms of distinct
literal types (`Nat` and `bool`). The preview constructs a type-valued match
using the existing motive syntax, checks the entire edited source and replays
the generated Gallina in Rocq. It returns one byte-range insertion bound to the
source, candidate and compiler identities. Consumers revalidate a retained
preview against the current source before applying it.
[Motive preview controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_motive_preview.py)

## Locked mathematical packages

The batch builder composes `math-2` packages for the
`rocq-gallina` target. Each package manifest lives at
`<name>/<revision>/holdfast-package.toml` and declares its modules,
dependencies and inputs relative to the package. A lock binds those manifests
and exact files, the selected revisions, the parser and elaborator, and the
target configuration.
[Example manifest](https://github.com/symbiogenesis/HoldFast/blob/main/examples/packages/scale/v1/holdfast-package.toml) · [Package contract](../../language/first-release/#modules-and-packages)

```console
python tools/run.py holdfast-parser lock-package examples/packages scale v1 --output scale.lock
python tools/run.py holdfast-parser build-package examples/packages scale.lock --output scale.json
```

Dependencies must resolve to one revision per package. A module can import
from its own package or a direct dependency. Instance digests distinguish
nominal declarations across package closures. The builder checks missing
inputs, undeclared imports, ownership collisions, cycles and stale locks,
then rereads inputs before publication. It also checks canonical layout for
the root package. [Locked package authoring](../authoring-tools/#locked-package-authoring)

The optional bundle maps full module names to generated Gallina and binds the
ordered module, lock, source, instance and output digests. Limits are 64
packages, 256 files, 16 MiB of input and 32 MiB of Gallina.

Use `build-package --linked-proofs --output FILE` to export a linked bundle.
Its `files` entries give the Gallina source bytes as UTF-8 text. Write them to
the named files and compile them in `file_order`. Each module has one file and
imports its dependencies and the versioned shared prelude. The bundle binds
the prelude digest and the source, instance and output digests per module.
The default export keeps each module independently replayable.

Package assurance compiles the linked graph and audits every emitted export
against the same closure. The provider's body is available to its own proofs.
Importers use its published contracts at the same opacity boundary as the
standalone export. The kernel checker separately checks the compiled graph.
[Package assurance](../../extensions/assurance-profiles/#composition-across-mixed-assurance)

`holdfast-parser compare-package-evidence` accepts `--match-theorems` to find
possible matches among changed, added and removed public theorem statements in
the same module. The supported fragment covers closed equality statements with
up to five independent scalar binders. The matcher canonicalizes binder
order, equality symmetry and left-neutral natural addition. Rocq replay checks
both implications between the exact emitted propositions. With `--no-replay`,
the report identifies candidates. Package compatibility and assumption review
still use the original locks, declarations and client evidence.
[Package review contract](../../assurance/workflow-contract/#reviewing-a-public-contract-change)

### Retained caller proof trial

```console
python tools/run.py holdfast-parser qualify-retained-caller
```

The trial elaborates a generic caller against a locked contract and saves its
exact Gallina proof unit. Two separately locked providers implement the same
claim with different data representations. Each replay binds the original
caller unit and selected provider unit to the same contract, keeps the provider
implementation opaque, and applies the caller theorem to the provider's
conformance proof. Rocq and `rocqchk` run with proof caches disabled. The report
records the caller, contract and provider digests, kernel assumptions and
refusals for changed caller sources or proof bytes, a changed contract, an
incorrect provider pin and a provider that supplies the wrong claim.
[Package evidence contract](../../assurance/workflow-contract/#reusing-a-retained-caller-proof)

## Try the mathematical fragment

Run these commands from the repository root. On Linux use `python3`.

```console
python tools/run.py holdfast-parser elaborate examples/dependent.hf
python tools/run.py holdfast-parser elaborate-qualify
```

The dependent example infers vector lengths and type arguments, passes and
returns higher-order functions, and uses `Fin` to check vector lookup.
Its proof blocks use `assert` and `by`. It also shows how to pass
an equality proposition with `type[Eq<T>(left, right)]`.
The first command prints Gallina. The second runs the kernel replay suite.
[Dependent example](https://github.com/symbiogenesis/HoldFast/blob/main/examples/dependent.hf)

The bounded word counter borrows a validated UTF-8 input for each lookup.
With three bytes of key storage, `red`, `red`, `blue`
records two occurrences of `red` and returns `KeyBytesFull`
for `blue`, leaving existing keys and counts intact. Other replay
cases cover input reuse, two-slot exhaustion and a two-byte UTF-8 key.
[Word counter](https://github.com/symbiogenesis/HoldFast/blob/main/examples/word_count.hf) · [Represented storage](../../language/first-release/)
