# Pure HoldFast translation prototype

The pure compiler translates explicit `Nat` and `bool` functions and constants
to Gallina, which interprets accepted expressions as mathematical values.
The checked parser supplies syntax for resolution, typing, evaluation and
emission. Kernel replay, source correspondence and machine evidence have
separate checks. [Checked parser](../parser/#checked-parser-boundary) ·
[Wider mathematical elaborator](../elaboration-prototype/)

## Source fragment

Write return and parameter types before names, immutable locals with optionally
typed `let`, and required-static values with typed `const`. Functions use
return blocks or expression bodies. The pure checker marks contracts, grades,
effects, loans and machine representations unsupported.
[Wider surface grammar](../../language/surface-grammar/)

UTF-8 source accepts `//` comments and ASCII identifiers matching
`[A-Za-z_][A-Za-z0-9_]*` except keywords. Reserved extension keywords report
unsupported features. Decimals match `[0-9](?:_?[0-9])*` and allow leading zeros.
Parsed syntax keeps spelling and positions. Emission normalizes separators and
leading zeros. Each file has one named module with at least one function or
constant. The compiler resolves declarations in source order, so a call to
another function in the module must follow that function's declaration.

```holdfast-check
module Example;

public const Nat Twice(Nat x) => x + x;

public const Nat Limit = Twice(x: 8);

public Nat Scale(const Nat factor, Nat value)
{
    const Nat multiplier = Twice(factor);
    return multiplier * value;
}

public Nat Runtime(Nat value) => Scale(factor: Limit, value: value);

public Nat Select(bool flag, Nat x)
{
    const Nat fallback = Twice(x: 0);
    let result = Twice(x: x);
    if (flag)
    {
        return result;
    }
    else
    {
        return fallback;
    }
}
```

```text
file      := 'module' name ';' declaration+
declaration:= function | 'public' constant
function  := 'public' 'const'? type name '(' parameters? ')' body
body      := block | '=>' expression ';'
parameters:= parameter (',' parameter)* ','?
parameter := 'const'? type name
type      := 'Nat' | 'bool'
block     := '{' binding* exit '}'
binding   := 'let' type? name '=' expression ';' | constant
constant  := 'const' type name '=' expression ';'
exit      := 'return' expression ';'
           | 'if' '(' expression ')' block 'else' block
expression:= disjunction
disjunction:= conjunction ('||' conjunction)*
conjunction:= comparison ('&&' comparison)*
comparison:= sum (('==' | '!=' | '<' | '<=' | '>' | '>=') sum)?
sum       := product (('+' | '-') product)*
product   := unary (('*' | '/' | '%') unary)*
unary     := '!' unary | atom
atom      := decimal | 'true' | 'false' | name
           | name '(' arguments? ')' | '(' expression ')'
           | 'Nat' '.' name '(' arguments? ')'
arguments := argument (',' argument)* ','?
argument  := (name ':')? expression
```

Arithmetic and ordering take naturals; equality and inequality take two operands
of the same type. Negation, conjunction and disjunction take booleans.
A condition must be Boolean. The compiler checks both branches of a definition
against the declared return type, even when the condition is a literal.
An expression body checks like a single return and evaluates its expression
once. Nonempty parameter and argument lists allow
a trailing comma. A block ends with a return or returning conditional. Calls
must match the declared arity and argument types. A positional prefix may be
followed by a labeled suffix. Each label must name the next declared parameter. Reordered,
duplicate or unknown labels, omitted arguments and positional arguments after a
label are refused. Labels preserve once-only left-to-right evaluation and do
not change the emitted application. The supported qualified call,
`Nat.SaturatingSub(a, b)`, takes two positional `Nat` arguments.
Local annotations must match the initializer's
`Nat` or `bool` type exactly; unannotated locals infer it. Bare `type name = expression;`
locals are refused as syntax, directing authors to explicit `let`.
Duplicate functions, parameters, local bindings in an active
scope (including active parameters) and unbound values are errors. Function and
value namespaces are separate. Natural arithmetic and comparisons emit `Corelib.Init.Nat` operations.
Boolean equality emits nested conditionals. Types and constructors come from
`Corelib.Init.Datatypes`.
Constants follow the [required-static contract](../../language/surface-grammar/#required-static-constants):
their typed initializers evaluate from earlier constants and pure calls with
static arguments, under finite work and numeric bounds. The supported constant
types are `Nat` and `bool`. Unmarked runtime parameters and
ordinary outer locals are refused before evaluation, including ignored or dead
dependencies. Constants denote evaluated values and cannot be reassigned or
called. Compiler-recorded constant symbols support the existing editor services.
An ordinary local inside a pure function evaluated with static arguments belongs
to that evaluation; it is not an outer runtime dependency. Constants with machine
types such as `usize` require the wider selected-target interpretation and are
outside this pure prototype.

The function modifier records constant-evaluation support without restricting
runtime calls. A static parameter is checked symbolically in its definition and
requires a static argument at every call. Instantiation substitutes that argument
and computes the required local constants. The definition checks both branches
before instantiation, which computes local constants only in the reachable branch
when the condition is known. Ordinary data arguments retain their original order.
Forwarding a static parameter preserves its availability;
neither a ghost binder nor a runtime local acquires that availability implicitly.
Logical template definitions may retain symbolic static expressions; this host
prototype establishes no target erasure or source-correspondence theorem.

The return type is checked before Gallina emission. This complete example
reaches a type error at the Boolean result.

```holdfast-reject type
module ReturnType;
public Nat Count() => true;
```

Every user name is mapped to a generated identifier so Gallina keywords and
library names cannot capture source references. There is no raw Gallina escape.

The development frontend reports limit diagnostics for excessive source bytes,
block and expression nesting, binding depth or decimal-literal length. Target
resource bounds and integer widths belong to the target profile.

## Extended pure expressions

The [pure grammar](#source-fragment) defines precedence. Comparisons require
parentheses to nest. Repeated negation is permitted within the existing
expression bounds.

`!`, `&&` and `||` require Boolean operands. Equality and inequality require
two operands of the same supported type. Ordering and subtraction require
naturals. For `a - b` the checker establishes `b <= a` using a known
operand bound or a matching fact from a branch or short-circuit condition.
The true branch of `if (used <= total)` can return `total - used`. For intentional truncation,
`Nat.SaturatingSub(2, 5)` evaluates to zero. Both forms emit
`Corelib.Init.Nat.sub`. Ordering emits `.ltb` and `.leb`, while Boolean
negation and short-circuit logic emit conditionals. Reversed ordering
must preserve left-to-right once-only operand evaluation through fresh bindings.
All generated binders remain disjoint from mapped source names.

Both logical operands undergo name/type and required-static dependency checks,
including dead operands. Evaluation and emitted conditionals evaluate the left
operand once and evaluate the right only when needed. Thus
`false && (huge * huge == 0)` can avoid a static arithmetic limit, while
`false && runtimeFlag` still cannot initialize a required-static constant.
The evaluator applies its work, depth, output and numeric limits.

The [expression fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_expressions.py) check
expected values, emitted terms, refusal cases and original-source spans.
`holdfast-parser elaborate-qualify` replays independently expected constant
and runtime equalities with the kernel and assumption auditor.
[Playground examples](../playground/#extended-expression-examples)

## Boolean web output

Export one function from a checked pure module as a default ECMAScript module
function. For example, build the playground's `Changed` comparison, then
import the resulting file in an ES module. [Example source](https://github.com/symbiogenesis/HoldFast/blob/main/examples/expressions.hf)

```console
python tools/run.py holdfast-parser emit-web examples/expressions.hf Changed --output changed.mjs
```

```js
import changed from "./changed.mjs";
changed(false, true); // true
```

The selected public function takes zero to eight ordinary `bool` parameters and
returns `bool` in a single expression or return statement. The expression may use
its parameters, Boolean literals, grouping, `!`, `&&`, `||`, `==` and `!=`.
Every declaration in the file must pass the pure checker. Only the selected
function is exported. Calls with the wrong arity or a nonprimitive Boolean
argument return `undefined`. Parameters receive positional JavaScript names.
Equality uses strict Boolean comparison. [ECMA-262, 16th edition](https://262.ecma-international.org/16.0/)

For each export the [backend](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/web_output.py) runs the
exact generated bytes in the pinned Node.js executable on Ubuntu ARM64 or WSL.
Each Boolean tuple, in order from all-false to all-true, produces one primitive
result. For every tuple, `rocq c` checks an equality between the existing pure
Gallina interpretation and that observed result by conversion. `rocqchk`
independently checks the compiled library. The command then rereads the source
and atomically publishes the executed bytes. Its JSON result identifies the
source, exported function, JavaScript, Gallina, engine and Rocq switch and
includes the truth table. The correspondence covers this file and function under
the pure parser and Gallina interpretation.

The input limit is 65,536 bytes. The entry expression permits at most 128
syntax nodes within the pure compiler's depth limits. Its execution visits
at most those 128 nodes, with at most eight parameter type tests and one arity
check per call. The emitted module is at most 16,384 bytes. Qualification runs
at most 256 in-domain tuples, tests invalid callers, and allows ten seconds
for Node with a 32 MiB old-space limit and thirty seconds for each kernel tool.
The bounds describe this generated expression and qualification process.
Browser engine memory allocation and execution time depend on the host.

Run `python tools/run.py holdfast-parser qualify-web` to exercise four independent
truth tables and require the kernel to reject two changed JavaScript expressions.
[Runtime pin](https://github.com/symbiogenesis/HoldFast/blob/main/THIRD-PARTY.md#boolean-web-execution-engine) ·
[Qualified client](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/web_output_check.py)

## Natural division and remainder

Division `/` and remainder `%` take two `Nat` operands and return `Nat`.
They share multiplication's precedence and associate left to right.
For example, `20 / 3 * 2` is `12`, `20 % 6 * 2` is `4` and
`20 / (3 * 2)` is `3`.

The checker must establish a nonzero divisor. A nonzero literal suffices,
and the true branch of `if (size != 0)` can use `count / size` or
`count % size`. Accepted expressions emit `Corelib.Init.Nat.div` and
`.modulo` for the natural quotient and nonnegative remainder. The static
evaluator uses the same mathematical operations. Both operands are checked
and evaluated once in source order.

The [division fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_division.py) exercise
values, rendering, operand types and static dependency checks. Native kernel
replay also checks emitted terms. [Playground examples](../playground/#division-and-remainder-examples)

## Command and publication

Run `python tools/run.py holdfast check SOURCE` to check a file, or
`python tools/run.py holdfast emit SOURCE` to print its Gallina. Use `--output FILE`
to publish Gallina atomically after successful checking. The destination's parent directory must exist, and the destination cannot alias
the source. Diagnostics identify
the source position and the kind of failure. Formatting and lint behavior
follow the [authoring command policy](../authoring-tools/#compiler-commands-and-publication).

The emitter generates deterministic Gallina definitions with fully qualified
CIC operations. The source SHA-256 binds the exact input used for emission,
including formatted bytes after an explicit formatting write.
[Source correspondence](../../extensions/unified-source-contract/)

## Acceptance

Behavioral fixtures check expected translations, types, lexical scope, syntax
and resource refusals, exact source provenance and output publication.
The [parser comparison](../parser/#pure-parser-comparison) exercises both syntax
routes. [Kernel replay](../elaboration-prototype/#commands-and-acceptance) checks
generated terms and their assumptions. [Unified-source acceptance](../../extensions/unified-source-contract/)
governs production correspondence.

## Try the prototype

From the repository root on Windows (use `python3` on Linux):

```console
python tools/run.py holdfast check examples/pure.hf
python tools/run.py holdfast emit examples/pure.hf
```

The second command prints the Gallina definitions. To save them, add
`--output out/Pure.v` after creating the `out` directory.
The [example](https://github.com/symbiogenesis/HoldFast/blob/main/examples/pure.hf) defines a cube and a Boolean selection.
`Choose(true, 1)` evaluates to `true` and `Choose(true, 2)` to `false`. The
emitted `HoldFast_Oracle` module contains `f_Cube`, `c_Base` and `f_Choose`. The
[expression example](https://github.com/symbiogenesis/HoldFast/blob/main/examples/expressions.hf) adds Boolean
logic, comparisons and checked natural arithmetic. The playground console
evaluates closed expressions through the bounded static evaluator; kernel
acceptance requires the separate replay.

## Bounded compiler traces

For a packet compiler timeline, run
`python tools/run.py holdfast-parser first-slice --trace`. The receipt's
`compiler_trace` points to a Chrome Trace Event recording from surface
parsing through C lowering. It covers resolution, elaboration, Gallina emission
and three proof processes. Separate child tracks record the parent wait for
each proof process and identify its PID. The interval ends before the C
controls and Sail replay.

A complete packet recording has 12 events. Missing phases, clock faults,
cancellation and truncation fail validation. The receipt recheck verifies
the trace digest, event nesting, timings and child identities against the
bound source, outputs and proof-tool closure. That closure includes the
compiler and proof executables, loader dependencies, plugins and load roots.
[First-slice qualification](../../language/first-release/#first-slice-qualification) · [Trace format](../tooling-protocols/#compiler-decisions-and-performance-traces)

Run `python tools/run.py holdfast trace-qualify-packet-viewer --trace-processor PATH --output out/packet-viewer.json`
to import the deterministic packet fixture in pinned Perfetto 58.2. The
qualifier checks 11 nanosecond spans, track nesting, source byte counts and
three proof process IDs. Use
`holdfast trace-packet-viewer-validate out/packet-viewer.json --trace-processor PATH`
to recheck its receipt.

Create the destination directory and run these commands to record, render or
qualify a pure compiler trace.

```console
python tools/run.py holdfast trace examples/pure.hf --output out/pure-trace.json
python tools/run.py holdfast trace-validate out/pure-trace.json --source examples/pure.hf
python tools/run.py holdfast trace-render out/pure-trace.json --source examples/pure.hf --output out/pure-timeline.html
python tools/run.py holdfast trace-benchmark examples/pure.hf --output out/pure-trace-comparison.json
python tools/run.py holdfast trace-benchmark-validate out/pure-trace-comparison.json --source examples/pure.hf
python tools/run.py holdfast trace-qualify-viewer --trace-processor /path/to/trace_processor_shell --output out/trace-viewer.json
python tools/run.py holdfast trace-viewer-validate out/trace-viewer.json --trace-processor /path/to/trace_processor_shell
```

`trace` records parsing and syntax decoding under `compile`, then
elaboration and emission with one span per source declaration. Declaration
spans carry the name, kind and one-based Unicode code-point location. Static
specialization stays in its calling declaration's span. Trace events use
microseconds from `perf_counter_ns` and logical process and thread ID 1.
`C` events count source bytes and `X` events record intervals.
[Perfetto formats](https://perfetto.dev/docs/getting-started/other-formats)

The schema-3 manifest binds source bytes, Python, compiler and parser inputs,
locks and the exact runtime closure, including the checked parser worker and
its loaded images. Windows also binds the WSL transport and guest Python.
Identity hashing runs outside timed intervals. `--max-events` sets the event
limit, up to 4,096. Dropped events are counted. Publication is atomic and
refuses source aliases. Refused source can publish a diagnostic trace and
still exits nonzero. `trace-validate` requires a fresh, complete recording.
[Trace controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_compiler_trace.py)

`trace-benchmark` alternates plain and traced translation in one host
process after one warmup by default. It takes seven samples by default.
Use `--warmups` for 0 to 5 warmups and `--samples` for 1 to 31
samples. The benchmark requires identical Gallina and complete traces. The
schema-1 report records sample order, elapsed and bookkeeping nanoseconds,
summary statistics and signed overhead. Bookkeeping excludes identity hashing,
serialization and publication. `--max-overhead-ppm N` rejects measured total
overhead above that budget. The published qualification tests the pure and
expression examples with a 250,000 ppm budget.
[Benchmark controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_trace_benchmark.py)

`trace-qualify-viewer` checks the provisioned Perfetto 58.2 executable
against the pinned digest for its platform. It runs two SQL queries and
checks six expected spans, depths, worker IDs and counters. It also exercises
seven controls for stale, malformed or incomplete recordings. The reader has
a 30-second deadline and the report publishes atomically.
`trace-viewer-validate` verifies receipt bindings without rerunning the reader.
[Reader pins](https://github.com/symbiogenesis/HoldFast/blob/main/THIRD-PARTY.md#independent-trace-importer) · [Viewer controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_trace_viewer.py)

### Offline browser timelines

`trace-render` validates a complete current schema-3 recording and writes a
self-contained HTML timeline. The timeline includes keyboard-focusable tooltips,
a searchable table of exact microsecond values and SHA-256 bindings. Its content
security policy pins the inlined assets. The input is limited to 2 MiB and the
atomic HTML output to 4 MiB. Qualify the renderer with a provisioned Chromium
executable.

```console
python tools/run.py holdfast trace-qualify-browser --browser /path/to/browser --browser-sha256 <sha256> --output out/trace-browser.json
```

The qualifier opens a temporary file in headless Chromium with a 30-second
deadline. It checks layout, colors, keyboard focus, tooltips, source counters
and filtering, and binds the exact browser, renderer, harness and HTML bytes.
[Browser controls](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_trace_html.py)
