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]>
alignment
Goal
Infer, from the spacing the author already wrote, whether a run of similar
lines is meant to be aligned (padded to a common column) or flush-left
(one separator between tokens), and reproduce that intent. This is Verible's
most-loved formatter feature and the reason RTL teams tolerate a formatter at
all: hand-aligned port lists, connection lists and parameter tables are how
Verilog is read, and a formatter that flattens them is a formatter nobody
runs. vfmt's rule is Verible's, minus the configuration surface: four or more
excess spaces before a column's token means "align this", a group already
sitting at one column stays there, and everything else formats exactly the way
it did before this feature existed. The two layouts are fixed points of each
other, so format(format(x)) == format(x) still holds by construction rather
than by luck.
Assumptions
- Four excess spaces is the threshold.
HINT_EXCESS = 4inalign.rs, matching Verible. "Excess" is measured against what the flush layout would write in that position, not against zero: one space before a declaration's name, none before a connection's(. Solocalparam int A = 1;(five spaces) is a hint andlocalparam int A = 1;(four) is not. - A tab counts as one space. vfmt's
no-tabslint wants them gone anyway, and guessing a tab stop would make the verdict depend on a setting the formatter does not have. - A group is a run of adjacent rows of one construct. Alignment never reaches across constructs, across a comment, or across a blank line at item level. It is not a whole-file column solver.
- Only whole rows align. A row holding a comment inside it has no flat width, so it drops out of every group rather than being measured with a guess.
- A hint outranks fitting on one line. Because an aligned list is a broken
list,
module m (input wire a, output logic b);— five spaces where one would do, on a list that fits — is exploded into three lines and aligned. Five excess spaces is read as deliberate wherever it is written; treating a one-line list as a special case would mean the verdict depended on the layout rather than on the spacing, and the layout is what the formatter decides. Zero corpus files were affected. - The trailing comment is not part of the line budget. A
// ...written after an aligned row can push that line past the line limit exactly as it can push a flush row past it. Counting it would let one long comment veto a whole group's alignment, which is worse than a long line; Verible does not count it either. Measured cost on the corpus: 2 lines in 578 files. - The AST's nesting is the printed indentation. The line-budget check
needs to know the column a row starts in, and it takes it from a
depththreaded through the item walk rather than from the printer. That mapping (depth * indent_width) is exact for every construct that aligns today; if it ever drifts, the consequence is a worse alignment verdict, never a wrong one, because the depth is a pure function of the AST and therefore identical on both passes.
The rule as shipped
A row is one element of a candidate construct, split into cells at the
positions that may be aligned. cells[k + 1] starts with the token that opens
column k:
| Construct | Cells | Columns |
|---|---|---|
| ANSI port | input wire [7:0] / data |
name (flush 1, min 1) |
| Named connection | .data_i / (bus) |
( (flush 0, min 1) |
parameter/localparam item |
localparam int / WIDTH / = 8 |
name, = (both 1/1) |
flush is what the unaligned layout writes before the column; min is what
the widest row of an aligned group gets. They differ only for connections,
whose flush spelling is tight (.clk(clk)) and whose aligned spelling is not
(.clk (clk)).
For a run of rows, let gap[i][k] be the horizontal whitespace the source
wrote immediately before row i's column-k token, col[i][k] its source
column, and w[i][k] the flat width of cell k. The run is laid out
aligned when all of the following hold:
- it has at least two rows;
- every row's cell 0 is non-empty and every row's cells have a flat width (no comment inside a row);
- there is something to pad: for some column
k, thew[i][k]are not all equal; - the author asked, either
max(gap[i][k] - flush[k]) >= 4— some row carries four excess spaces; or- every column is internally consistent (
col[i][k]equal overifor eachk) andmax(gap[i][k] - flush[k]) >= 1— the group is already sitting at one column;
- the widest aligned line fits the line budget:
max_width - depth * indent_width.
Otherwise the run is flush — today's layout, byte for byte.
The columns of an aligned run are computed from the run's own widths, never from the columns the author used:
target[0] = max_i(w[i][0]) + min[0]
target[k] = target[k-1] + max_i(w[i][k]) + min[k]
extent = target[last] + max_i(w[i][last+1] + tail[i])
tail is the , a list element takes or the ; a declaration ends with.
An aligned list is a broken list: alignment means nothing with every
element on one line, so a planned group forces its list one-element-per-line.
Group boundaries
A run ends at anything that will still be visible to the next pass:
- a standalone comment or an
(* attribute *)on the element — both print on their own line; - a compiler directive written between two elements of a list;
- a blank line, at item level only.
delimiteddeliberately drops blank lines between the elements of a bracketed list, so a boundary drawn at one would vanish from the output and the next pass would group differently. In a port or connection list a blank line is therefore not a boundary. - a row that cannot be aligned at all: a port with no type prefix (
output a, b), a.*or implicit.name, a positional connection, a parameter with two declarators or no value, a fenced item, a row with a comment inside it.
A comment written between an element and its comma (Meta::before_sep) is
not a boundary: it prints on the element's own line and does not move the
columns.
The fixed-point argument
Everything above is decided while the document is built, from the source text and the AST's nesting. Nothing is decided by the printer, because a decision the printer made would not be visible to the next pass. That is what makes the following exhaustive.
Take a run that formatted aligned. Its output has, for every column k,
every row's token at the same output column (rule 4's second clause is
satisfied); the widest row gets min[k] spaces, so its excess is 0, and the
narrowest gets min[k] + max_i(w[i][k]) - min_i(w[i][k]) >= min[k] + 1, so
max_excess >= 1 — provided the widths differ, which rule 3 guaranteed. Rule
5 held for the widths that produced this output and the widths are unchanged,
so it holds again. The next pass therefore re-derives aligned, recomputes the
same targets from the same widths, and emits the same bytes. Fixed point.
Take a run that formatted flush. Every gap is exactly flush[k], so every
excess is 0: rule 4's first clause fails, and its second needs max_excess >= 1, so it fails too. The next pass re-derives flush. Fixed point.
The two hazards this design had to close, both of which are real and both of which cost a debugging round:
- Equal widths. Without rule 3, a run like
input wire a,/input wire b,would be "aligned", but padding to equal widths writes the flush bytes — and the next pass, seeing zero excess, would say flush and re-flow the list onto one line. Rule 3 makes the first pass say flush too. - A verdict split across phases. The line-budget check (rule 5) first
lived in the printer, which knows the real column, while the forced break
lived in the document. When the printer backed out, the forced break stayed,
and an enclosing
#( ... )group measuredfitsdifferently on the next pass —corpus/ibex/rtl/ibex_core.svat--line-length 60diverged. The fix was to move the budget into the document build, which is whydepthis threaded through the item walk at all. Regression test:a_group_that_alignment_gives_up_on_still_convergesintests/verification.rs.
One-pass convergence follows the same way: a hinted run (rule 4, first clause) produces aligned output whose shape satisfies rule 4's second clause, so pass 2 agrees with pass 1. An author who over-padded — aligned at column 40 when 30 is enough — gets column 30 on pass 1, because the targets come from the run's widths, and column 30 again on pass 2. That is a change to the author's bytes, but it converges immediately and is the only way two people's tables can agree.
Handshakes
Consumed from vlog_parser:
AnsiPort::name_span,ParamPort::name_span,Connection::name_span,Declarator::name_span,Expr::span,Item::span— the byte offsets the anchors are derived from. Nothing new was added to the lexer or totoken.rs: the minimal representation of "excess space before a token" is no representation at all. The anchor's byte offset plus the source text the formatter already holds (Fmt::src) yields both the preceding gap and the token's column by a backward scan of at most one line. Adding a field toTokenwould have duplicated a fact the spans already carry and put new weight on the losslessness/spans suite for nothing.- The comment attachment contract (
Meta::leading,Meta::attrs,Meta::before_sep), which is what group boundaries are drawn from.
Consumed from vlog_formatter:
Config::max_width/Config::indent_widthfor the line budget.fence::region_at(viaFmt::is_fenced) to keep fenced items out of groups.
Promised to the rest of the formatter:
align::render(cells, specs, None)writes exactlyspecs[k].flushspaces between cells. Every construct that grew cells must produce, in that mode, the same bytes it produced before — that equivalence is what makes "give up on alignment" indistinguishable from "never considered it".verify.rsis untouched, and no normalization was widened. Alignment only ever inserts spaces between two tokens that already had whitespace between them, which the token-stream equivalence check ignores by design.doc.rsandprinter.rsare untouched: padding isDoc::Textcomputed at build time.
Requested of nobody. No other crate changed; vlog_semantic,
vlog_linter and vfmt_server compile and pass unmodified.
Status / TODO
- Inference rule, written down before it was implemented
crates/vlog_formatter/src/align.rs:ColSpec,Row,Align,plan,render,flat_width,gap_before,column_of+ unit tests- ANSI port declarations in module headers — name column
- Named connections in instance connection lists — the
(column parameter/localparammodule/package/class items — name and=columns- Group boundaries: standalone comment, attribute, directive, blank line (item level), unalignable row
- Line-budget fallback, whole group at a time, decided at build time
depththreaded through the item walk so the budget knows its column- 39 cases in
tests/cases/alignment.cases - Four convergence tests at non-default widths in
tests/verification.rs - Zero churn on the pre-existing 397-case table and the fixture snapshots
- Corpus: 0 verification errors, 0 crashes, 0 round-trip failures
README.mdStyle section,TODO.md§2- Parked: parameter ports in a
#( ... )list (module and class headers). Structurally identical to an ANSI port row and nearly free to add, but it doubles the test matrix for a construct that is usually two or three entries long. Next thing to do here. - Parked: parameter overrides in an instantiation's
#( ... ). Same shape as a named connection; the same argument applies. - Parked: the direction/type column of a port list (
inputvsoutput) and the type column of a declaration. Verible aligns these as separate columns; vfmt collapsesinput wiretoinput wire. Adding them means a row's first cell splits too, and the hint rule then has to decide what a group means when one column is hinted and another is not. - Parked: the trailing-comment column. Verible aligns
// ...after a port list; vfmt writes one space. This is the most visible remaining gap on real RTL. - Parked:
wire/logicdata declarations andstructmembers. Both are ordinary declaration rows; neither has the same cultural pull as the three shipped constructs.
Work log
2026-08-19 — dev
- Read
TODO.md§2,docs/features/format-fences,docs/features/comments-roundand the Verible-derived style rules inREADME.md. Wrote the rule above before writing code, including the fixed-point argument, then implemented it. - Lexer trivia: nothing added. The task allowed
lexer.rs/token.rsfor trivia. The minimal representation turned out to be none:Tokenalready carriesline/col/span, and every construct that aligns already carries aname_span(from thename-spansfeature), so "excess space before this token" isgap_before(src, anchor)— a backward scan over spaces from the anchor's byte offset — and "the token's column" iscolumn_of(src, anchor). Both are derived on demand inalign.rsfromFmt::src. The losslessness/spans suites are therefore untouched, which was the point of the constraint. - Splitting each construct into cells is the only change to existing layout
code:
ansi_port_cells,connection_cells,param_decl_cells. The first two replace the old single-document builders outright, so the flush path is the aligned path with zero-width padding and the two cannot drift.param_declkeeps its legacy body for the unaligned case, becausedeclaratorsis shared with three other constructs and rewriting it would have risked churn for nothing; the equivalence of the two spellings is pinned by theparams: an aligned line past the limit takes the group back to flushcase. - First design, backed out. The line-budget check originally lived in the
printer as a new
Doc::Pad { to, cost, flush }node, because the printer is the only thing that knows the real column. That works for the padding but not for the verdict: the forced one-element-per-line break was decided at build time, so when the printer backed out the break stayed, and an enclosing group'sfitschanged between passes. Caught by a 2312-run config sweep over the corpus (--line-length 60oncorpus/ibex/rtl/ibex_core.sv), not by the default-width suites. Replaced by adepth: usizethreaded throughitem_seq/item_docs/item_kindand the constructs below them;doc.rsandprinter.rswent back to their original contents. The lesson is worth keeping: a layout verdict may not be split across the document/printer boundary, because only the document is visible to the next pass. - Verified, in order:
cargo test --workspacegreen, with zero churn: every one of the pre-existing 397 table cases, both fixture snapshots, the fences suite and the 74 verification tests pass unmodified. Baseline 642 → 653 passing, the difference being 7 newalign.rsunit tests and 4 new convergence tests.- Corpus (820 files,
tools/corpus_check.sh): outcome per path is byte-identical to the baseline TSV (same md5). 0 verification errors, 0 crashes, 578/820 formattable as before. The classification did not move because no previously-clean file was aligned differently and no would-reformat file became clean — alignment changes how a file is reformatted, not whether it is. - Output delta: 291 of 578 formattable corpus files (50.3%) now format differently — the feature reaches half of real RTL.
- Round-trip: all 578 formattable files re-formatted from their own output, 0 divergences.
- Config sweep: 578 files × 4 configurations (
--line-length 60,--indent 4,--line-length 120,--indent 8 --line-length 200) = 2312 runs, 0 failures. This is what caught the design bug above. - Line discipline: 2 lines in 2 files exceed 100 columns that did not before, both because a trailing comment follows an aligned row. Documented under Assumptions.
QA log
2026-08-19 — QA
Verified claims 1-5. Result: PASS, no blocking findings.
- Static review.
align.rsread in full against the rule as written: rows/cells/columns,HINT_EXCESS = 4, the fourplan()guards (row count, cell-count/anchor-count match, non-empty first cell, "something to pad"),wants_alignment's global (not per-column) hint test,render'ssaturating_sub/min-floor padding. Matches the README's rule description exactly.doc.rs,printer.rs,verify.rs,fence.rs,vlog_parser/src/lexer.rs,vlog_parser/src/token.rs:git diff --staton each is empty — confirmed untouched, as claimed. - Tests.
cargo test --workspace: 655 passed, 0 failed (matches the README's "655 workspace tests" exactly: 28+63+45+109+5+22+1+4+6+2+78+71+30+ 84+24+19+17+6+1+19+20+1 = 655). All 4 new convergence tests present and green (an_aligned_group_is_a_fixed_point_at_every_width,a_group_that_alignment_gives_up_on_still_converges,a_hint_converges_in_one_pass_and_then_holds,a_flush_group_stays_flush).crates/vlog_formatter/tests/cases/alignment.casesparses to 39 cases (independently counted with the same====-splitting rulecases.rsuses).cargo clippy --all-targets -- -D warnings: silent, on both the default lint set and with warnings promoted to errors. No#[allow]was added anywhere in the diff. Zero churn:git status --porcelainontests/shows onlyverification.rsmodified (pure appends — the diff is+88lines, no line removed) and one new untracked.casesfile; every pre-existing.casesfile, both fixture snapshots, and the fences suite are byte-for-byte untouched. - Corpus (claim 3).
tools/corpus_check.shrun twice on the 820-file corpus: outcome TSV byte-identical, md5b74f2f167c57e381d46f3503363a79b3both times (matches the claimed prefix). 578/820 formattable (70.5%), 0 verification-error, 0 crash, 0 other-error on both runs. Content delta re-derived independently: built a HEAD worktree (commit7f2e78f, pre-alignment) inscratchpad/head-worktree, formatted all 578 formattable files under both binaries and diffed — 291/578 differ, exactly the claimed count. Round-trip: all 578 files formatted-from-their-own-output are byte-identical to that output — 0/578 failures. Long-line cost: countedlength > 100output lines per file under both binaries; exactly 2 files gained exactly 1 long line each (corpus/ibex/dv/formal/check/peek/alt_lsu.sv:30,corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2.sv:43), both a trailing//comment after an aligned port row — matches the Assumptions section's "2 lines in 2 files" claim exactly, confirmed by inspecting both lines directly. - Config sweep (claim 4). 578 formattable files × 2 configs
(
--line-length 60,--indent 4) = 1156 runs via--stdout: 0 abnormal exits (no crash, no nonzero-beyond-1 status). This is a reduced version of the full 4-config sweep the work log already ran; it adds nothing the dev's own 2312-run sweep didn't already cover, but reproduces cleanly. ibex_core.svregression (claim 2, design-bug story). Reproduced at--line-length 60: the current code converges (vfmt --checkclean after one pass, andtwice()-style double-format is byte-identical). The regression testa_group_that_alignment_gives_up_on_still_convergesintests/verification.rsexercises the same shape (prim_buf #(...) u_buf (...)) at widths 40-100 and all converge.- Fixed-point hunting (targeted attacks, debug binary, 4 passes each,
widths 40/60/80/100/120, indent 2 and 4 where relevant). All of the
following converge, with the specific behavior noted:
- Excess boundary. A row at exactly 4 excess spaces aligns (rule 4,
>=4); 3 excess with inconsistent source columns stays flush and collapses to one line. Boundary is exactly where the rule says it is. - Over-padded group (author aligned far past the computed width): collapses to the narrower computed target on pass 1 (target is a function of the run's widths, never the author's columns, exactly as the README's fixed-point argument describes) — output was byte-identical to the minimally-hinted case. Not a 2-pass settle; a 1-pass correction.
- Under-aligned (gaps below threshold, source columns inconsistent): flush, collapses to one line, stable.
- Tabs in the gaps: 5 tabs (byte-gap 5) trips the same
>=4hint as 5 spaces would, and the aligned output is written with spaces regardless (render always emits" ".repeat(pad)) — no tab ever survives into aligned output, so there is nothing for a later pass to reinterpret. - Generate-nested budget crossing: swept width 50-65 in 1-column steps around the point a nested nested-generate connection list's budget flips the group from aligned to flush (crosses between width 55 and 60 in the probe) — converged at every width, both sides of the boundary, indent 2 and 4.
- 1-row vs 2-row groups: a lone hinted port/param never aligns (rule
1); confirmed via
p15_one_row_hint.svand the pre-existing unit test. - Hint in one column of a two-column param group: hint on the
=column only (name column at flush spacing) aligns both columns —wants_alignment'smax_excess/one_columnaccumulate across all columns of the group before the single yes/no decision, so a hint anywhere aligns the whole row. This matches the rule as documented (rule 4 is stated once per run, not per column) — not a bug. .*in the middle of a connection list: splits the list into two 1-row runs around it (aNonerow can't be spanned), so neither side aligns even with hinted spacing on both real connections — correct per "at least two rows" and the unalignable-row boundary rule.- Directive between hinted param rows: the directive is itself a
non-
ParamDeclitem, so it acts as an unalignable row exactly like.*above — both sides become 1-row groups and stay flush. This is a structural consequence ofparam_decl_aligns(directives aren't threaded into itsbreaksarray the waylist_breaksthreadsListDirectivefor ports/connections — see note below), not a bug, and it converges. - CRLF file with hints: converges; output is LF-normalized, which is pre-existing general formatter behavior unrelated to alignment (not re-verified here beyond confirming it doesn't interact badly with alignment).
- Multi-byte content: non-ASCII in an identifier is correctly
rejected by the lexer (not an alignment concern). Multi-byte content in
a param's string value (é/λ characters, ~90 chars wide) converges at
widths 40-120 —
flat_widthuses.chars().count(), so budget/target math is char-width-correct, not byte-length-correct. - Blank line in a port list: does not break the group (per rule,
delimiteddrops list-level blank lines) — confirmed aligned across it. - Fenced region containing an aligned-looking group: bytes emitted verbatim, completely untouched by alignment — confirmed byte-for-byte.
before_sepcomment on a port (clk /* c */,): does not break the group — confirmed aligned across it, matching the documented rule literally (comment before the comma).before_sep-shaped comment on aparameterdeclarator (= 1 /* c */;, i.e. before the;): does make that row unalignable (checked explicitly inparam_decl_rowviadecl.meta.before_sep), splitting the group. This does not contradict the README: the "before_sep is not a boundary" sentence in Group Boundaries is scoped to "an element and its comma" (list items), andparameteritems end in;, not a comma, and aren't printed through theListItem/delimitedmachinery that makes the port/connection accommodation possible. Filed here only so the next reader doesn't trip on the same apparent inconsistency I did; not a finding, not an action item.
- Excess boundary. A row at exactly 4 excess spaces aligns (rule 4,
- Sabotage attack (claim: two hazards, tested). Disabled the "something
to pad" guard in
plan()(if false && (0..cols).all(...),align.rsline 86) and rebuilt. Result:- The direct unit test
align::tests::equal_widths_have_nothing_to_alignfailed immediately, as expected. - More importantly: constructing the exact scenario the README predicts
(three equal-width ports,
input wire clk/rst/ena, single hinted column) and running the debug binary's ownformat_sourceon it did not silently corrupt anything — it refused to produce output at all:verification failed: formatting is not idempotent; line 1 changed from "module m (" to "module m (input wire clk, ...);". This isformat_source's own internal double-pass check catching the exact flip-flop the README describes (pad-to-equal-widths on pass 1, see zero excess and collapse to one line on pass 2) for any input that would trigger it — not just the one unit test. That is hard invariant 1 (no partial output, verified-correct or unchanged-with-error) working exactly as designed against a real regression in this module. - Reverted via a pre-sabotage backup (
md5 4827dcb78431e784b6273b1ed29ae7c7before and after);cargo test -p vlog_formattergreen again post-revert (78/78 inverification.rs, 9/9 inalign's own unit tests).
- The direct unit test
Findings: none blocking. One documentation-adjacent observation (not a
defect, not actioned): the before_sep-on-a-parameter-declarator behavior
above is correct but easy to misread against the general Group Boundaries
wording if you don't notice the "and its comma" qualifier — worth keeping in
mind if that section is ever edited, but not asking for a change now.
Not independently re-verified (time-boxed out; covered by the dev's own
work log and not flagged by any attack above): the exact byte-for-byte
equivalence of align::render(..., None) against the pre-feature flush
output for every corpus construct (spot-checked via the 291/578 content-diff
and the 39-case table, not diffed construct-by-construct against the old
formatter).
Review
2026-08-19 — lead. Verdict: accepted; commits jointly with format-cache (round 17). Verible's most-loved feature, delivered without bending a single invariant.
Points reviewed and accepted:
- The fixed-point argument is written before the tests and the tests confirm it — the two guards (something-to-pad; whole verdict at build time) are each load-bearing, and the design bug the config sweep caught (the printer-side Pad splitting the verdict) is exactly the failure mode the whole-verdict rule exists to prevent. Finding it via a 2,312-run sweep before QA is the standard; QA's sabotage then showed the runtime net catches even the predicted flip-flop with the unit test deleted — invariant 1 holds structurally, not by test coverage.
- Zero lexer footprint — name_span plus the source answers every spacing question, so losslessness/spans/token suites are untouched. The feature that most tempted new trivia needed none; the foundations paid for themselves again.
- "Alignment changes how, not whether" made observable: the corpus outcome TSV is byte-identical while 291/578 files change content — the cleanest possible statement of a style-only feature, and QA re-derived both halves from a HEAD worktree.
- Honest costs stated: the 2-lines-over-100 trailing-comment exception (a long comment must not veto a group), the parked constructs (#() lists, direction/type column, trailing-comment column — the most visible gap), and QA's parameter-before_sep scoping note now logged so the next reader doesn't trip.
The author-intent rule shipped matches Verible's culture: ≥4 excess spaces or existing consistent columns opts in; single-space code stays exactly as vfmt always wrote it — no existing user's output moves unless they asked.