All five briefed bugs fixed, plus a sixth found during the work: 1. Block-comment continuation drift: token::Comment gained line/col; continuation lines are dedented by the comment's original column before re-indenting, making reformatting a true fixed point while preserving the author's relative indentation inside the comment. 2. Comments inside expression groups (concat, parens, call args, assignment patterns, binary operands) now force the group to break instead of being lifted out. 3. Closing block labels preserved for end/join*/endfunction/endtask/ endpackage, matching endmodule. 4. Multi-instance declarations fit on one line when they fit and indent their continuations when they break. 5. @( /* c */ * ) keeps its comments (SensList::Star before/after). 6. Multi-line `define/attribute bodies no longer drift (RawText.col). verify.rs comparison logic untouched (diagnostic positions only) — QA audited the diff to confirm the safety net was not weakened. All four #SKIP cases un-skipped verbatim as spec; 17 cases added (183 -> 200, 0 skipped). QA triple-formatted 204 inputs with zero regressions. Clippy is now fully silent workspace-wide. Remaining comment-placement refusals (4) and a pre-existing @(* ) lexer limitation are documented as open items, not hacked around. Dev: Opus agent; QA: Sonnet agent; review in docs/features/formatter-bug-fixes/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
13 KiB
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)
- [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. Addverify_equivalence(input, output)tovlog_formatter: re-lex both throughvlog_parser::lexer, compare token kinds + text (whitespace excluded, comments included). Run it insideformat_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. - [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-verifyfor speed later). Today idempotency is only asserted intests/fixtures.rs. - [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.
- [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.rswithstd::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*.- 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 invlog_parser::parserthat returns a parse error past a documented limit (ruff does the same). Do the same in the formatter's recursive walk.
2. Formatter features
- [V] Format-off fences. Support
// verilog_format: off/// verilog_format: on(accept avfmt: off/onalias). Verible implements this as "emit the original byte range verbatim" — the trivia inMetaalready carries comments, so detect fences during formatting informat.rsand splice source text by span. Requires nodes to carry byte spans (see §5, it's needed for LSP anyway). - [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 shipsgit-verible-verilog-format.shon top of it). Follow-up: avfmt --diff-base <rev>or contrib script that derives ranges fromgit 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. - [R]
--diffmode. Likeruff format --diff/ Verible's autofixpatchmode: print a unified diff instead of rewriting, for CI logs and code review. - [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)
- [R] Config file discovery. Search upward from each input file for
vfmt.toml/.vfmt.toml(analog ofruff.toml/pyproject.toml). Keys:line-length,indent,excludeglobs. CLI flags override file config. Keep Verible's philosophy of few knobs — don't grow a clang-format-sized option surface. - [R] Parallel file processing. ruff's speed story is embarrassing
parallelism over files.
main.rsformats serially; userayonpar_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
.gitignoreand add--excludeglobs when walking directories (collect_filesinmain.rscurrently walks everything, including e.g. generated netlists). - [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 checkandvfmt formatmust sharevlog_parseroutput in a single invocation (vfmt check --fix --formatstyle 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 jsonfor tooling from the start. - [R] Fix applicability model. ruff distinguishes safe vs
unsafe fixes (
--fixvs--unsafe-fixes). Adopt it now — retrofitting safety classification is painful. - [V] Waiver mechanisms: inline
// vfmt: waive rule-name(acceptverilog_lint: waivefor migration),waive-start/waive-stopranges, 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:
- [V] Massive text-in/text-out table tests. Verible's
formatter_test.ccis thousands of small{input, expected}pairs — the backbone of the formatter.small_casesincrates/vlog_formatter/tests/fixtures.rsis the seed; grow it into a dedicatedtests/cases/organized by construct (one file per area: ports, expressions, case-statements, generate, comments, macros...). Port cases directly fromformatter_test.ccwhere 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_equivalenceexists, 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 forlexer.rstrivia attachment (comment → leading/trailing decisions, blank-line counting),parser.rsper-construct parse tests, andprinter.rsgroup-breaking behavior on synthetic docs. - [V] Lint test harness with inline violation markers. Port the
LintTestCase/RunLintTestCasesidea: test cases embed expected findings positionally in the source (Verible splicesExpectedTokenInfofragments 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]
RunApplyFixCasesequivalent: 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.
- [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. - [R] Fuzzing. ruff fuzzes its parser.
cargo-fuzztargets: (a) parser must never panic on arbitrary bytes, (b) for inputs that parse, format must satisfy equivalence + convergence. - [R] Consider
instafor the snapshot harness (review workflowcargo insta reviewbeatsUPDATE_SNAPSHOTS=1), keeping the idempotency loop fromfixtures.rs.
6. Foundations for LSP / highlighting / navigation
Goal: reuse the frontend as a language-server backend (semantic
highlighting, hover, go-to-definition) the way ruff grew ruff_server
(and ty) on shared crates. Decisions that are cheap now and expensive
later:
- Byte spans on every token and AST node. Prerequisite for
everything in this section (and for §2 fences/range formatting).
token.rs/ast.rsshould carryTextRange { start, end }offsets; add a line-index utility (ruff'sruff_source_file) for offset↔line:col. - 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. - Keep the CST lossless. Current design (trivia in
Meta) is format-oriented; verify every source byte is reachable from the tree (tokens + trivia + spans). Areconstruct(tree) == inputround-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 patchingMeta. - New crate
vlog_semantic(analog ofruff_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). - New crate
vfmt_server(analog ofruff_server): LSP over stdio viatower-lsporlsp-server. Order of capabilities:textDocument/formatting+rangeFormatting(reuses §2--lines),- publish parse/lint diagnostics,
semanticTokensfor highlighting (needs only the lexer + spans),hover/definition(needsvlog_semantic).
- Salsa-style incrementality — defer. ruff's
ruff_dbuses 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: like Verible, operate on unpreprocessed
source, treat
`define/`ifdefbodies and macro calls as opaque (current behavior — keep, and document the implications). - 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_semanticexists.