Files
lucisv/TODO.md
T
lucioandClaude Fable 5 02f68655b5 Add error-recovery and format-fences (jointly: entangled in format.rs)
error-recovery (vlog_parser): parse_source_tolerant never fails —
errors become positioned ParseDiagnostics and ItemKind::Error /
StmtKind::Error leaves (raw text + span, nesting invariant intact),
with recovery at documented sync tokens, bracket-balanced skipping,
and stray-closer collapse. Strict parse_source is byte-identical in
behavior (shared grammar, tolerant flag). Guarantees tested:
tolerant==strict on 500 valid sources; depth/links budgets neither
reset nor leak across recovery (mutation-tested); no panic across
27k+ truncation cuts, every single-char fixture deletion, 1MB of
semicolons (500k recoveries, 344ms). The future LSP parses mid-edit
code; the formatter still refuses on the first error.

format-fences (vlog_formatter): // verilog_format: off|on and
// vfmt: off|on emit fenced item ranges as exact source bytes via
spans (Doc::Verbatim), Verible-style item-level regions per scope,
unmatched off to end of scope, byte-exact including indentation and
idempotent at every join (24 adversarial probes). ~2000 corpus fence
injections: zero region byte changes, zero new verification
failures. verify.rs untouched; with no fences output is
byte-identical (corpus TSV md5 unchanged).

Also surfaced and queued in TODO: comment-in-list refusals
(112/1868 injection trials) and the double-blank leading-comment
nit — the next comments round.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{error-recovery,format-fences}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 05:23:05 -07:00

287 lines
17 KiB
Markdown

# TODO — best practices adopted from ruff and Verible
Curated backlog for vfmt, drawn from `astral-sh/ruff` (architecture, CLI/UX,
fix model) and `chipsalliance/verible` (formatter safety, alignment,
waivers, and especially test methodology). Items reference the current
draft's files. Roughly ordered by priority within each section.
Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
---
## 1. Correctness safety net (highest priority)
- [x] **[V] Token-stream equivalence verification.** Verible's formatter
re-lexes its output and asserts it is lexically equivalent to the input
(`verilog_equivalence.cc`); on mismatch it emits the *original* text.
Add `verify_equivalence(input, output)` to `vlog_formatter`: re-lex both
through `vlog_parser::lexer`, compare token kinds + text (whitespace
excluded, comments included). Run it inside `format_source()` on every
call — not just in tests. This turns "the formatter can never corrupt
code" from a test-suite property into a runtime guarantee.
- [x] **[V] Convergence (idempotency) verification at runtime.** Verible
formats twice and checks a fixed point before writing. Do the same in
`format_source()` (optionally behind `--no-verify` for speed later).
Today idempotency is only asserted in `tests/fixtures.rs`.
- [x] **[V] Failsafe fallback semantics.** On any internal verification
failure, return the input unchanged *with a diagnostic and nonzero exit*,
never partially formatted output. Parse errors already behave this way
(README notes it); extend the same contract to the two checks above.
- [x] **[R] Panic containment.** ruff catches panics per-file and reports
them as errors instead of killing the whole run. Wrap per-file work in
`crates/vfmt/src/main.rs` with `std::panic::catch_unwind`.
- [ ] **`@(* )` fails to lex** (bug-fix QA find): `(*` followed by anything
but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare
space inside `@( * )`-style spellings errors out. Make the attribute
scan back off when the contents are just `*`.
- [x] **Recursion-depth limit in the parser.** Found by cli-polish QA:
~150 levels of expression nesting overflow the stack and abort the whole
process — uncatchable by `catch_unwind`, so mid-batch files after the
crash never get processed. Add an explicit depth counter in
`vlog_parser::parser` that returns a parse error past a documented limit
(ruff does the same). Do the same in the formatter's recursive walk.
## 2. Formatter features
- [x] **[V] Format-off fences.** Support `// verilog_format: off` /
`// verilog_format: on` (accept a `vfmt: off/on` alias). Verible
implements this as "emit the original byte range verbatim" — the trivia
in `Meta` already carries comments, so detect fences during formatting in
`format.rs` and splice source text by span. Requires nodes to carry
byte spans (see §5, it's needed for LSP anyway).
→ `crates/vlog_formatter/src/fence.rs`; grammar, item-level semantics and
join rules in `docs/features/format-fences/README.md`. Item scopes only —
statement-level fences are documented as not implemented.
- [ ] **[V] Range formatting: `--lines M-N[,M-N...]`.** Format only
constructs intersecting the given line ranges; emit everything else
verbatim. This is what makes adoption in dirty legacy codebases possible
(Verible ships `git-verible-verilog-format.sh` on top of it). Follow-up:
a `vfmt --diff-base <rev>` or contrib script that derives ranges from
`git diff`.
- [ ] **[V] Alignment inference for declaration/port/connection groups.**
Verible's most-loved feature: infer align-vs-flush-left intent from the
original spacing (≥4 excess spaces = author wants alignment), and break
alignment groups at blank lines and standalone comments
(`--alignment_group_boundary`). Start with the three constructs where RTL
culture demands it: port declarations, named connections (`.clk (clk)`),
and localparam/parameter lists. This needs original-spacing info
preserved through the lexer — record "excess spaces before token" as
trivia.
- [ ] **Comment inside port/param lists and assignment patterns is
dropped → refused** (found at scale by format-fences QA: 112 of 1868
corpus injection trials refuse with exit 2). The failsafe holds, but
this is the largest remaining comment-attachment gap; fix alongside the
three documented expression refusals (replication, compact bracket,
assign-value) from docs/features/formatter-bug-fixes and corpus-bugs.
- [ ] **Two leading comments separated by one blank line come out
separated by two** (format-fences QA find, pre-existing): `leading`
pushes a HardLine after each comment and a BlankLine before the next.
Fix churns snapshots; take it with the comments round above.
- [x] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix
`patch` mode: print a unified diff instead of rewriting, for CI logs and
code review.
- [x] **[R] `--stdin-filename <path>`.** Editors pipe buffer contents via
stdin; the filename is needed for good error messages and (later)
per-directory config resolution.
## 3. CLI / UX (mostly ruff)
- [x] **[R] Config file discovery.** Search upward from each input file for
`vfmt.toml` / `.vfmt.toml` (analog of `ruff.toml` / `pyproject.toml`).
Keys: `line-length`, `indent`, `exclude` globs. CLI flags override file
config. Keep Verible's philosophy of *few* knobs — don't grow a
clang-format-sized option surface.
→ `crates/vfmt/src/config.rs`; discovery rule, TOML subset and
precedence in `docs/features/config-discovery/README.md`.
- [ ] **[R] Parallel file processing.** ruff's speed story is embarrassing
parallelism over files. `main.rs` formats serially; use `rayon`
par_iter over the collected file list (formatting is already pure).
- [ ] **[R] Content-hash cache.** Skip files whose (content hash, config
hash, vfmt version) triple is unchanged, stored in `.vfmt_cache/`.
Do this *after* parallelism; it matters for big monorepo RTL trees.
- [ ] **[R] Respect `.gitignore`** and add `--exclude` globs when walking
directories (`collect_files` in `main.rs` currently walks everything,
including e.g. generated netlists).
- [x] **[V+R] Exit-code contract doc.** Already ruff-like (0 clean /
1 would-reformat / 2 error) — document it in README and freeze it; CI
scripts will depend on it.
## 4. Linter (`vfmt check`) — new crate `vlog_linter`
Design it ruff-style from day one (shared parse, fix model), with
Verible's rule ergonomics (waivers, configurable rules).
- [ ] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must
share `vlog_parser` output in a single invocation (`vfmt check --fix
--format` style workflows come free later).
- [ ] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name,
one-line summary, longer doc with style-guide rationale (Verible links
each rule to a style-guide section — do the same), and a
`check(node/token) -> Vec<Diagnostic>` over syntax tree or token stream.
- [ ] **[V] Diagnostic format `FILE:LINE:COL: message [rule-name]`** plus
**[R]** `--output-format json` for tooling from the start.
- [ ] **[R] Fix applicability model.** ruff distinguishes *safe* vs
*unsafe* fixes (`--fix` vs `--unsafe-fixes`). Adopt it now — retrofitting
safety classification is painful.
- [ ] **[V] Waiver mechanisms:** inline `// vfmt: waive rule-name` (accept
`verilog_lint: waive` for migration), `waive-start`/`waive-stop` ranges,
and external waiver files (`waive --rule=X --line=N --location=glob`) for
code you can't touch. ruff's lesson: also warn about *unused* waivers.
- [ ] **[V] Configurable naming rules via regex** (module/instance/
parameter/enum naming), with named presets like Verible's
(snake_case, ALL_CAPS, etc.).
- [ ] **[V] `--generate_markdown`-style self-documentation** — generate the
rule reference from the registry so docs can't drift. ruff does the same
for its 900+ rules.
- [ ] Seed rules (all syntactic, all from Verible's default set):
no-tabs, no-trailing-spaces, explicit-parameter-storage-type,
case-missing-default, always-ff-non-blocking / always-comb-blocking,
forbid `wire`-reg mixups in SV files, module-filename match.
## 5. Testing — adapt Verible's methodology
Verible's formatter confidence comes from a few complementary layers
(`formatter_test.cc`, component tests, equivalence/convergence checks).
Adapt each:
- [x] **[V] Massive text-in/text-out table tests.** Verible's
`formatter_test.cc` is thousands of small `{input, expected}` pairs — the
backbone of the formatter. `small_cases` in
`crates/vlog_formatter/tests/fixtures.rs` is the seed; grow it into a
dedicated `tests/cases/` organized by construct (one file per area:
ports, expressions, case-statements, generate, comments, macros...).
Port cases directly from `formatter_test.cc` where our supported-syntax
overlaps — it encodes years of accumulated edge cases (translate expected
output to our style: 2-space indent matches, wrap style differs).
- [ ] **[V] Run equivalence + convergence on *every* test case**, not just
snapshots — once §1's `verify_equivalence` exists, assert it in the
fixture harness too, so every new case buys three checks for free.
- [ ] **[V] Component-level tests.** Verible tests the pipeline stages
separately (`token-annotator_test.cc`, `tree-unwrapper_test.cc`). Ours:
unit tests for `lexer.rs` trivia attachment (comment → leading/trailing
decisions, blank-line counting), `parser.rs` per-construct parse tests,
and `printer.rs` group-breaking behavior on synthetic docs.
- [ ] **[V] Lint test harness with inline violation markers.** Port the
`LintTestCase` / `RunLintTestCases` idea: test cases embed expected
findings positionally in the source (Verible splices `ExpectedTokenInfo`
fragments inline). A Rust adaptation: annotate with a marker comment or a
`^^^` caret line, e.g.
`assert_lint::<NoTabsRule>("module m;\n\twire x;\n ^ no-tabs\nendmodule")`.
Exact-match: unexpected findings fail the test too.
- [ ] **[V] `RunApplyFixCases` equivalent:** every autofix rule gets
`(input, fixed_output)` pairs, and the fixed output must itself be
lint-clean and formatter-idempotent.
- [ ] **[V] Error-case tests.** Table of inputs that must *fail* to parse
with the expected error position — locks in the failsafe path.
- [x] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff
CI runs against big OSS codebases and diffs results between commits. Do
the same with permissively-licensed RTL: e.g. lowRISC Ibex, OpenTitan,
PULP cores, picorv32. Script: clone pinned revs, run vfmt over every
`.sv/.v`, report parse-success rate + equivalence/convergence failures;
fail CI on regression. Also the honest tracker for the "not yet
supported" list in README.
→ `tools/corpus_fetch.sh` + `tools/corpus_check.sh`, baseline and
findings in `docs/features/corpus-check/README.md`. CI wiring is the
one part left open (network access is a separate decision).
- [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets:
(a) parser must never panic on arbitrary bytes, (b) for inputs that
parse, format must satisfy equivalence + convergence.
- [ ] **[R] Consider `insta`** for the snapshot harness (review workflow
`cargo insta review` beats `UPDATE_SNAPSHOTS=1`), keeping the
idempotency loop from `fixtures.rs`.
## 6. LSP: full editor support (a first-class goal, not a maybe)
Goal (owner's requirement, 2026-08-19): vfmt becomes a language server
for VS Code and Vim/Neovim with feature parity, for Verilog/
SystemVerilog, with what the Python VS Code stack (ruff + Pylance)
offers over LSP — scoped to **synthesizable Verilog first**:
- semantic syntax highlighting (`semanticTokens`)
- formatting (document + range) and lint diagnostics as you type
- go-to-definition and find-all-references
- hover: declaration/type info, and **`` `define`` expansion on hover**
(hover a macro usage → see its value/body)
- document + workspace symbols; later: completion, rename, signature
help for module instantiation
- **cross-file resolution through header imports**: `import pkg::*;` /
`import pkg::name;` at the top of a file or in a module header must
resolve into the package's file anywhere in the workspace (workspace
index of modules/packages; `` `include`` paths resolved too)
One server binary serves both editors (VS Code via a thin extension,
Vim/Neovim via built-in LSP config); no editor-specific logic below the
protocol layer. Foundation decisions that are cheap now and expensive
later:
- [x] **Byte spans on every token and AST node.** Prerequisite for
everything in this section (and for §2 fences/range formatting).
`token.rs` / `ast.rs` should carry `TextRange { start, end }` offsets;
add a line-index utility (ruff's `ruff_source_file`) for offset↔line:col.
→ `docs/features/spans/README.md`. `vlog_parser::span::TextRange` on every
token, comment and node; `vlog_parser::line_index::LineIndex` for
offset↔line:col; token-level losslessness is a test
(`crates/vlog_parser/tests/spans.rs`).
- [x] **Error-tolerant parsing mode.** A formatter may refuse broken input;
an LSP cannot — code is mid-edit most of the time. Add recovery in
`parser.rs`: on statement-level error, record a diagnostic, skip to a
sync token (`;`, `end`, `endmodule`), continue. Formatter keeps requiring
zero errors; the LSP consumes the partial tree.
→ `vlog_parser::parse_source_tolerant(src) -> (SourceFile,
Vec<ParseDiagnostic>)`; unparsable ranges become `ItemKind::Error` /
`StmtKind::Error` leaves. Sync tokens, the four guarantees and the
deliberate gaps (no tolerant *lexer*, no recovery inside headers or lists)
in `docs/features/error-recovery/README.md`. `parse_source` unchanged.
- [ ] **Keep the CST lossless.** Current design (trivia in `Meta`) is
format-oriented; verify every source byte is reachable from the tree
(tokens + trivia + spans). A `reconstruct(tree) == input` round-trip test
makes losslessness a tested invariant — this is what makes the same tree
serve formatter, linter, and highlighter. If gaps appear, consider a
rowan-style green tree (rust-analyzer / ruff direction) rather than
patching `Meta`.
- [ ] **New crate `vlog_semantic`** (analog of `ruff_python_semantic`):
symbol tables per scope (module/package/function/block/generate), binding
→ references. Serves go-to-definition/hover first, then semantic lint
rules (unused-signal, undriven-net) which are the lint rules people
actually want and Verible *can't* do (it's syntax-only — this is the
differentiation opportunity).
- [ ] **`` `define`` table for hover expansion.** Record every
`` `define`` (name, params, body text, source span) during lexing
instead of treating it as fully opaque — no expansion during
formatting (that non-goal stands), but the table feeds hover
(`` `WIDTH`` → "defined as 8 in defs.svh:12") and later single-step
macro expansion display. Cheap to collect now that directives carry
`RawText`.
- [ ] **Workspace index for cross-file navigation.** Map module/package/
typedef names → (file, span) across all workspace files, so header
imports (`import pkg::*;`) and instantiations resolve to definitions
in other files. Start as a full-scan-on-startup index (Verilog
codebases are small); incrementality comes with salsa later.
- [ ] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over
stdio via `tower-lsp` or `lsp-server`. Order of capabilities:
1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`),
2. publish parse/lint diagnostics,
3. `semanticTokens` for highlighting (needs only the lexer + spans),
4. `hover` (decl info + define table) / `definition` / `references`
(needs `vlog_semantic` + workspace index),
5. document/workspace symbols; then completion, rename, signature
help for instantiations.
- [ ] **Editor packaging.** A minimal VS Code extension (launch the
server, register file types) and a documented Vim/Neovim `lspconfig`
snippet. No editor-specific features beyond launching.
- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa;
don't take that dependency until hover/definition across files exists.
Per-file recompute is fine at Verilog file sizes.
## 7. Deliberate non-goals (also a best practice)
- No preprocessor expansion *in the formatter*: like Verible, format
unpreprocessed source and never expand macros into the output. (The
LSP's define table in §6 *records* definitions for hover display —
that is bookkeeping, not expansion, and doesn't weaken this rule.)
- No option explosion: Black/ruff's lesson — every knob halves the value
of a canonical style. Alignment inference (§2) is the culturally
necessary exception.
- No semantic claims in v1 lint rules: syntax-only rules first (Verible's
scope), semantic rules only after `vlog_semantic` exists.