Files
lucisv/docs/features/range-formatting/README.md
T

718 lines
40 KiB
Markdown

# range-formatting
## Goal
Format only the lines the caller names and emit every other byte exactly as it
was written — `lucisv --lines M-N[,M-N...]`, and `textDocument/rangeFormatting`
on the same engine. This is the adoption story for a legacy tree: a formatter
that can only rewrite a whole 2000-line file is one that never gets turned on,
because the first patch it touches becomes unreviewable. Verible ships
`git-verible-verilog-format.sh` on top of exactly this, and `tools/lucisv-changed.sh`
is our version. A range is morally an **inverted fence**: the same
`Doc::Verbatim` splice `docs/features/format-fences/README.md` built, over
byte ranges the *caller* chose instead of ranges a comment marked.
## Semantics
### The unit is one item
> **An item whose lines meet a requested range is laid out exactly as a
> whole-file run would lay it out. Every other item is emitted as the source
> bytes it was written with.**
An **item's lines** are its whole *unit*: its leading comments, its
`(* attributes *)` and code, and the comment written after it on the same
line. Two consequences worth stating:
- Selecting a doc comment selects the declaration under it. The comment is
part of the unit, and laying out half a unit is not a thing the printer can
do.
- Selecting a **blank line** selects nothing. A blank line belongs to no
item, so a range that only covers blank lines leaves the file untouched.
This matters more than it sounds: without it, a range hitting the gap
between two items would descend into the module around them and normalize
the gaps at the boundaries for no reason at all.
A scope's **dangling comments** (the ones after its last item) are units of
their own, selected the same way.
### One level down: modules and packages are descended into
"An intersected item formats whole" is too coarse for the use case — *I edited
three lines of a 2000-line module*. So a **module** or a **package** whose
body contains a selected item is cut into three:
| part | what it is | when it is laid out |
|---|---|---|
| head | leading comments through the `;` that closes the header | its own lines are selected |
| body | the item list, planned recursively | per item, by the rule above |
| tail | the `endmodule`/`endpackage` line, its trailing comment included | its own lines are selected |
The three decisions are independent: editing the port list lays out the header
and leaves the body alone; editing one declaration lays out that declaration
and leaves the header and the closing keyword alone.
**Only modules and packages.** A `generate` region, a `class`, a
`begin`…`end`, a function or a task is **one unit**: selecting a line inside a
generate region lays out the whole region. They are item scopes too, but they
have no header worth keeping apart from their body, and the two shapes above
are the ones that are thousands of lines long in real RTL. Lifting this is a
small change to `scope_of` plus a head/tail doc for the new kind; it is not
done because nothing yet needs it.
**Statements are never descended into, deliberately.** Selecting one line of
an `always` block lays out the whole block. Going a level deeper means
splitting statement lists the same way item lists are split, which is a second
copy of the machinery for a case nobody has asked for; the item level already
buys the two-thousand-line-module win.
### A module that cannot be cut
The head/tail slices are emitted at column zero and carry their own
indentation, so every boundary has to fall on a line of its own. A module
written `module m; wire a; endmodule`, or one with an empty body, has no such
line: it is one unit, laid out whole or not at all. Same for a package.
### Runs
Consecutive unselected units are merged into **one** verbatim slice rather
than emitted one at a time. This is not an optimization — it is what makes
"everything else verbatim" true. Emitted separately, each unit would get an
item separator between it and the next, and the separator normalizes runs of
blank lines to one. Merged, the blank lines are *interior bytes of the slice*
and survive exactly.
### What still changes outside the range
Three things, all of them the same normalizations a fenced region already
lives with, and all tested:
1. **The file's tail.** Exactly one final newline, as in every run.
2. **Blank lines at a boundary.** The gap between a laid-out item and the
verbatim run next to it is written by the item separator, which collapses
two or more blank lines to one. Inside a run nothing is touched.
3. **Line terminators the formatter writes are `\n`.** A `\r` between two
units is inter-unit whitespace and nobody emits it; a `\r` *inside* a run
is an interior byte and survives. This is what a whole-file run already
does to a CRLF file, so it is consistent rather than new.
## Ranges
`--lines` takes 1-based, **inclusive** line ranges: `M-N`, a bare `M` for one
line, comma-separated (`3-9,40`) and repeatable (`--lines 3-9 --lines 40`).
The two forms mean the same thing; ranges are sorted and merged, and adjacent
ranges (`1-2,3-4`) fold into one because that changes no answer.
| input | answer | why |
|---|---|---|
| `5-1` | **error** | a reversed range is a typo, not an intent |
| `0`, `0-3` | **error** | lines are 1-based; `0` is a caller bug |
| empty piece (`1,,2`), empty spec, `x`, `1-2-3` | **error** | unparsable |
| `900-1000` on a 20-line file | **clamped**, i.e. it matches nothing | a wrapper deriving ranges from a diff cannot know where the file ends, and refusing would make the wrapper's job harder for no safety gain |
The parse happens during argument handling, so a bad spec exits 2 before any
file is read.
## Interaction rules
### `// verilog_format: off` outranks `--lines`
A fenced item is never laid out, whatever the caller selected. `off` means
hands off across all of lucisv (the position `docs/features/shared-fence-filter/README.md`
already took for `--fix` and the server's quick fixes), and a range is a
weaker signal than a comment somebody wrote into the source. Mechanically the
planner asks `fence::region_at` before it asks about lines, and the two
region lists are merged into one sorted, non-overlapping list, so the fence's
own bytes are emitted by the fence's own opener.
One case reads oddly and is correct: the `on` fence is the *leading comment*
of the item after the region, so selecting the `on` line selects that item.
The region itself still does not move.
### Alignment groups break at a range boundary
Alignment groups are mostly per-list *inside* one item — a port list, a
connection list — and those travel with their item, so a range boundary can
never fall inside one. **The exception is `param_decl_aligns`**, which groups
consecutive `parameter`/`localparam` *items* in a scope, and a range boundary
can absolutely fall inside that.
The answer needed no new code: `param_decl_row` already returns `None` for an
item inside a verbatim region (it was written for fences), and generalizing
that predicate from "fenced" to "verbatim" is the whole change. So an
unselected member leaves the group and keeps its bytes; the selected members
form their own group and align among themselves; a lone selected member has
nothing to align to and formats flush. Both passes see the same split, which
is why it is still a fixed point.
```systemverilog
// --lines 2-3
localparam int A = 1; // selected: these two align to their own column
localparam int BBBBB = 2;
localparam int C = 3; // not selected: byte-for-byte as written
```
### A file that does not parse is refused
Range formatting cannot rescue broken input. `format_range` calls the same
strict `parse_source` as `format_source`, so a parse error is an error and an
untouched file (exit 2), even when the range names none of the broken lines.
The tolerant parser exists for the LSP's diagnostics, not for the formatter —
splicing verbatim bytes around an `ItemKind::Error` would mean printing a
guess about code we could not read.
## Safety
The runtime net runs over the **whole output**, unchanged, and `verify.rs` was
not touched — no normalization was added, broadened or weakened, so CLAUDE.md
hard invariant #4 does not apply to this round.
- **Equivalence** (`verify_equivalence(source, output)`) is global and exactly
as strong as always. It holds by construction — a verbatim slice re-lexes to
the tokens it came from, and a laid-out item is ordinary formatter output —
and it is the backstop that catches any mistake in that reasoning. It
earned its keep during development: the first version of the split computed
the body's end from the last *item* and forgot the scope's dangling
comments, so the tail slice re-emitted a comment the run had already
emitted. Equivalence rejected it immediately.
- **Convergence** is the half that needed thought, because a *line* range is
not a stable name for anything once the text moves.
### Convergence: replay the decisions, not the line numbers
`format_range` runs:
1. `select(source, tree, lines)` → a `Selection`: one `Pick` per unit
(`Verbatim`, `Format`, or `Split { head, tail }`), in the order a
depth-first walk over item scopes visits them.
2. `format_selected(source, selection)` → the output.
3. `verify_equivalence(source, output)`.
4. `format_selected(output, selection)` — the **same** selection, replayed.
5. `verify_convergence(output, again)`.
The replay is sound because equivalence already proved the output's token
stream is the input's, comments included; the same tokens parse to the same
item tree, so the same walk visits the same units in the same order and pops
the same picks. What each unit *does* is then a fixed point for reasons the
whole-file formatter already establishes: a laid-out item is formatter output
being formatted again, and a verbatim slice is the same bytes. Alignment
groups are split identically in both passes because the split depends on the
picks, not on the text.
To keep that invariant honest, **the body of a module or package is always
walked, splittable or not**. The shape of the pick list then depends on the
item tree alone, never on whitespace — otherwise a module that was
unsplittable in the input but splittable in the output would consume picks
differently on the replay and the check would fail for a bookkeeping reason.
### Idempotency: what is and is not promised
**Promised, and checked at runtime:** replaying the same selection is a fixed
point. That is what "the output is stable" means for a partial run.
**True in practice, and tested:** running `lucisv --lines M-N` twice on the same
lines changes nothing the second time — *when the first run did not move the
selected lines*. Every hand-written case in `tests/ranges.rs` is of that kind,
which is the normal editing experience.
**Not promised:** the same *line numbers* after the text moved. Laying out a
construct can change how many lines it takes, and the second run's line
numbers then reach different constructs:
```systemverilog
// --lines 1-3, twice
module m #( → module m #(parameter P = 1) (input a); // pass 1
parameter P = 1 → wire x; // line 4 → 2
) (input a);
wire x; → module m #(parameter P = 1) (input a); // pass 2
endmodule → wire x; // now inside lines 1-3
```
That is another correct, fully verified partial run — not a broken fixed
point. Measured on the corpus: of 8236 range trials, 449 (5.5 %) reached
further on a second run with the same line numbers, and **every one of them
settled on that second run** (checked to 12 iterations; none needed a third).
**Also not promised, and this is the feature:** a partial run is not a fixed
point of the *whole-file* formatter. `lucisv` with no `--lines` afterwards will
reformat more. That is the point of having formatted less.
*(Lead note, per lexer-cleanup QA: one more unstated exception to
"every other byte exactly as written" — a leading BOM is dropped by
`--lines`/`format_range` even when line 1 is not selected, because the
lexer consumes it before any range logic runs. Benign: converges,
verifies, and an LSP range edit at offset 0 is legal. Recorded here so
the promise's edges are all in one place.)*
## CLI
```
--lines <M-N> format only the constructs meeting these 1-based, inclusive
line ranges; comma-separated and repeatable
```
- **Format only.** `lucisv check --lines` is an error: the linter has no notion
of a line range (waivers are its equivalent).
- **Explicit files, never a directory.** "Line 12 of everything under `rtl/`"
is not a thing anyone meant, so a directory input is an error. Several file
arguments are accepted and get the same ranges each — defined, but a wrapper
should invoke once per file, which `tools/lucisv-changed.sh` does.
- **Combines with** `--check`, `--diff`, `--stdout`, and stdin (`-`, with
`--stdin-filename`). `--check` exits 1 only if the *partial* format would
change something, which is what makes "CI checks the lines this PR touched"
possible.
- **The cache is off.** A `--lines` run neither reads nor writes it. Reading
would be wrong twice over: a hit skips the file entirely, including the very
lines the caller named; and writing would record a partially-formatted file
under the "already formatted" verdict, which is the one thing
`docs/features/format-cache/README.md` promises the cache only ever stores.
### `tools/lucisv-changed.sh`
The `git diff` half of TODO.md §2's follow-up. It reads `git diff -U0` hunk
headers, turns each `@@ -old +first,count @@` into `first-(first+count-1)`,
and calls `lucisv --lines` once per changed `.sv`/`.svh`/`.v`/`.vh` file. A hunk
with `count == 0` deleted only and contributes nothing. `--check`/`--diff` and
a base revision pass through, so `tools/lucisv-changed.sh --check origin/main`
is the CI form. A `lucisv --diff-base <rev>` flag *inside* the binary is still
open; the script answers the need without teaching the CLI about git.
## LSP
`documentRangeFormattingProvider` is advertised (it was the README's deferred
capability #1) and `format::range_formatting` serves it.
The protocol's `Range` is a half-open span of UTF-16 positions; the engine
wants inclusive lines, so **only the line numbers survive the conversion** —
which sidesteps the whole UTF-16 column question rather than solving it again.
One rule needs stating: an end position at character 0 of a *later* line is
the start of that line, not any of its content (an editor's "select these
three lines" ends at the start of the fourth), so such a range stops one line
short. An end at character 0 on the range's own start line still selects that
line.
The reply is still **one whole-document `TextEdit`**, and only when the text
actually changed. That is not a contradiction with "range formatting": the
engine's contract is all-or-nothing over the file (CLAUDE.md invariant #1),
and what makes the request a range format is which constructs were laid out,
not which bytes the edit is allowed to replace. A refusal produces no edit and
a `window/showMessage`, exactly as the whole-document handler does — the two
now share `Server::edits` and `Server::warn_about_config`.
## Assumptions
- **A node's span is its code extent, comments excluded** — the `spans`
convention. Both halves are load-bearing here, as they were for fences: the
attribute half is why a spliced item reproduces its `(* keep *)`, and the
comment half is why a unit's extent has to be computed as "leading comments
through trailing comment" rather than read off `Item::span`.
- **The formatter is only reachable through `format_source`/`format_range`**,
so the text spliced from is always the text the spans were lexed from.
- **The same token stream parses to the same item tree.** The convergence
replay rests on this; the parser is deterministic and reads nothing but the
tokens.
- **Slicing is char-boundary safe.** Every offset comes from a span or from a
scan over ASCII whitespace. Slices are still taken with `get()`: a `None`
would produce an empty region, which drops tokens, which equivalence
rejects — a failsafe, not a panic. (Multi-byte content is tested at the
engine, CLI-adjacent and LSP levels.)
- **Files are small enough that planning twice is free.** `format_range`
parses three times (once to select, once per pass). At Verilog file sizes
that is microseconds, and sharing a tree between the select and the first
pass would couple two things that are currently independent.
## Handshakes
**Consumed from `vlog_parser`:** `parse_source`, `LineIndex::line_col`,
`Item`/`Meta`/`Comment` spans, and the `Module` / `ItemKind::Package` shapes.
Nothing in `crates/vlog_parser` was changed and nothing new is asked of it.
**Consumed from `crate::fence`:** `collect`, `region_at`, `Region`, and two
helpers that became `pub(crate)` for this round — `line_start` and
`with_trailing_comments`. Both were already the right answer to "where does
this unit's line begin" and "how far does the comment after it reach"; a
second copy would be a second thing to keep in sync. **This is the only change
to `fence.rs`: two `fn` → `pub(crate) fn`, no behavior.**
**Promised to `vlog_formatter` callers:**
- `format_source` is unchanged in signature and in behavior. Verified rather
than argued: the whole-file `--stdout` output of all 578 formattable corpus
files is **byte-identical** to a binary built from the pre-change commit,
and the corpus TSV md5 matches exactly.
- New: `format_range(&str, &Config, &LineRanges) -> Result<String, FormatError>`,
and `LineRanges` (re-exported at the crate root). `range::{Selection, Plan,
Pick, Split, select, plan}` are public for the same reason `fence`'s are —
one definition of the answer — but only `format_range` and `LineRanges` are
meant for outside callers.
**Promised to `crates/lucisv` and `crates/lucisv_server`:** both call
`format_range` and nothing else new. `Options::lines` and
`Options::cache_enabled` are the CLI's own.
**`verify.rs` is untouched.** `git diff --quiet` on it and on
`tests/verification.rs` both exit 0. No normalization was added, broadened or
weakened, so invariant #4's attack-test requirement does not apply — and none
was needed: a verbatim slice is source bytes, so it re-lexes to exactly the
tokens it came from, and the units it replaces are exactly the ones whose
bytes it contains.
**Recursion budget (`docs/features/recursion-limit/README.md`):** unaffected.
The planner recurses only through nested module/package scopes, a subset of
the AST depth the parser already bounds, and builds no tree. `Doc::Verbatim`
is a leaf, as it was for fences.
## Status / TODO
- [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and
zero refused, past-EOF clamped) with unit tests for every spelling.
- [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in
both modes (from lines, and replaying picks), run merging, region
normalization.
- [x] `format.rs`: `format_range`, `format_selected`, `render` extracted from
`format_once`; `Fmt.splits`; `split_at`/`opens_at`/`slice`;
`split_item`/`head_doc`/`tail_doc`; `module()` split into `module_head`
+ body + closing; `is_fenced` → `is_verbatim`.
- [x] `fence.rs`: `line_start` and `with_trailing_comments` → `pub(crate)`.
- [x] `tests/ranges.rs` — 22 tests: the unit rule, header/footer/body
independence, packages, the generate and statement coarseness, fences
outranking ranges, alignment-group splitting, the parse-error refusal,
blank-line and comment preservation, multi-byte, the uncuttable module,
the spec grammar, the line-shift counterexample, and a corpus spot
check.
- [x] CLI `--lines`: comma and repeated forms, `--check`/`--diff`/`--stdout`/
stdin, directory refusal, cache bypass, `lucisv check` rejection — 6 CLI
tests + 2 arg unit tests.
- [x] LSP `documentRangeFormattingProvider` + `format::range_formatting` — 6
handler tests and one e2e leg over the wire with UTF-16 content.
- [x] `tools/lucisv-changed.sh`.
- [x] README.md usage block + a Range formatting section; TODO.md §2
checkbox; the one-line `lucisv-server` README annotation.
- [ ] **Not done, deliberately:** statement-level ranges (an intersected
`always` block lays out whole).
- [ ] **Not done, deliberately:** descending into `generate` regions,
classes, functions and tasks. One `scope_of` arm plus a head/tail doc
each, whenever a real file makes it hurt.
- [ ] **Not done:** a `lucisv --diff-base <rev>` flag. `tools/lucisv-changed.sh`
covers the need from outside; putting git inside the binary is a
separate decision.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, TODO.md §2/§6, and the Handshakes of `format-fences`,
`spans`, `lucisv-server` and `alignment` before writing anything. Baseline:
`cargo test -p vlog_formatter` **113 passed**, clippy silent, fmt clean.
(`cargo test --workspace` did not build at that moment — a concurrent
`vlog_linter` round had the tree mid-edit; it was green again before the
final run below, and nothing in `vlog_linter` was touched here.)
- **Chose "a range is an inverted fence" as the implementation, not just the
metaphor.** The fence machinery already answers "these bytes are emitted as
written, and the items they cover are skipped"; the only thing it could not
do was *open* a region at an item's code rather than at a comment. Adding
`opens_at` (a region whose `fence` offset equals the item's `span.start`)
made ranges fall out of the existing splice with no second mechanism. The
alternative — a parallel "skip this item" flag on `Fmt` — would have been a
second definition of verbatim, and the fence round's lesson is that one
definition is what keeps the safety net's argument short.
- **Runs, not per-item slices, because of blank lines.** The first sketch
emitted each unselected item as its own `Doc::Verbatim`. It passed
equivalence and looked right until a file with two blank lines between two
untouched declarations came back with one: the *separator between* the
slices is the formatter's, and it normalizes. Merging consecutive verbatim
units into one slice puts those bytes inside the slice, where nothing can
reach them. The residual — a boundary between a laid-out item and a run
still normalizes its one gap — is documented rather than chased, because it
is the same rule a fence boundary follows.
- **Descending: modules and packages only.** The brief's granularity call, and
the right one; the honest scope line is that a `generate` region is atomic,
which is documented in three places rather than hidden. Head and tail
extents are computed from the *scope*, not from the item kind — the header
ends at the last non-whitespace byte before the first body unit's line, the
footer starts at the `endmodule` line — so adding a kind later is one match
arm plus a head/tail doc.
- **`module()` was split into `module_head` + body + closing** so a split item
can lay out the header while the body stays verbatim. Pure extraction: the
`Doc` sequence is the same list, built in two functions instead of one, and
the zero churn on the `.cases` table is the evidence.
- **The convergence check was the real design problem, and the first two
answers were wrong.** Re-running with the same *line* ranges is not
well-defined (lines move); re-running with *no* ranges is not a fixed point
by construction (that is the feature). The answer that works is to record
the per-item decisions and replay them, which is sound precisely because
equivalence has already proved the two texts have the same token stream —
the check upstream is what makes the check downstream meaningful. Two
consequences fell out of that and are now invariants: the pick list is
indexed by a depth-first walk whose shape depends only on the item tree, and
the body of a module is therefore walked even when it cannot be split.
- **A construction bug the safety net caught, exactly as designed.** The
split's "where does the body end" used the last *item* and ignored the
scope's dangling comments, so a module ending in `// note` before
`endmodule` emitted that comment twice — once in the run, once in the tail
slice. `verify_equivalence` rejected it on the first probe with a token
index and both spellings. Fixed by taking the dangling comments' end when
there are any.
- **Two findings from the corpus, both kept as documentation rather than
papered over.** (a) The `on` fence is the next item's leading comment, so
selecting the `on` line selects that item — my first test asserted "nothing
changes" and the code was right. (b) A same-line-range second run can reach
further when the first run moved a line; measured at 449 of 8236 trials, all
settling on that second run. The runtime replay is unaffected by either.
- **`--lines` bypasses the cache** for two independent reasons, both written
at the `cache_enabled` call site: a hit skips the very lines the caller
named, and a miss would record a partial format under the "already
formatted" verdict the cache exists to promise.
- **The LSP handler converts only line numbers**, which is the cheapest
correct answer to the UTF-16 question: the columns are thrown away, so
there is nothing to get wrong. The one rule that needed a test is the
end-at-character-0 case every editor sends.
- Did not touch `verify.rs`, `vlog_parser`, `vlog_semantic`, `vlog_linter`
(a concurrent round owns it), `corpus/`, or the `.cases` tables. Did not run
`git commit`/`git push`.
**Results.**
- `cargo test --workspace`: **768 passed, 0 failed** (a moving number — the
concurrent `vlog_linter` round is landing tests in the same tree; it read
767 an hour earlier). This feature's own crates: `vlog_formatter` 113 →
**141** (+6 unit tests in `range.rs`, +22 in `tests/ranges.rs`), `lucisv`
91 → **99** (+2 arg unit tests, +6 CLI tests), `lucisv_server` 114 → **121**
(+6 handler tests, +1 e2e).
- `cargo clippy --workspace --all-targets`: silent, 0 warnings.
`cargo fmt --all --check`: clean.
- **No default-behavior change, verified two ways.** `tools/corpus_check.sh
corpus` gives TSV md5 `b74f2f167c57e381d46f3503363a79b3` — byte-identical
to a run of a binary built from a `git worktree` at the pre-change commit
(003e076); 820 files, 578 formattable (70.5 %), 10 ok-unchanged, 568
would-reformat, 242 parse-error, **0 verification errors, 0 crashes**. And
the whole-file `--stdout` output of all **578** formattable corpus files is
**byte-identical** between the two binaries (0 differing). The worktree was
removed afterwards.
- **Range sweep over the corpus**: every formattable file, ~12 evenly spread
3-line ranges each — **578 files, 8236 trials, 0 refusals**, i.e. range
formatting never refuses a file the whole-file formatter accepts, and the
safety net (equivalence + replayed convergence) passed on every one. 449
trials (5.5 %) were not a fixed point under the same *line numbers*; all 449
settled on the next run. The sweep harness was a scratch test, not checked
in; `tests/ranges.rs`'s corpus spot check is the committed version.
Files added: `crates/vlog_formatter/src/range.rs`,
`crates/vlog_formatter/tests/ranges.rs`, `tools/lucisv-changed.sh`, this README.
Files edited: `crates/vlog_formatter/src/{lib,format,fence}.rs`,
`crates/lucisv/src/{args,main}.rs`, `crates/lucisv/tests/cli.rs`,
`crates/lucisv_server/src/{main,server,format}.rs`,
`crates/lucisv_server/tests/e2e.rs`, `README.md`, `TODO.md`,
`docs/features/lucisv-server/README.md` (the deferred-capability annotation).
## QA log
### 2026-08-19 — QA agent
Read `CLAUDE.md`, this README, `range.rs`, the `format.rs`/`fence.rs`/`lib.rs`
diffs, `tests/ranges.rs`, the `lucisv`/`lucisv_server` diffs, and
`tools/lucisv-changed.sh` before touching anything. Verified by (a) rebuilding
and re-running the gates myself, (b) an independent binary-diff of the
no-default-change claim, (c) hand-written probe files against the real
release binaries (not just re-running the shipped test suite), and (d) one
deliberate sabotage of the convergence mechanism to confirm the safety net is
load-bearing rather than decorative. No BLOCKING findings. No file outside
this README's QA log was left modified (the sabotage below was applied and
reverted in the same sitting; diffed byte-for-byte against the pre-sabotage
`git diff` to confirm).
**Gates — pass.** `cargo build --release` clean. `cargo test --workspace
--release`: **768 passed, 0 failed** across 27 test binaries — recomputed by
hand from the per-binary counts, matches the dev's snapshot exactly.
`cargo clippy --workspace --all-targets --release`: silent. `cargo fmt --all
--check`: clean. `git diff --quiet` on `verify.rs` and
`tests/verification.rs`: both exit 0 (untouched, confirmed independently of
the dev's claim). `git status --porcelain -- '*.cases'`: no `.cases` churn.
`fence.rs`'s diff is exactly the two claimed `fn` → `pub(crate) fn` lines,
nothing else — read the whole diff, not just the summary.
**No default-behavior change — pass, verified independently, not just
re-run.** `tools/corpus_check.sh corpus` here: TSV md5
`b74f2f167c57e381d46f3503363a79b3`, byte-for-byte the value in the Work log.
Then, independently of the dev's worktree (which was already removed):
created my own `git worktree` at `003e076`, built its `lucisv --release`, and
compared `--stdout` output against the current binary over all 578
formattable corpus files (from the TSV's `ok-unchanged`/`would-reformat`
rows) — 0 differing via a `$()`-capture pass over all 578, then a second,
byte-exact `cmp` pass on a 20-file stride subset (every 29th file). Both
clean. Worktree removed after.
**Semantics (claim 1) — pass.** Hand probes against `target/release/lucisv`,
not just re-running `tests/ranges.rs`:
- Unit rule: a range on only a leading comment lays out the whole unit
(comment + declaration), sibling untouched — matches the doc's "selecting a
doc comment selects the declaration under it."
- Module split independence, probed three ways on one file: header-only range
leaves a **mis-indented** body byte-identical (checked as a substring, not
a line-diff, since the header's line count itself changes — `p2.sv` in the
scratchpad); a range on `endmodule` alone leaves header and body untouched;
two ranges (items 1 and 3) around a misformatted item 2 leave item 2 and
the blank lines around it byte-identical.
- Run merging: confirmed the bug class the doc says this prevents is real —
a CRLF probe (`p7b.sv`) with two consecutive *unselected* items merged into
one run showed the `\r` **between** them surviving (interior byte of the
run) while every `\r` at a unit **boundary** (header/body, run/tail, EOF)
was stripped, exactly per "Line terminators the formatter writes are `\n`."
This is the sharpest confirmation available short of literally reverting
the run-merge and watching a blank-line count change.
- Blank-line selection: `--lines` on a pure blank line is a no-op (confirmed
via CLI, matches `tests/ranges.rs`).
- Uncuttable module: `module m; wire a; endmodule` on one line lays out
whole, not partially — confirmed via CLI, matches the shipped test.
**Interactions (claim 2) — pass.**
- Fence wins: `--lines` on lines fully inside a `// lucisv: off` region leaves
the region untouched; the on-fence-line quirk (selecting the `on` line
selects the *next* item, not the region) reproduced independently.
- Alignment split: `ALIGNED`-shaped probe with lines 2-3 selected — the two
selected `localparam`s align to their own column, the third (unselected)
keeps its original spacing byte-for-byte; a lone selected member formats
flush with no padding. Matches the doc's worked example exactly.
- Unparseable file: `--lines 1` on a file broken at line 3 still exits 2 and
leaves the file untouched, even though line 1 never touches the break.
- Reversed/zero/junk ranges (`5-1`, `0`, `0-3`, `x`, `1-2-3`, empty spec) all
exit 2 with the file untouched, checked by diffing the file after each
attempt — confirms the parse happens before any file is opened.
- Past-EOF (`900-1000` on a 3-line file): exits 0, "1 file left unchanged",
file untouched — clamps rather than errors, as documented.
**Convergence (claim 3) — pass, and load-bearing (see sabotage below).**
- Same-selection replay inside one `format_range` call is the promised fixed
point; re-running `--lines` on the *same* ranges after a run that did not
move the selected lines is a no-op (`--check` exits 0) in every probe,
including a CRLF file and an alignment-group probe.
- The honest limit reproduced deliberately: a probe port-list header written
over 5 lines, `--lines 1-6`, shrinks to 1 line but the range (1-6) still
covers the whole shrunk output, so the *next* CLI run is still a fixed
point (no sweep, because the shrink didn't cross the range's own boundary).
Separately, re-derived the exact `a_line_shift_can_sweep_in_the_next_construct`
scenario by hand (a 3-line header that becomes 1 line, selected via
`--lines 1-3`) and confirmed the second run sweeps in the body item, and a
third run settles — matching the doc's 449/8236 finding's description of
the shape of the effect, not just trusting the number.
**CLI/cache/LSP (claim 4) — pass.**
- `--lines` forms (comma, repeated), `--check`/`--diff` combination (diff
patch applied cleanly with `patch` against a copy and matched the actual
`--lines` output byte-for-byte), stdin, directory refusal (exit 2, correct
message, file untouched), `lucisv check --lines` rejection (exit 2) — all
reproduced directly against the binary, not just by reading `cli.rs`.
- `--lines` bypasses the cache in both directions: verified via `cli.rs`'s
own test (already covers "warm cache, `--lines` run still does the work,
and writes nothing"); did not re-derive this one independently beyond
reading it, since it is a single boolean at one call site
(`args.rs::cache_enabled`) and the existing test already exercises both
the hit-skip and the no-write cases.
- LSP: drove the **real** `lucisv-server` release binary over stdio with a
hand-rolled Content-Length framer (independent of `e2e.rs`'s harness) —
`initialize` advertises `documentRangeFormattingProvider: true`; a range
mid-module (line 3 of a 3-item module) returns one whole-document
`TextEdit` containing only that line reformatted; a range on an
already-clean line returns `"result": []` (empty, no edit). Matches the
doc's "reply absent/empty when nothing changes" and "one whole-document
edit" claims. `cargo test -p lucisv_server` (part of the workspace run
above) is green, e2e included.
- Did not independently re-derive the end-at-character-0 UTF-16 conversion
math beyond reading `format.rs::range_formatting` and its unit tests
(`crates/lucisv_server/src/format.rs:80-90`) — the logic is a two-line `if`
with four unit tests covering exactly the boundary cases the doc names
(cursor-only, "select two lines" ending at char 0, single line via the same
rule, and a multi-byte line proving only line numbers survive the
conversion); re-tracing it by hand against each test agreed with both.
**lucisv-changed.sh — pass.** Scratch git repo, two files, three edited lines
(one in `a.sv`, two in `b.sv`): only the touched declarations moved, module
headers and untouched siblings stayed exactly as written. A deletion-only
hunk (`sed -i '' '3d'`, no added lines) was skipped entirely — file
untouched, confirmed by diff. `--check` pass-through: exit 1 when the
touched hunk would still reformat, exit 0 once clean, exit 2 when
`$LUCISV` points at a nonexistent binary (the script's own guard, not lucisv's
exit code, but still the documented "2 = error" contract).
**Sabotage (required by CLAUDE.md invariant #4's spirit, even though this
round added no new normalization) — the replay is load-bearing.** Edited
`format_range` in `crates/vlog_formatter/src/format.rs` to re-derive the
second-pass selection with `range::select(&output, &sabotage_file, lines)`
(the caller's original line numbers, re-applied to the reparsed *output*)
instead of replaying `selection.picks` — i.e., exactly the "re-derive from
line numbers on pass 2" bug the Work log's convergence section describes as
the wrong answer. Rebuilt and ran `cargo test -p vlog_formatter --release`:
**2 failures**, both in `tests/ranges.rs`:
- `a_line_shift_can_sweep_in_the_next_construct` panicked inside
`format_range` itself: `Verification(NotConverged { line: 2, first: " wire
x;", second: " wire x;" })` (bytes verbatim: pass one's output kept
`wire x;`, the sabotaged replay reformatted it to `wire x;`) — the exact
mechanism the doc predicts:
lines 1-3 select only the header on pass one, but after the header
collapses to one line, the same line numbers reach into the body on the
sabotaged pass two, and the two passes disagree.
- `a_corpus_spot_check_touches_only_the_top_of_the_file` also failed, on a
real file (`corpus/picorv32/testbench_wb.v`): "formatting is not
idempotent; line 5 changed from `\treg clk = 1;` to ` reg clk = 1;`" —
confirms the bug is not a contrived-input artifact, it fires on real RTL
too.
Reverted the edit (`git diff crates/vlog_formatter/src/format.rs` back to
exactly the pre-sabotage diff, confirmed with a byte diff of the saved
pre-sabotage patch against the post-revert patch, plus `grep -n sabotage`
returning nothing). Rebuilt; `cargo test -p vlog_formatter --release`: 78
passed, 0 failed, back to clean. Re-ran the full workspace gate afterward
(build/test/clippy/fmt) to confirm the revert didn't leave the tree in a
different state than before I started — all four clean, 768/0 again.
**Conclusion:** every claim in the brief holds, verified independently
rather than by re-trusting the dev's numbers where an independent check was
feasible in the time available. No BLOCKING findings (no non-convergence
under a *held* selection, no bytes changed outside a selected unit, no
default-behavior change). The one substantive risk this feature carries —
that convergence could silently degrade if a future edit "simplified" the
replay back into a line-number re-derivation — has a sharp, fast-failing
regression signal: the sabotage above took under a minute to both introduce
and get caught by the existing `tests/ranges.rs` suite, with no new test
needed.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 18. The
legacy-codebase adoption story is complete: edit three lines of a
2000-line module and only three lines move — in the CLI, via git, and
in the editor.**
Points reviewed and accepted:
1. **Selection replay is the design contribution**: convergence over
line-addressed partial formatting is unsound by construction (lines
move), and replaying the per-item Selection — justified by the
equivalence check having already proven token identity — turns it
sound. QA's sabotage replaced replay with re-derivation and got
immediate NotConverged failures including on real RTL: the
mechanism is load-bearing, not decorative.
2. **The honest limit is measured and pinned**, not hidden: same LINE
NUMBERS can sweep in a neighbor when the first run moved lines
(449/8236 corpus trials, all settled next run), with a committed
counterexample test. Users of lucisv-changed.sh get self-stabilizing
behavior; the docs say why.
3. **Run-merged verbatim slices** — found by a probe, not reasoning —
is the kind of bug (separator-collapsed blank lines between
untouched items) that only surfaces when you treat "untouched"
as a byte-level promise. The head/body/tail module split with
independent decisions is the right granularity for the use case,
and one `scope_of` arm from going deeper when someone needs it.
4. **Every interaction decided and probed**: fence wins; alignment
groups split at verbatim boundaries; cache fully bypassed (a
partial format is not the cached clean verdict); unparseable files
still refuse; the LSP handler sidesteps UTF-16 columns entirely by
consuming only lines. Default behavior provably unchanged two ways
(TSV md5 + all-578 whole-file byte-compare against a pre-round
binary, re-derived independently by QA).
With this, the owner's full directive is delivered. What remains on
the backlog is the corpus-nominated queues/dynamic-arrays parse round
(41 files), the parked §4 linter items, and the LSP-side class
navigation gap — all documented where they live.