HoldFast compile-time metaprogramming
Design for typed introspection and hygienic compile-time generation. Implementation plan
Product and scope
The first release uses total pure computation for required-static constants and finite specialization. Each library derivation needs a client and an independent input/output contract. First-release boundary
Broader introspection, derivation and hygienic construction of definitions and evidence need a named client, measured authoring or maintenance gains over ordinary libraries, and composition proofs for the selected features. Clients call generated APIs normally. Navigation, diagnostics and inspectable output expose generation.
The mathematical prototype checks type-valued parameters, computed types and bounded definitional computation. General introspection and generation need checked descriptors and construction. Prototype · Frontend admission
Evaluation and phase boundaries
Use total pure functions for mathematical computation, types, static values
and generators. Check generics symbolically under declared static requirements.
Each demanded specialization requires admissible closed inputs before emission.
Unavailable inputs leave a located goal or refusal. Infer static arguments from
the interface and declare public requirements explicitly. const T Name = EXPR;
requires a static value. Call const T F(...) statically or at runtime.
const U configuration requires a static argument at every call. A local
constant can compute a plan for the enclosing runtime function.
Required-static grammar
Dependent callable telescopes and inferred or explicitly typed lambdas retain static parameter requirements. Partial application keeps requirements on remaining inputs. Reject conversion to a runtime-parameter callable if it would let callers omit a required static argument.
public const Nat Square(Nat value) => value * value;
public Nat ApplyGain(const Nat gain, Nat sample) {
const Nat multiplier = Square(gain);
return multiplier * sample;
}
public const Nat Gain = 4;
public Nat Process(Nat sample) => ApplyGain(gain: Gain, sample: sample);
Process combines a static multiplier with runtime samples. A runtime sample
cannot supply gain, even to a helper that ignores it. Constant initializers
can call admitted total pure helpers. The frontend freezes scalar and nested
vector tables, including UTF-8 literal bytes, and proves conversion to their
declared interpretation. Frozen static tables
Required-static availability is independent of the foundation's dimensions:
| Distinction | Rule |
|---|---|
| Stable versus static | An immutable runtime length is stable enough to index a result, but unavailable to a build-time layout calculation. |
| Static versus erased | A computed table can be retained at runtime; an erased proof cannot supply a runtime value. ghost alone neither requests nor establishes static evaluation. |
| Static versus graded | A use allowance constrains its interpreted demand, not when a value becomes available. Grade zero does not erase an argument's effects. |
| Static versus owned | A type or resource description conveys no live memory permission, CHERI capability or protocol token. |
| Definition versus generated program | The generator's evaluation is distinct from executing the program it constructs. Quoted or constructed target operations are not performed by inspecting their syntax. |
Kernel conversion runs admitted total pure definitions under CIC's universe and equality rules. Introspection reads frontend metadata outside conversion. Bounded proof search and untrusted generators propose terms for ordinary checking. Timeouts leave unresolved goals and block build acceptance.
Static computation uses mathematical or declared target integer semantics. Widths, endianness, layouts, capability formats and ABI come from the target description. Runtime constants, including specialized mathematical values, need checked finite representations.
Two-Level Type Theory and closure-free staged compilation inform the separation between static computation and first-order systems execution. A HoldFast lowering must show that each specialization preserves typing, behavior and resources. Staging design references · Mode and effect specialization
Typed introspection and derivation
Provide typed descriptions of the supported type and declaration forms, with
qualified identities, universe levels, parameters, constructor/field structure
and the relevant public contracts, grades, effects and capture requirements.
Each descriptor binds the exact declaration and interpretation it describes.
Descriptors are data for ordinary computation; a generic type parameter alone
grants no structural inspection or assumption that every type has a finite schema.
Obtain a descriptor through explicit compiler reification or an opt-in schema
dictionary, checked against that declaration. This is not a CIC function that
eliminates arbitrary Type into syntax, decides function equality or reflects
universes by adding an axiom.
Introspection obeys module boundaries. A defining module can derive over its own representation and export the resulting abstract API and laws. A client sees only the published description or an explicit derivation interface; opting into a derivation does not export otherwise private fields. Opaque types remain opaque. Describing a nominal type cannot reconstruct another type with its identity, prove arbitrary type equality, or introduce a representation-changing cast.
Derivations use coherent qualified library implementations and explicit format or
policy descriptions. Adding an unrelated import must not change the selected
implementation. Equality, visitors, optics, codecs and finite registries expose
their generated definitions and requested laws through the normal module system.
Declaring a derivation does not make its laws definitionally true or established.
Mandatory safety judgments and the selected
assurance policy
apply exactly as they do to handwritten code. Every generated exported contract
must be discharged before its interface is accepted. Exploratory unproved claims
stay in the separate non-exported scratch channel; they cannot justify
optimization, a caller's proof or an accepted requires/ensures declaration.
This proposed library API uses ordinary generic-call syntax.
let schema = Meta.SchemaOf<Packet<Capacity>>();
let codec = Meta.DeriveCodec(schema, wireFormat);
let specialized = Meta.Specialize(copyDefinition, Capacity);
Here Capacity and wireFormat are declared static inputs. A packet's discovered
length remains represented in the generated program. The format description fixes
the encoding independently of record layout. The codec must establish its requested
bounds, failure and correspondence laws, and specialization must establish its
preservation obligations. Production parsers follow the
required Narcissus lowering
and independent descriptor review.
Frozen schema-1 description protocol
meta_descriptors.py freezes the
schema-1 typed introspection protocol (DESCRIPTION_PROTOCOL_SCHEMA = 1) over
TypeDescriptor, FieldDescriptor, VariantDescriptor, and
DescriptorRegistry:
- Reification and privacy:
reify_module_descriptorsparses HoldFast declarations and constructs nominal descriptors (type_id = "<module>.<name>") bound tosource_sha256and canonicaldescriptor_sha256. Cross-module requesters receiveopaque = Truewith private fields, private-union constructors, and private contracts withheld. - Protocol freezing:
freeze_description_protocolvalidates schema version, nominaltype_id, privacy opacity, deterministicdescriptor_sha256recomputation, andDescriptorRegistry.lookupinvariance when unrelated imports are registered before or after the target descriptors, sealing the snapshot withprotocol_sha256. - Codec derivation:
derive_indexed_codecandqualify_codec_derivationin meta_construction.py validateWireFormatagainst the frozenPacketdescriptor, derive and elaborate the codec throughHygieneScopeandelaborate.elaboratewith zero solver axioms, emit freestanding C11 viaemit_codec_c11, and verify-O0/-O2execution (and optional VerifiedOSccomp) against an independent wire-byte oracle and mutually-agreeing wrong-codec controls.
Hygienic construction and composition
Provide scoped typed construction of expressions, declarations and proof terms. Typed quotation/splicing may be an ergonomic frontend to these builders after its syntax and laws qualify; textual substitution is insufficient. Each open fragment records its binder telescope, expected type, stage, representation, effects, transitive captures and resource entry/exit obligations. Substitution preserves binding, dependency, universes and those obligations. Generated names are fresh and deterministic; intentional references use resolved qualified identities.
Open code may describe an operation requiring a linear input at execution. It does not possess that input while being generated. Duplicating syntax is valid only when checking the resulting program establishes the actual use, capture and resource account. A generator cannot embed a build-process pointer, live owner, loan, continuation or target capability as a runtime constant. Closed constants cross stages only through admitted representations and provenance checks.
| Interaction | Required preservation |
|---|---|
| Dependent types and universes | Construction/substitution preserves ordered telescopes, motives, universe constraints and explicit transports. No arbitrary solver result extends conversion. |
| Grades and erasure | Generated demand uses the selected lawful domain and its interpretation. Runtime indices/discriminants remain represented; proof erasure creates no disposal or zeroization operation. |
| Ownership and loans | Every generated use and transitive capture respects exclusive permission, lifetime, restoration and mandatory outcomes on every exit. Duplication of a descriptor grants no duplication of its referent. |
| Effects and evaluation | Preserve explicitly sequenced call-by-value evaluation. A zero-use parameter does not skip an effectful argument, and repeated use does not repeat its once-performed evaluation. |
| Handlers and async | Preserve handler delimiters, resumption allowances, checkpoint/commit placement, invariant closure, terminal collection and cleanup. Moving or cloning work across those boundaries needs the corresponding preservation laws. |
| Mutation and dependency | Depend on stable snapshots with justified validity. A generated accessor or cached fact cannot retain a claim about current mutable state after its validity ends. |
| Security and resources | Preserve requested relational observations, cost and storage bounds as well as functional results; specialization is not permission to declassify or drop failure paths. |
| Machine and hardware authorship | Generated state, schedules and RTL retain their admitted architectural/cycle interpretations, finite representations and independent refinement subjects. Shared generation supplies no hardware theorem. |
When a generator receives code for an effectful argument, it emits a binding
at the argument's original evaluation point in the generated program. Each
use refers to the bound value. For example, generating zero or two references to the value of
ReadAndAdvance(ref cursor) must advance the cursor once on either successful
path. If the read fails, both generated programs propagate or examine that
failure before subsequent work. Two uses of an owned value require its
duplication evidence. Test the trace, the final cursor, and each returned owner
for both generated programs under the call-by-value application rule.
Prove the selected extension laws over the checked elaborated term in its admitted interpretation. Establish correspondence with the exact source and supply the concrete resource laws required by the generated operations. Frontend admission · Concrete resource obligations
Published construction and evidence interface
meta_construction.py publishes the checked hygienic builder and receipt interface consumed by codec derivation:
TypedFragment: recordsexpr,type_repr,stage,ownership,effects,free_binders,binder_uses,captures,exit_obligations,dependent_telescope,node_count, anddepth.HygieneScope: enforces deterministic fresh naming (_hf_gen_0, ...), lexical containment (bind,child_scope,var,validate_fragment), dependentPi/Sigmatelescope construction (dependent_bindwith universe levels), sequential composition (compose_sequencepropagating captures, effects, andexit_obligationswhile refusing dropped linear obligations or discarded intermediate linear values), stage separation (lift_to_static), zero-authority descriptor copying (duplicate_descriptor), and bounded generation (MAX_NODES,MAX_DEPTH).bind_cbv_argument: binds effectful arguments once at their evaluation point before 0-use or N-use bodies, preserving single evaluation and refusing linear duplication without evidence.DerivationReceiptandverify_derivation_receipt: seal and verifysource_sha256,descriptor_sha256,wire_format_sha256,generated_sha256,gallina_sha256,receipt_sha256, and zero-axiom minimal-CIC compliance without a proof-admission bypass.qualify_hygienic_constructionexercises all builder laws, refusals, and tamper checks end-to-end.
Reproducibility, evidence and diagnostics
A generation request seals its source closure, generator and library definitions, descriptors, selected instances, static arguments, target/ABI, options, declared external input bytes and relevant tool identities. No ambient filesystem, network, clock, randomness, environment lookup or runtime service execution is available inside static evaluation. Import external data through explicit build inputs before generation. Bound source/input sizes, evaluation steps, recursion, memory, generated declarations and output bytes; exhaustion fails with the bounded cause. Publishing is atomic only after complete checking of the selected output boundary.
A separately scoped procedural producer may use bounded local scratch storage when its accepted result is deterministic over the sealed inputs. Such storage supplies no target authority and cannot cross stages as a pointer or host-dependent representation. That producer's operational implementation stays outside kernel conversion; effectful target code remains constructed data during generation.
Record resolved dependencies and the generated terms, representation decisions, proof obligations and source maps in the source evidence package. Cache identities bind that complete closure; changed private layouts invalidate their derivations even when an exported name is unchanged. Cyclic generation, unresolved instances and recursive specialization without a justified finite closure remain unresolved/refused. Record input and output confidentiality where static specialization exposes information in artifacts or diagnostics.
Generated APIs remain navigable to both the invocation and the generator/library definition. Diagnostics identify the original invocation, expansion path, static arguments and first failed typing/resource/proof premise; retain the complete generated subject for inspection. Stale editor previews cannot become current build evidence. A generator shared with an oracle creates common-mode risk; independently reviewed intent, telling negative examples and the independent canonical machine subject retain their existing roles.
Runtime cost
Qualify erasure and specialization by showing that the emitted artifact carries no evaluator, introspection or construction machinery. Charge explicitly requested runtime schemas, registries and dictionaries for their representation, authority and execution. A failed static resolution stops specialization.
Generated algorithms still execute, use storage and can be inefficient. Compare equivalent generated and independently authored baselines on the same target: final code size, stack, allocation, memory traffic and execution/WCET where claimed. Report compilation, generation and proof-replay costs separately. Bound code-size growth and use checked sharing or specialization policies; unrolling everything is not a performance guarantee. Final-byte correspondence, constant-time and resource evidence remain the compiler's duties.
Compiler services and runtime information
Compile-time derivation covers many finite serialization, dispatch and registry uses of runtime reflection. Data or schemas first discovered during execution need explicit runtime descriptors, a confined interpreter or a later build; no compile-time construct makes unknown information available earlier. The native admission rules still govern executable updates.
Compiler services expose located syntax, resolved symbols, types, elaboration, dependencies, generated definitions and diagnostics to analyzers and tools. They complement static generation: refactoring and navigation also operate on partial source and whole workspaces. Reuse the same frontend services for the inspection and interoperability interfaces, with versioned concrete, resolved/typed, elaborated, analysis/proof and lowering views, bounded queries/exports and source/image identities. That contract owns public schemas, snapshot-scoped handles, partial-result status and consumer qualification. LSP, SARIF and SCIP consume projections of the same facts; compiler remarks and traces come from the passes and phases they describe. Workspace and debugger access follow the tooling authorization rules. Generated terms follow the ordinary proof acceptance rules.
Design references
These references guide the intended interfaces. Each mechanism still needs HoldFast's own interpretation, source correspondence and composition evidence; no source or dependency is incorporated, feature parity claimed or implementation commissioned.
| Reference | Design use |
|---|---|
| Zig 0.15.2 compile-time evaluation and type reflection | Ordinary functions at compile time and the @typeInfo/@Type metadata/reification interface inform static computation and explicit descriptors. Their availability establishes no CIC or ownership theorem. |
| Idris 2 elaborator reflection | Checking, quotation, declaration and fresh-name operations inform scoped generation and discoverable library APIs. HoldFast retains its own dependent, graded and resource-aware construction obligations. |
| Two-Level Type Theory (2LTT) (ICFP 2022, ICFP 2024) | Kovács's staging-by-evaluation separates dependent compile-time meta-types from first-order closure-free runtime code, informing zero-closure systems lowering of static abstractions without bypassing kernel correspondence. |
| Roslyn compiler API model | Syntax, symbols, semantic analysis, diagnostics and workspace services inform the shared tool interface. These services complement compile-time generation. |
Qualification
The delivery plan qualifies static computation with the initial software clients. Select later descriptor, construction or cross-feature rows only when a named consumer needs them; a synchronous derivation does not owe handler/async or hardware generation before it can be useful. General generation, compiler-service schema breadth and extensible graded interaction retain separately scoped budgets and stop decisions.
Qualify each advertised fragment with inhabited clients and independent, well-formed negative neighbors using the same supported mechanisms. A parse failure or missing feature supplies no semantic rejection. Retain exact source, tools, target, generated subjects and verdicts; documentation examples alone supply no executed evidence.
| Client | Required positive result and telling negative neighbor |
|---|---|
| Static computation and types | Compute a type family, table and finite specialization with declared target semantics; refuse a runtime-dependent layout, host-width substitution and over-budget computation without runtime fallback. |
| Indexed tagged-union codec | Derive over a bounded payload with represented runtime length, independently chosen wire bytes, failure cases and round-trip/canonicality obligations; detect an incorrect field order, missing length check and mutually agreeing but incorrect encoder/decoder. Preserve the required parser route. |
| Stages, grades and erasure | Retain a static table while erasing its proof; keep a discovered length represented. Refuse using ghost, zero demand or an idempotent grade to conjure a static operand, skip effects or duplicate authority. |
| Binding and abstraction | Generate nested dependent binders with qualified instances and an abstract module's permitted derivation; reject captured/escaping binders, private-field inspection, forged nominal identity and ambiguous selection. An unrelated import preserves the selected meaning. |
| Ownership and control | Generate bounded code with one owner, checked callback demand and cleanup across a handler/async path; reject duplicated captures, a lost mandatory verdict, repeated effectful evaluation and moved checkpoints/commits. |
| Freshness and tooling | Replay after a harmless local rename, then invalidate changed generator, private layout, format, instance, input and target dependencies; reject late editor results, stale output and forged source maps. |
| Artifact costs and runtime metadata | Show the evaluator/descriptors absent when not requested and account for explicitly retained metadata; detect hidden boxing, runtime derivation fallback, unjustified code growth and changed final bytes reusing old evidence. |
| Proof and machine boundary | Replay generated exported laws under every preset with exact assumptions and independent intended behavior; refuse unestablished exported clauses, scratch claims consumed as facts, unchecked holes, extra axioms and a disconnected source/output claim. A selected hardware extension retains independent architecture/refinement checks. |
| Existing owner | Work retained at that boundary |
|---|---|
core-soundness |
Phase separation, descriptor interpretation, hygienic substitution, dependent/graded resource composition and erasure laws. |
core-frontend |
Introspection and construction interfaces, required-static checking, coherent resolution, bounded generation and checked source/output correspondence. |
core-diagnostics |
Expansion provenance, inspectable output, semantic invalidation and the positive/negative client corpus. |
| Compiler/representation and whole-system stages | Static target semantics, finite specialization, growth bounds, exact artifact costs and final-byte/hardware preservation. |
| Editor/debug protocol stages | Versioned compiler-service consumption, generated-source navigation and exact-image mappings under the existing interoperability contract. |
The metaprogramming plan defines selection, owners and implementation prerequisites.
MetaHygiene theorem boundary
meta_hygiene.v (Module MetaHygiene)
proves 24 zero-axiom theorems inside the minimal CIC profile (without importing
graded_cbv_span_carrier), audited by Print Assumptions and rocqchk in
test_holdfast_metaprogramming.py:
| Theorem group | Kernel-checked theorems | Boundary |
|---|---|---|
| Nominal descriptors and coherence | type_id_eqb_refl, type_id_eqb_eq, type_id_eqb_neq, public_view_hides_private, client_view_hides_private, nominal_distinct_not_equal, coherent_lookup_prepend, coherent_lookup_append_some, coherent_lookup_append_absent, coherent_lookup_unrelated_import |
Captures nominal TypeId distinction, cross-module privacy hiding, and qualified lookup invariance under unrelated imports; does not model reflection over arbitrary CIC Type. |
| Hygienic substitution and staging | renaming_preserves_typing, subst_preserves_typing, cross_stage_leak_refused, cbv_let_bind_single_eval, descriptor_copy_zero_authority, closed_const_lift_sound |
Proves capture-avoiding renaming/substitution, refusal of runtime owned binders in static contexts, single-evaluation CBV cursor advance, zero-authority descriptor duplication, and stage-sound closed constant lifting. |
| Dependent telescopes and composition | dep_telescope_wf_preserved_by_rename, dep_telescope_subst_preserves_typing, hygienic_compose_preserves_effects_and_exits |
Proves renaming/substitution preservation for dependent Pi/Sigma binder rows with exact universe levels, and monotonic capture/effect/exit-obligation preservation under composition (refusing dropped obligations). |
| Indexed tagged-union codec | codec_roundtrip, codec_canonical, codec_rejects_oversized, codec_rejects_truncated, codec_rejects_bad_tag |
Proves roundtrip, canonicality, and malformed/oversized/truncated/bad-tag refusals over the abstract Packet wire model; concrete machine-level C/CompCert refinement beyond C11 -O0/-O2 and ccomp assembly compilation follows the target-lowering stages. |