# HoldFast formatting, documentation and lints

Both compilers offer formatting and advisory lints. Checked formatting requires
accepted source. Editor formatting and `holdfast-parser fmt --syntax-only`
require a complete supported syntax tree.
[Pure compiler](../pure-prototype/) · [Mathematical compiler](../elaboration-prototype/) ·
[Surface grammar](../../language/surface-grammar/)

## Common style

- Indent four spaces. Use LF and one terminal newline. Put each block brace
  and `else` on its own line. Separate top-level declarations by one blank
  line and attach documentation directly above its declaration.
- Use one statement per line, with spaces around binary operators and after
  commas and control keywords. Omit space before call parentheses and inside groups.
  Preserve return blocks and expression bodies as authored. Prefer unsuffixed
  literals where the [checked context](../../language/first-release/#contextual-inference)
  uniquely determines their type. Keep explicit widths where they resolve
  ambiguity or communicate a chosen representation.
- Use PascalCase for public functions, constants and user-defined types and
  camelCase for parameters and locals. Naming is a suppressible lint. Formatters
  preserve all names, including primitive, lifetime, grade and foreign names.
- Indent each contract on its own line before the body. A short expression-bodied
  function can keep its sole `~>` clause on the signature line, as in
  `public u32 Step() ~> none => 1u32;`. Wrap a long effect list at commas,
  indenting continuation entries one level. Long signatures and calls may
  wrap at argument boundaries with one extra indentation level.
  Width is advisory. Keep ownership, loan, effect and proof annotations visible
  in authored order.
- Preserve token spellings, literal representations, comments and documentation
  contents. Do not sort imports, declarations or arguments, insert conversions,
  change parentheses or synthesize proof, resource or disposal operations.

```hf
module Example;

/// Sets the configured capacity.
public const Nat Capacity = 1_024;

/// Scales a count by the configured capacity.
public Nat Scale(Nat count)
{
    return count * Capacity;
}
```

## Numeric separators

The compiler ignores separators when interpreting a number and counts only
its digits against the literal limit. Formatters retain the original spelling.
[Numeric syntax](../../language/surface-grammar/)

## Documentation comments

Consecutive `///` lines directly above a declaration attach as documentation.
A blank line, ordinary comment or token breaks attachment. Unattached lines
remain comments. Presentation strips `///` and at most one space. Formatting
preserves attachment and comment contents, with original source and positions
retained for display.

Pure hover shows attached documentation for resolved public functions and constants
at declarations and references. It renders bounded plain text, including XML-like
content. Documentation has no semantic or proof authority.
[LSP projection](../lsp-prototype/#pure-navigation-increment)

### Checked examples in Markdown

For complete pure modules, use `holdfast-check` for success or
`holdfast-reject syntax`, `holdfast-reject name` or `holdfast-reject type` for
refusals. The gate checks the expected verdict and locates discrepancies.
Use ordinary fences for fragments and illustrations. Keep minimized generated
failures as replayable regressions in the owning tests.
[Pure compiler](../pure-prototype/#source-fragment)

## Compiler commands and publication

The default build of a [locked root package](#locked-package-authoring)
checks canonical layout and reports advisory lints. Editors can send buffers to
the same formatter on demand.

| Command or mode | Source policy |
| --- | --- |
| `holdfast check SOURCE` and `holdfast emit SOURCE` | Read an immutable snapshot, run required checks and advisory lints, and preserve source bytes. Emission may publish its explicitly requested output only after successful checking. |
| `holdfast fmt SOURCE` | Explicitly request canonical source formatting. |
| `holdfast fmt SOURCE --check`, `--format check` on check/emission | Report formatting differences without writing source; differences fail the formatting check. |
| `--format off` on check/emission | Explicitly select the ordinary source-preserving default. |
| `--format write` on check/emission | Explicitly opt into formatting this invocation; this mode is never inherited as a hidden build or dependency setting. |
| `holdfast lint SOURCE` | Report the supported lint set without rewriting. |
| Editor formatting | Offer layout for a complete supported syntax tree, including buffers with semantic errors. The editor applies the proposed edit. |

Pure `check` and `emit` accept `--no-lint`. Syntax, type and constant evaluation
still run. Style differences fail only with `--format check` or `fmt --check`.
Source-preserving commands accept read-only inputs with writable output locations.
Unsaved editor snapshots have their own identity. The editor owns source writes.

For checked formatting writes, validate the full source and reparse and recheck
the candidate for token/comment preservation and idempotence. Publish atomically
to the same unchanged regular source file. Refuse symlinks and changed inputs.
Syntax/type failures, denied lints and invalid destinations preserve source and
output. Recompute semantic facts and emission from formatted bytes. Diagnostics
and emitted hashes bind the compiled snapshot. A later I/O failure can leave
formatted source with failed output publication.

## Lint policy

Lints preserve source and require a complete check. Each finding has a stable
ID, location and message. The mathematical checker uses checked facts for
contract, proof, guard, effect and loan findings. Pure lints cover naming,
documentation and Boolean comparisons.

| ID | Advisory finding |
| --- | --- |
| `HOLDFAST100` | A public member name does not use a capital initial and ASCII alphanumeric words |
| `HOLDFAST101` | A parameter or local name does not use a lower-case initial and ASCII alphanumeric words; `_` is exempt |
| `HOLDFAST102` | A public function or constant has no attached documentation |
| `HOLDFAST103` | An equality comparison has a Boolean literal operand |
| `HOLDFAST105` | A generic type parameter name does not use a capital initial and ASCII alphanumeric words |
| `HOLDFAST107` | An unparenthesized bitwise expression is an operand of a comparison in checked mathematical source |
| `HOLDFAST108` | An otherwise legal binding pattern differs only in its initial capitalization from a constructor of the scrutinee type. A confusable whole match pattern is a [type error](../../language/reference/#lexical-structure). |
| `HOLDFAST109` | A contract repeats or restates a checked descriptor-preservation fact |
| `HOLDFAST111` | An `old` selects a snapshot of a stable value |
| `HOLDFAST112` | A clause repeats a fact supplied by its checked type, invariant or library law |
| `HOLDFAST113` | A contract conjunct repeats the same resolved fact |
| `HOLDFAST114` | A stronger requirement or guarantee already implies this fact |
| `HOLDFAST115` | A contract expression is tautological or repeats a fact across exhaustive outcomes |
| `HOLDFAST116` | Entry conditions are contradictory, or a guard or quantified range makes its guarantee vacuous |
| `HOLDFAST117` | An implementation clause repeats its checked inherited contract |
| `HOLDFAST118` | An effect entry is duplicated or adds nothing to the effect set |
| `HOLDFAST119` | A private declaration has an unused effect allowance |
| `HOLDFAST120` | A postcondition repeats a frame fact supplied by the callable's checked loan and effect boundary |
| `HOLDFAST121` | A lifted invariant stays established across the checked scope |
| `HOLDFAST122` | A shared loan suffices at this borrow, private parameter or iteration |
| `HOLDFAST123` | An initialization-only private scalar parameter can use `out` |
| `HOLDFAST124` | An immutable binding suffices at this `var` |
| `HOLDFAST125` | Checked path facts make a branch, short-circuit operand or loop body unreachable |
| `HOLDFAST126` | A verdict match reconstructs its scrutinee unchanged |
| `HOLDFAST127` | Checked arithmetic or conversion always succeeds within its represented bounds |
| `HOLDFAST128` | An intermediate assertion repeats existing proof evidence |
| `HOLDFAST130` | A nonrecursive definition declares a termination measure |
| `HOLDFAST131` | A loop invariant or measure repeats a fact already supplied by its context or range |
| `HOLDFAST132` | A ghost parameter is unused in the checked declaration |
| `HOLDFAST133` | Local type or explicit generic arguments can be inferred with equivalent elaboration, opt-in |
| `HOLDFAST134` | A public declaration allows effects beyond its checked footprint, opt-in |

The mathematical CLI and native playground report `HOLDFAST107` for accepted
expressions such as `flags & mask == 0u8`. Write `(flags & mask) == 0u8` to
show the existing grouping explicitly. The warning locates the bitwise
operator and leaves the source unchanged.

Use `python tools/run.py holdfast-parser lint-preview SOURCE --line LINE --column COLUMN`
with the one-based warning coordinates to preview a pair of parentheses around
that operand. The JSON gives the half-open UTF-8 byte span, replacement text
and original and candidate digests. Every original byte stays in order,
including comments within a multiline operand. An already grouped operand
produces no warning or edit.

The mathematical parser and elaborator check both snapshots. The full syntax
trees must agree after adding the selected group and dropping locations.
The generated Gallina must agree byte for byte apart from the source digest.
The [preview validator](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/mathematical_preview.py) rechecks the
retained edit against the current source, compiler dependencies, parser bytecode
and the OCaml interpreter selected by its executable header.
The command reads the source again before printing the preview.

<a id="compiler-verified-assist-dont-coerce-tooling"></a>

### Authoring diagnostics and suggestions

Syntax errors can identify an invalid nullary constructor call or explain
how `?` propagates an error. The generic authoring helpers also
construct suggestions from supplied loan modes, effect sets and numeric types.
Check a suggestion in the source context before relying on it.
[Authoring helpers](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/authoring.py)

The mathematical compiler reports both the conflicting read and where the
exclusive loan starts. For a first formatting hole that reads the built-in
`builder.Written` count directly with a fixed-width hexadecimal format,
it can show an expression-local snapshot.
For example, write `(let count = builder.Written in builder.Write($"{count:x4}"))`
to evaluate the count before `Write` borrows the builder.

Repeatable `--allow ID` suppresses optional findings. `--deny ID` enables a
finding and makes it an error. The mathematical commands accept repeatable
`--warn ID` to enable opt-in findings as warnings. Combining suppression and
explicit enablement for the same ID is a command error. Unknown IDs are command
errors. Defaults and rule identities are compiler-versioned; disabling an optional
lint cannot waive a language error. Findings go to stderr, keeping emitted Gallina
on stdout usable. A denied finding prevents any requested formatting and output writes.
If bounded compiler inspection cannot supply complete lint facts, normal advisory
compilation reports lints unavailable and continues. Explicit `holdfast lint` and a
command with denied lints require complete findings and refuse without writes.

## Formatting and linting mathematical source

Run `python tools/run.py holdfast-parser fmt FILE --check` to check a standalone
mathematical module's layout. A style difference yields a failing exit code.
`holdfast-parser fmt FILE` writes the checked layout. Ordinary `holdfast-parser elaborate FILE`
reads the authored bytes. Its explicit `--format check` and `--format write` modes
check the requested layout before emitting Gallina. A denied elaboration lint or
invalid program preserves both source and existing output. Emission after a
formatting write identifies the formatted source. `holdfast-parser fmt FILE
--syntax-only` applies layout to a complete mathematical syntax tree, including
one with an unresolved name, type error or broken proof. Add `--check` for a
read-only style verdict. This mode gives no elaboration or proof verdict.

The formatter works from Menhir's complete original token ranges. It preserves
literal spellings, nested block comments, line comments and the groups of
`///` comments attached to declarations. Raw and interpolated string tokens
retain their contents. The formatter keeps a separator between a propagation
`?` and an immediately following `?` or `.`. Byte-identical layout reuses the
original parse and any checked elaboration. When layout changes, the formatter
compares the complete location-independent syntax and ordered spellings and
checks that a second formatting pass yields identical bytes. Both compilers use
the same source identity checks and atomic file replacement. [Formatter](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/mathematical_authoring.py)

`holdfast-parser lint FILE` reports mathematical expression, pattern and contract
findings alongside public member naming, local and parameter naming, and missing
documentation on public functions, definitions and constants. Use `--allow ID`
to suppress a rule or `--deny ID` to fail on its findings. The locations identify
the original source. The [bitwise grouping preview](#lint-policy) consumes the
reported operator coordinates.

`HOLDFAST109` uses checked metadata preservation for `ref Span<byte>` and
`ref Slots<T, capacity>`. It recognizes `buf.Base == old(buf.Base)` and
`buf.Base == old(buf).Base`, including reversed operands, preserved entry
permissions and bounds, and equivalent old and current bounds under scoped
guards. Loan-mode, effect and type rules apply to the resolved resource or
declaration at the finding's source site. [Descriptor preservation](../../language/reference/#contracts)

The `HOLDFAST133` check elaborates an omission candidate against the same
source context. It requires identical emitted terms and matching resolved call
targets, inferred literal types and integer operations across the edit. Public
contract and effect findings are advisory by default. An exported bound or
guarantee can carry compatibility obligations for dependent clients.
[Public API evolution](../../language/first-release/#public-api-evolution)

### Locked package authoring

`holdfast-parser build-package WORKSPACE LOCK` checks the declared modules of
every locked root package (`edition = "math-2"`) for canonical layout by
default. It elaborates the locked graph in its own import context and reports
advisory lints using those checked facts. The checks preserve package inputs
and lock bytes. A layout difference fails the build before bundle publication
and prints the command to format the affected source file from the Linux or
WSL checkout. Regenerate the lock after applying a source edit.
[Locked builds](../elaboration-prototype/#locked-mathematical-packages)

The authoring trial uses this marked module as a package dependency. The
repository gate checks the same source through the pure compiler.
[Locked authoring trial](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_package_authoring.py)

```holdfast-check
module TrailUnits;

/// Gives the distance covered by one step.
public const Nat Step = 2;
```

For an editor formatting request, send the unsaved buffer as UTF-8 on standard
input to `python tools/run.py holdfast-parser fmt - --syntax-only` on Windows,
or use `python3` on Linux. Standard output carries the complete replacement
on success. A rejected buffer produces a diagnostic on standard error. The
editor owns application of the result to the matching buffer version. Syntactic
formatting works for files with imports and gives a layout verdict.

## Checked Boolean comparison previews

`python tools/run.py holdfast lint-preview SOURCE --line LINE --column COLUMN`
prints one explicit `HOLDFAST103` edit as JSON. Coordinates are the one-based
compiler location of the first `=` in `==`, as reported by the lint. The command
preserves the source file and its modification time. It emits no preview if the
source changes during checking.

The bounded pure compiler's complete syntax and concrete-source snapshot select
the comparison and its original byte spans. Comparing `value == true` or
`true == value` proposes `(value)`; comparing with `false` proposes `!(value)`.
Grouping around a literal is supported. Parentheses retain precedence and the
operand occurs exactly once. One request changes one comparison; it preserves
every byte outside that span. Comparisons containing comments refuse the edit.
Naming, documentation and other lint findings remain independent.

Both original and candidate must pass the existing parser and pure checker.
The checker compares their complete syntax modulo grouping and the two Boolean
equality identities, retaining calls, arguments, bindings and control flow.
The schema-2 preview binds the original inspection snapshot, exact source,
producer/configuration/target, replacement span and candidate SHA-256. The
`authoring_preview.validate` library operation rechecks all fields against the
current source and producer before returning candidate bytes. Unknown fields,
changed candidates, stale bindings and malformed coordinates refuse. This is a
development preview; it supplies no checked source or artifact correspondence.

Independent expected edits and exhaustive two-variable truth tables cover both
literal sides, negation, nested comparisons, precedence, Unicode and CRLF.
Refusal controls cover comments, invalid source, nonliteral comparisons, changed
source/producer and tampered fields; CLI controls verify source preservation and
concurrent-edit refusal.

In the pure language server, place the caret on either character of `==`, or
select a range intersecting exactly one equality operator, and request the
**Simplify Boolean comparison (HOLDFAST103)** refactoring. The editor must support
literal `refactor.rewrite` actions and versioned `documentChanges`. The server
checks the current unsaved text in a bounded worker and returns a single edit
for that document version. The editor chooses whether to apply it. Comments,
ambiguous selections and excluded action kinds yield no edit. An invalidated
generation or a failed worker prevents publication.

`python tools/run.py holdfast-lsp --qualify-actions --output actions.json`
checks application in the same [pinned editors](../lsp-prototype/#local-rename-previews)
as the local rename qualification. Each editor requests one checked action
against an unsaved Unicode buffer and applies the returned versioned edit.
The next request checks the rewritten source, and replaying the earlier edit
preserves the newer buffer. The report validates both bidirectional transcripts
against the expected request, edit, source and document versions. The probes
also check that the on-disk fixture retains its original bytes.

## Generic type parameter naming

The [mathematical playground](../playground/#dependent-mathematics-increment)
and CLI report `HOLDFAST105` for generic type parameter names that fail the
PascalCase check. `T`, `TValue` and `Element` qualify. In `Copy<T, ghost Nat n>`,
`T` follows the type-parameter rule and `n` follows the camelCase rule for
value bindings.

The lint uses the checked binder role, including in nested callable signatures,
and reports the original identifier location. It runs after complete semantic
checking and is advisory by default.

`holdfast-parser elaborate SOURCE` reports `HOLDFAST105` warnings by default;
`--allow HOLDFAST105` suppresses the rule and `--deny HOLDFAST105` makes it an error
before stdout emission or atomic output publication. Conflicting options refuse
before compilation.
The mathematical playground shows findings from successful compilation as
warning markers and Problems entries. It refuses invalid, stale, oversized or
mislocated findings.

<a id="pure-formatting-and-lint-disposition"></a>

## Qualification

The formatter checks a fingerprint of ordered tokens and comments, documentation
attachment, location-independent syntax and idempotence. The
[formatting fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_format.py) independently specify
canonical bytes. The [lint fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_lint.py) check
findings, original positions and refusal when inspection is unavailable.

The [documentation fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_documentation.py) check
direct attachment, orphan and broken attachment cases, Unicode and mixed
newlines, bounded plain text, declaration/use hover agreement, forged facts and
invalidation after unsaved edits over stdio. They compare translation and
attachment before and after formatting. An oversized orphan is ordinary trivia.

The [CLI fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_authoring_cli.py) check immutable
defaults, read-only source, exact snapshot provenance, explicit formatting, lint
policy and publication failures. The
[editor fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_lsp_editor.py) check edit ranges,
worker refusal and recovery and stdio. Independent client qualification follows
the [LSP contract](../lsp-prototype/#acceptance-and-remaining-qualification).

The [mathematical authoring fixtures](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_mathematical_authoring.py)
compare independently specified canonical bytes, preserve attached and orphan
Unicode documentation, reject detached token ranges and stale writes, and
replay the original and formatted bitmask lemma in Rocq.
