workspace-index (vlog_semantic): cross-file resolution -- the
owner's `import pkg::*;`-anywhere requirement delivered.
WorkspaceIndex maps modules/packages/file-scope typedefs, package
exports, module ports/params and per-file define tables; built
tolerantly (broken files still contribute), deterministic by
construction (FileIds assigned after path sort). resolve_external
answers ExternalCandidates in a two-layer overlay keyed by
ReferenceId -- Semantics stays a pure single-file fact; local
declarations outrank imports. Corpus: 87% of external candidates
answered (external rate 19.6% -> 2.6% on clean files), ambiguity
kept honest (OpenTitan prim_generic/prim_xilinx), 0.7s build,
workspace_symbols substring search.
name-spans (vlog_parser): the approved vlog-semantic handshake --
the parser records every declared name's span at parse time (28
fields across 21 node kinds; Name/ImportPath bundles where parallel
Vecs could desync; ImportPath splits p::x for the index). Content-
pinned by the exhaustive walker on every source, mutation-tested
three ways, zero behavior change (corpus md5 exact, QA byte-compared
formatter output against a HEAD worktree). scan.rs is now one
consumer away from deletion (DataType span, handshake item 2).
TODO §6 foundations complete: spans, error recovery, define table,
single-file semantics, workspace index. Next: vfmt_server.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{workspace-index,name-spans}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
vfmt — a Verilog/SystemVerilog formatter in Rust
An opinionated, fast formatter for Verilog-2001 and SystemVerilog RTL, built
in the image of ruff's formatter, with
layout conventions borrowed from
Verible's verible-verilog-format.
# format files / directories in place (like `ruff format`)
vfmt rtl/ tb/top_tb.sv
# 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/
# 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, or --check/--diff found nothing to change |
| 1 | --check/--diff only: at least one file would be reformatted (nothing written) |
| 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.
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:
vfmt.tomlin the directory — used if present;- else
.vfmt.tomlin the directory; - else, if the directory contains
.git, stop: no config (the.gitcheck comes after 1–2, so a config file in the repo root is still found); - 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.
# 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.
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/vfmt |
the ruff CLI |
File discovery, in-place rewriting, --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).
- 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/`includeand(* attributes *)passed through verbatim
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.
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, allcasekinds withunique/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 generateregions and module-levelif/for/case- Functions and tasks (ANSI and old-style port declarations)
typedef(aliases,enum, packedstruct/union)- 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/endandfork/join, case-item andif/elsebodies, 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
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:
Macro invocation at module-item / statement position (— done; see`ASSERT_INIT(...)style)docs/features/macro-items/README.md. Unblocked 179 corpus files and moved the parse rate from 35.2% to 57.1%- Classes/constraints (mostly blocks DV/UVM code, not RTL) — now the top
blocker at 142 files, all
extends binddirectives- Dynamic arrays and queues
- Declarations with identifier (typedef'd) types in some positions
(
my_t [N-1:0] x;) `ifdef/`define/`includeinside a port, parameter or enum list (they are accepted at item and statement position already)- DPI, concurrent assertions (
assert property), non-simple casts - 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.
Contributing / workflow
This is a solo project — committing directly to master is allowed and
expected; no PRs or review required.
Building
cargo build --release # binary at target/release/vfmt
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.