Files
lucisv/README.md
T
lucioandClaude Fable 5 003e0766e9 Add alignment inference and the format cache (round 17)
alignment: Verible-style alignment-intent inference for ANSI ports
(name column), named connections (paren column) and parameter items
(name and = columns). A group aligns iff the author asked: >=4
excess spaces somewhere, or the group already sits consistently at
one column -- single-space code keeps today's bytes exactly (zero
churn across all 397 pre-existing cases; corpus outcome TSV
byte-identical while 291/578 formattable files change content).
Fixed-point by construction: aligned output re-infers the same
targets, flush re-infers flush; the whole verdict is decided at
document-build time (a printer-side split diverged ibex_core.sv at
width 60 during development -- caught by a 2312-run config sweep and
redesigned). Groups break at comments/attributes/directives/blank
lines; a group that cannot fit falls back to flush whole, never
mixed. No lexer changes: name_span plus the source answers every
spacing question. QA's sabotage confirmed the runtime convergence
check catches the predicted flip-flop even with the unit test gone.

format-cache: warm runs skip verified-clean files. Key = (FNV-1a 64
content hash, resolved config values, vfmt version), path-keyed;
only the fixed-point verdict is ever cached, so --check/--diff can
never go stale and a hit can only skip work, never produce output.
One atomic text file in self-gitignoring .vfmt_cache/; --no-cache /
--cache-dir; 8-process concurrency clean. Warm corpus check: 2x at
default threads, 7.7x single-threaded.

655 workspace tests. Dev: 2 Opus agents (both isolated their gates
from the other's churn via HEAD-reverted scratchpad copies); QA: 2
Sonnet agents; reviews in docs/features/{alignment,format-cache}/
README.md.

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

465 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# vfmt — a Verilog/SystemVerilog formatter and linter in Rust
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
layout conventions and lint ergonomics borrowed from
[Verible](https://github.com/chipsalliance/verible).
```bash
# format files / directories in place (like `ruff format`)
vfmt rtl/ tb/top_tb.sv
# lint (like `ruff check`); `vfmt format ...` is the explicit spelling of the above
vfmt check rtl/
# check mode for CI (exit 1 if anything would change)
vfmt --check rtl/
# print a unified diff instead of rewriting (also exit 1 if anything would change)
vfmt --diff rtl/
# skip generated files while walking directories (repeatable)
vfmt --exclude '*_gen.sv' --exclude build rtl/
# .gitignore is honored while walking; --no-gitignore turns that off
vfmt --no-gitignore rtl/
# files are formatted on all cores; pin the worker count for reproducible CI
vfmt --threads 1 rtl/
# repeat runs skip files that are already formatted; --no-cache turns that off
vfmt --check rtl/
vfmt --no-cache --check rtl/
# ignore any vfmt.toml found next to the input
vfmt --no-config rtl/
# pipe through stdin/stdout; --stdin-filename names the buffer in messages
cat foo.sv | vfmt -
cat foo.sv | vfmt --stdin-filename rtl/foo.sv -
```
### Exit codes (frozen contract — CI may depend on it)
| Code | Meaning |
|---|---|
| 0 | Success: files were formatted, `--check`/`--diff` found nothing to change, or `check` found no violations |
| 1 | `--check`/`--diff`: at least one file would be reformatted (nothing written). `check`: at least one violation was reported |
| 2 | An error occurred (bad arguments, I/O, or a file that could not be formatted); every file involved in an error is left untouched |
An error outranks "would reformat": a run with both exits 2.
### Parallelism
Files are formatted on a worker pool, one thread per logical CPU by default.
`--threads N` pins the worker count (`--threads 1` is a single worker), which
matters for reproducible CI timing and for bisecting; it never changes what is
produced. **The thread count does not affect output**: results are collected
and reported in input order, so stdout, stderr and the exit code are
byte-identical at any `N`, and `vfmt --diff` stays one clean patch in input
order. stdin mode is single-threaded.
### Cache
vfmt remembers which files it has already verified are formatted, so a repeat
run over an unchanged tree skips them: the summary says `N files from cache`,
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`, vfmt version)**
per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run, so
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
text file in `.vfmt_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
default is relative to the current directory). Content hashing is 64-bit
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
states the collision posture, the semantics table and the concurrency story.
### Ignore files
While walking a directory, vfmt reads a `.gitignore` in every directory it
enters and skips what those rules name. A deeper `.gitignore` is applied after
(and so overrides) a shallower one, and within one file the last matching line
wins — git's own precedence. `--no-gitignore` switches this off. A path named
directly on the command line is never ignored, exactly as with `--exclude`.
Supported: `#` comments, blank lines, `*` inside one path component, a leading
or embedded `/` (anchors the pattern to that `.gitignore`'s own directory), a
trailing `/` (matches directories only), and `!` negation. **Not** supported:
`**`, `?`, character classes, `\` escapes, the global/repo excludes files, and
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
## Configuration
Settings live in a `vfmt.toml` (or `.vfmt.toml`) file, ruff-style. For each
input, vfmt searches **upward from that path's directory** for one:
1. `vfmt.toml` in the directory — used if present;
2. else `.vfmt.toml` in the directory;
3. else, if the directory contains `.git`, stop: no config (the `.git` check
comes *after* 1–2, so a config file in the repo root is still found);
4. else repeat in the parent directory, up to the filesystem root.
The first file found wins outright — configs are never merged. Files in
different directories may therefore be formatted with different settings in
one run. For stdin, the search starts at `--stdin-filename`'s directory, or
the current directory if that flag is absent. `--no-config` skips all of this.
```toml
# vfmt.toml — every key is optional
line-length = 100 # 40..400, same as --line-length
indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
```
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables, multi-line arrays, string escapes) is a hard error
naming the file and line — exit 2, with nothing written. This is deliberate:
a silently ignored `line_length` typo costs more than a strict parser does.
## Linting
`vfmt check` runs a set of syntactic lint rules over the same files `vfmt`
would format — same walk, same `--exclude`, same `.gitignore` handling, same
`vfmt.toml` discovery.
```bash
vfmt check rtl/ # FILE:LINE:COL: message [rule-name]
vfmt check --output-format json rtl/ # one JSON array, for editors and CI
vfmt check --select no-tabs rtl/ # only these rules (comma-separated)
vfmt check --ignore module-filename rtl/ # everything but these
vfmt check --fix rtl/ # apply the safe fixes, write files back
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file vfmt cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Waivers
```systemverilog
wire a; // vfmt: waive no-tabs suppresses that rule on this line
// vfmt: waive no-tabs alone on a line: suppresses the next line
// vfmt: waive-start no-tabs ... and everything through
// vfmt: waive-stop no-tabs ... this line
```
`verilog_lint:` is accepted in place of `vfmt:`, so code annotated for Verible
works unedited — including waivers naming Verible rules vfmt has not
implemented, which are ignored rather than reported. A waiver of vfmt's own
that suppresses nothing, names an unknown rule or is malformed is reported
under `unused-waiver`. External waiver files are not supported. Full rules:
`docs/features/linter-core/README.md`.
## Architecture (the ruff mapping)
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
generic pretty-printing IR, language formatting rules, and a thin CLI:
| This repo | ruff equivalent | Role |
|---|---|---|
| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST |
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules |
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
| `crates/vfmt` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
Key ideas carried over from ruff/prettier:
- **Trivia attachment.** The lexer runs a second phase that folds comments
into neighboring tokens as *leading*/*trailing* trivia and records blank
lines; the parser then harvests them onto AST nodes (`Meta`). Comments are
never dropped — anything not harvested at a precise location is folded into
the next node's leading comments.
- **Fit-based layout.** Every breakable construct (port lists, connection
lists, expressions, concatenations) is a `Group`: it renders on one line if
it fits within the line limit, otherwise it breaks one-element-per-line.
A comment inside a group forces it to break.
- **Idempotency as a hard invariant.** The test suite formats every fixture
twice and asserts a fixed point.
## Style
Defaults follow Verible: **2-space indent**, **100-column lines** (both
configurable via `--indent` / `--line-length` or a `vfmt.toml`, see
[Configuration](#configuration)).
- One port / parameter / connection per line once a header doesn't fit
- Cuddled `begin`/`end` (`end else begin`)
- Tight dimension expressions: `[WIDTH-1:0]`, `[base+:8]`
- Blank lines between items preserved (collapsed to at most one)
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
through verbatim
### Alignment is inferred, not imposed
Hand-aligned columns are how RTL is read, so vfmt reads the spacing you
already wrote and keeps your intent — Verible's rule, without the knobs.
Within a run of adjacent ANSI **port declarations**, **named connections**
(`.clk (clk)`) or **`parameter`/`localparam` declarations**, four or more
spaces where one would do — or a run whose column is already lined up — means
"aligned": every row is padded to the widest one, and the list stays one
element per line. Anything else formats flush-left with a single separator,
exactly as it always has, so a file written without alignment never grows any.
```systemverilog
// written with aligned columns, so vfmt leaves them aligned — at the width
// the group actually needs, which is what makes two people's tables agree
module m (
input wire clk,
input wire [WIDTH-1:0] data,
output logic valid
);
localparam int A = 1;
localparam int LONGER = 22;
endmodule
```
Groups end at a blank line, a standalone comment, an `(* attribute *)` or a
compiler directive, so two tables separated by a comment get their own
columns. A group whose widest aligned line would pass the line limit falls
back to flush-left *as a whole* — never half-aligned. Full rule, including why
both layouts are fixed points of re-formatting:
`docs/features/alignment/README.md`.
### Turning the formatter off
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// vfmt: off` / `// vfmt: on` is an accepted alias.
```systemverilog
module m;
// verilog_format: off
localparam int A = 1; // hand-aligned, left alone
localparam int LONGER = 22;
// verilog_format: on
localparam int B = 3; // formatted normally
endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// vfmt: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
## Supported syntax
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
- Modules (ANSI and non-ANSI headers), packages, parameter ports,
`import`, `timeunit`
- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing,
packed/unpacked dimensions, net delays), `parameter`/`localparam`,
`genvar`, `defparam`
- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`,
`initial`/`final`
- Full statement set: `begin/end` (labeled), `if`/`else`, all `case` kinds
with `unique`/`priority`, `for`/`while`/`do`/`repeat`/`forever`/`foreach`,
`fork/join*`, timing controls (`#`, `@`), `wait`, `disable`, `force`/
`release`, event triggers, immediate assertions, `break`/`continue`/
`return`
- Module/gate instantiation: named and ordered connections, `.*`,
parameter overrides, instance arrays
- `generate` regions and module-level `if`/`for`/`case`
- Functions and tasks (ANSI and old-style port declarations)
- `typedef` (aliases, `enum`, packed `struct`/`union`, `typedef class`
forward declarations)
- Classes: `class`/`virtual class` … `endclass[: label]`, `#( ... )` class
parameters, `extends Base[#( ... )]`, `implements`, and class-scope members —
properties with `rand`/`randc`/`local`/`protected`/`static`/`const`, virtual
interface handles, parameterized types (`uvm_analysis_port #(bit [31:0]) p;`),
methods with `virtual`/`static`/`local`/`protected`/`automatic`, `function
new`, `extern` and `pure virtual` prototypes and their out-of-body
definitions, plus everything that already works at module scope (`typedef`,
`localparam`, `import`, directives, macro items, nested classes). `constraint
c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two
grammars with no layout convention worth inventing. See
`docs/features/classes/README.md`
- Expressions: the full operator precedence table, ternaries,
concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`),
assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped
names
- Macro invocations (`` `NAME ``, `` `NAME(args) ``, with or without a
trailing `;`) in expression position **and** wherever a module item or a
statement can appear — module and package bodies, generate regions and
blocks, `begin`/`end` and `fork`/`join`, case-item and `if`/`else` bodies,
function and task bodies. The invocation is passed through verbatim (a
multi-line argument list keeps its own line structure, re-indented); a
trailing `;` is reproduced only if the source wrote one
- `` `ifdef``/`` `ifndef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
`` `undef``, `` `include`` and macro invocations written **between the
elements** of a module header's port list, its parameter port list, an enum
member list, an instantiation's `#( ... )` parameter overrides or an
instance's `( ... )` connection list. The condition is not evaluated: both
arms' elements are entries of the one list, exactly as at item position. The
directive must be the last thing on its line, and the comma placement the
source wrote is reproduced — including a comma written *inside* an
`` `ifdef`` arm. A list may be nothing *but* a directive
(``sub #(`include "config.vh") u (...)``). See
`docs/features/directives-in-lists/README.md` and
`docs/features/directives-in-instances/README.md`
Not yet supported (parse errors). Roadmap ordered by measured impact on
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
corpus baseline this ordering comes from:
1. ~~Macro invocation at module-item / statement position
(`` `ASSERT_INIT(...) `` style)~~ — **done**; see
`docs/features/macro-items/README.md`. Unblocked 179 corpus files and
moved the parse rate from 35.2% to 57.1%
2. ~~Classes/constraints (mostly blocks DV/UVM code, not RTL) — the top
blocker at 142 files, all `extends`~~ — **done**; see
`docs/features/classes/README.md`. Unblocked 102 corpus files and moved
the parse rate from 58.0% to 70.5%. 72 of the 142 `extends` files now
format; the other 70 advanced to a second blocker, 34 of them to item 4
below, which is now the top blocker
3. `bind` directives
4. Dynamic arrays and queues — now the top blocker at 41 files (`bit x[$]`,
`int q[]`)
5. Declarations with identifier (typedef'd) types in some positions
(`my_t [N-1:0] x;`)
6. ~~`` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum
list~~ — **done**; see `docs/features/directives-in-lists/README.md`.
Two corpus files unblocked and six advanced to their next blocker
(`picorv32.v` itself now parses 1986 lines further but still does not
format — its next blocker is `restrict property`, item 7 below). The
real payoff was the workspace index: `picorv32`, `picorv32_axi` and
`picorv32_wb` now index (521 → 530 modules), taking cross-file external
resolution from 87.0% to 93.6% on cleanly-parsed files. The instantiation
half followed in `docs/features/directives-in-instances/README.md`: the
same construct inside an *instantiation's* `#( ... )` overrides or an
instance's `( ... )` connections, which unblocked the remaining 6 files.
**No corpus file is blocked on a compiler directive any more**
7. DPI, concurrent assertions (`assert property`), non-simple casts
8. Interfaces/modports, `case ... inside`, streaming operators, specify
blocks, `let`/`checker`, sequences — rare in the corpus RTL
Like ruff, `vfmt` refuses to output anything for a file it cannot fully
parse, so it can never corrupt code.
## Editor setup
`vfmt-server` is a language server: one binary, LSP over stdio, the same
answers in every editor. It ships formatting, diagnostics as you type, semantic
highlighting, hover (including `` `define`` expansion), go-to-definition,
references and document/workspace symbols — the full list, and what is
deliberately *not* advertised yet, is in
`docs/features/vfmt-server/README.md`.
**The binary comes from the same build as the CLI**, and nothing downloads it
for you:
```bash
cargo build --release # target/release/vfmt-server (and target/release/vfmt)
cp target/release/vfmt-server ~/.local/bin/ # anywhere on PATH
```
Every editor below defaults to finding `vfmt-server` on `PATH`; each also
accepts an absolute path if you would rather leave the binary in `target/`.
**VS Code** — a thin extension in `editors/vscode/` whose entire job is
registering the file types and starting the server:
```bash
tools/release.sh # builds dist/vfmt-<version>.vsix
code --install-extension dist/vfmt-0.2.0.vsix
```
Sideloading that `.vsix` is the supported install; the extension is not on any
marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
npx @vscode/vsce package`.
One setting, `vfmt.serverPath`. Full steps, F5 development flow and
troubleshooting: `editors/vscode/README.md`.
**Neovim / Vim** — no plugin, just configuration. Neovim 0.11+:
```lua
vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog' } })
vim.lsp.config('vfmt', {
cmd = { 'vfmt-server' },
filetypes = { 'verilog', 'systemverilog' },
root_markers = { 'vfmt.toml', '.vfmt.toml', '.git' },
})
vim.lsp.enable('vfmt')
```
`nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents:
`editors/nvim/README.md`.
**Checking the server without an editor.** `node editors/vscode/smoke.js
<path-to-binary>` spawns it exactly as the extension does and drives a whole
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
One caveat, stated up front: the server does **not** read `vfmt.toml` yet, so
formatting through an editor uses the defaults (100 columns, 2-space indent)
with the editor's tab size overriding the indent. `vfmt` on the command line
does read it.
## Contributing / workflow
This is a solo project — committing directly to `master` is allowed and
expected; no PRs or review required.
## Building
```bash
cargo build --release # binaries at target/release/{vfmt,vfmt-server}
cargo test # unit + snapshot + idempotency tests
```
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
## Install and releases
There are no prebuilt downloads: you build the artifacts, or someone builds
them for your platform and hands you the files.
```bash
tools/release.sh # release binaries + the .vsix + SHA256SUMS, into dist/
```
`dist/` then holds `vfmt-<version>-<host-triple>`,
`vfmt-server-<version>-<host-triple>`, `vfmt-<version>.vsix` and `SHA256SUMS`
(verify with `cd dist && shasum -a 256 -c SHA256SUMS`). Copy the two binaries
onto your `PATH` and sideload the extension with `code --install-extension`.
The script builds for the host triple only and publishes nothing anywhere.
Release notes are in [`CHANGELOG.md`](CHANGELOG.md); the full checklist —
where the version number lives, how the `.vsix` is packaged, and what
marketplace publishing would take if it ever happens — is in
[`tools/RELEASING.md`](tools/RELEASING.md). vfmt is MIT licensed
([`LICENSE`](LICENSE)).