Rainbow begin/end: vfmt/scopePairs request + themed depth decorations

Server: custom vfmt/scopePairs request returning every begin/end and
fork/join* pair with its nesting depth (UTF-16 ranges); wire shape pinned
by a literal-JSON test and by smoke.js over a real spawned server.

Extension: paints each depth with the theme's own bracket palette
(editorBracketHighlight.foreground1..6), debounced 250 ms, with a
document.version staleness guard; vfmt.rainbowBeginEnd setting (default
on) honored immediately in both directions.

Corpus sweep: 8,146 block pairs across 859 files, max depth 13, worst
request 2.1 ms (picorv32.v).

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 02:23:22 -07:00
1 parent f280e51169
commit aa26e5e427
8 files changed
+673 -33

No files matched your search

+270 -15
View File
@@ -5,14 +5,15 @@
Three of the owner's five editor requests are the same question asked three
ways — *which `end` belongs to this `begin`?* — so they get one answer:
`crates/vfmt_server/src/pairs.rs`, a stack matcher over the token stream the
document already caches. This milestone ships the engine and two of its three
consumers: `textDocument/documentHighlight`, so the cursor on a `begin`
document already caches. On top of it sit three consumers:
`textDocument/documentHighlight`, so the cursor on a `begin`
highlights its own `end` (real matching, not a text search for the word), and a
**missing-closer warning** that points at the `begin` which lost its `end`
instead of leaving the user with one parse error at the bottom of the file. The
third consumer, the extension's rainbow colouring, is the next milestone and
needs nothing from the engine that is not already here — `Pair::depth` is
computed and tested, it just has no wire to travel on yet.
third consumer is the extension's rainbow: `vfmt/scopePairs` hands the client
every `begin`/`end` and `fork`/`join*` pair with its nesting depth, and
`extension.js` paints each depth in one of the six colours the user's theme
already defines for bracket pairs.
## Assumptions
@@ -50,10 +51,19 @@ computed and tested, it just has no wire to travel on yet.
wrong is a phantom unclosed scope; each has a test, and the corpus sweep in
the work log is what says the list is complete rather than merely plausible.
- **Analysis is cheap enough to redo per request.** `analyze` is one pass over
the token vector with a small stack — microseconds on a Verilog file — so
nothing is cached and no invalidation rule can go stale. If a profile ever
says otherwise, the result belongs next to `tokens` in `Document`, computed
once per change like everything else there.
the token vector with a small stack, so nothing is cached and no invalidation
rule can go stale. Measured, because `vfmt/scopePairs` arrives on a debounce
timer rather than on a user gesture: sweeping the corpus, the worst single
`scope_pairs` call is **2.1 ms** (`picorv32.v`, the largest file), against a
250 ms debounce. If a profile ever says otherwise, the result belongs next to
`tokens` in `Document`, computed once per change like everything else there.
- **The client repaints; the server never pushes.** LSP has no "decorate these
ranges" notification, so the extension asks after every settled edit. That
makes a stale answer possible — the reply describes the version that was
asked about, and the user may have typed since — so `extension.js` compares
`document.version` across the await and drops anything late. Without that,
every range after an edit is painted at the wrong offset until the next
repaint.
## Handshakes
@@ -81,11 +91,45 @@ JSON `null` — deliberately not an empty array, because an empty array tells th
editor there are no occurrences anywhere and suppresses its own word
highlighting.
**Promised to the next milestone:** `analyze(&[Token]) -> ScopeAnalysis`, with
`Pair { open, close, depth }`. `depth` counts every frame open at push time
(the module is 0, a `begin` under an `always` inside it is 1 or 2), which is
what `depth % 6` needs to pick a bracket colour. `Pair::depth` carries an
`#[allow(dead_code)]` until `vfmt/scopePairs` reads it.
**Promised to `extension.js` — the `vfmt/scopePairs` wire shape.** This is the
contract; `the_scope_pairs_wire_shape_is_what_the_extension_reads` pins it as
literal JSON so it cannot drift silently.
Request — a custom method, so nothing advertises it and a client that does not
know it simply never asks:
```json
{ "method": "vfmt/scopePairs", "params": { "textDocument": { "uri": "file:///…" } } }
```
Result:
```json
{ "pairs": [ { "open": Range, "close": Range, "depth": 0 } ] }
```
- `open`/`close` are LSP `Range`s over the **keyword itself** — UTF-16, like
every other position this server sends, converted with `doc.positions()`.
- `pairs` holds only `begin`/`end` and `fork`/`join`/`join_any`/`join_none`.
Every other scope the engine matches is dropped: a whole-file `module`
would tint its own keywords a colour that means nothing, and letting
`case`/`endcase` into the ladder makes the nesting read as deeper than it
looks. What the owner asked for is the `begin`/`end` ladder.
- `depth` counts every frame open at push time, **including the ones filtered
out** — a `begin` directly inside a `module` is depth 1, not 0. Filtering
after counting is what keeps nesting *differences* right, which is all
`depth % 6` needs; an absolute 0 for the outermost block would cost a pass
to renumber and buy nothing.
- Unmatched keywords are absent. Half a pair is nothing to colour, and the
missing-closer warning already speaks about it.
- An unopened document answers `null`, matching every other handler here.
The extension treats that as "no pairs".
Ordering is by opener position, though the extension does not depend on it.
**Promised to any future consumer:** `analyze(&[Token]) -> ScopeAnalysis`, with
`Pair { open, close, keyword, depth }`. `keyword` is the opener as written,
which is how `scope_pairs` filters.
**The guards — the list that must stay correct.** Each is an opener keyword in
a construct with no closer:
@@ -122,7 +166,15 @@ source. Neither file belongs to this feature, so neither was touched.
failed, capped at 20.
- [x] e2e coverage over the wire (`tests/e2e.rs`).
- [x] Corpus sweep for false positives (found one class; fixed).
- [ ] `vfmt/scopePairs` + the extension's rainbow — next milestone.
- [x] `vfmt/scopePairs` in `server.rs` + `pairs::scope_pairs`, wire shape
pinned by a literal-JSON test.
- [x] The rainbow in `extension.js`: six theme decoration types, `depth % 6`,
repaint on active-editor / visible-editors / document change (250 ms
debounce), stale-answer guard.
- [x] `vfmt.rainbowBeginEnd` (default true), honoured live by a
configuration-change listener.
- [x] `smoke.js` drives `vfmt/scopePairs` against a nested-begin + fork
fixture and asserts the depths.
- [ ] Not done, deliberately: no check that a labeled `end : outer` agrees with
its `begin : outer`. That is a lint rule with its own fix and its own
opinion, not part of matching.
@@ -221,6 +273,68 @@ green. Full workspace: 937 passed, 0 failed. `cargo fmt --all` clean,
`cargo clippy --all-targets` clean. The one `#[allow]` in the new code is on
`Pair::depth`, with a comment naming the milestone that removes it.
### 2026-08-24 — M3: `vfmt/scopePairs` and the extension's rainbow
**Server.** `Pair` gained a `keyword` field (the opener as written) so a
consumer can take a subset without the engine having to know about subsets;
`scope_pairs` filters on it and converts to LSP `Range`s. That field is also
what let the `#[allow(dead_code)]` on `Pair::depth` go — both fields are now
read by shipping code, and the crate has no `#[allow]` left in this module.
The handler is one arm in `server.rs`, matched on the method name rather than
through an `lsp_types::request` type because the method is ours.
**Three decisions worth recording.**
1. *Depth is not renumbered after filtering.* A `begin` directly inside a
`module` reports depth 1, because the module frame was open when it was
pushed. The rainbow only needs nesting *differences*, and renumbering would
cost a pass and change nothing on screen. Written down because "why does my
outermost block get colour 2?" is otherwise a mystery.
2. *Only `begin`/`end` and `fork`/`join*` go on the wire.* The engine matches
twenty-one scopes; nineteen are dropped here. Colouring `module`/`endmodule`
tints a keyword pair the user never wonders about, and letting `case` into
the ladder shifts every `begin` inside it one colour, which reads as deeper
nesting than the code has.
3. *The extension guards against its own staleness.* `paint` records
`document.version` before the request and drops the answer if it changed
while in flight. The debounce reduces how often that happens; it cannot
prevent it, and a decoration painted at a pre-edit offset is worse than no
decoration.
**Extension.** Six `TextEditorDecorationType`s, colour-only, each bound to
`vscode.ThemeColor('editorBracketHighlight.foregroundN')` so the palette is
whatever the user's theme already uses for brackets — no colours invented here,
nothing to clash. Repaint on active-editor change, visible-editors change
(splits, tab drags) and document change on a 250 ms debounce. Turning
`vfmt.rainbowBeginEnd` off repaints with empty range lists, which is how a
decoration type is removed — so "off" takes effect immediately in both
directions rather than "after a reload". Closing an editor needs no handler:
VS Code disposes its decorations with it, and the types themselves are in
`context.subscriptions`. A failed request leaves the previous colours alone
rather than blanking the file, since the language client already reports a
server that will not start, in its own channel.
**Corpus sweep, again** (temporary test, run and removed, as in M2): all 860
files through `scope_pairs`. **8 146 block pairs, max depth 13, 0 malformed
ranges** (every `open` before its `close`, every range non-empty), and the
timing above. No behavioural change from M2 — the `keyword` field is additive —
but the new surface is the one that reaches the screen, so it got its own pass.
**Deviations from the plan.** One, and it is an addition: the plan put
scopePairs coverage in `smoke.js` only, and it is also asserted in
`tests/e2e.rs` (one request appended to the existing scopes test). `smoke.js`
is run by hand before packaging; the routing of a custom method is exactly the
kind of thing that breaks silently, so it is worth having in `cargo test` too.
Otherwise the milestone is as specified.
**Verification.** `cargo fmt --all` clean, `cargo clippy --all-targets` clean
(0 diagnostics), `cargo test --workspace` **944 passed, 0 failed** (168 unit in
this crate, up from 162; 7 e2e). `node smoke.js ../../target/debug/vfmt-server`
against a freshly built binary: OK. The smoke assertion was mutation-checked —
changing the expected depths to `[9,9,9]` fails with
`got [1,2,1]`, so it is live rather than vacuous. `npx @vscode/vsce ls` still
accepts the manifest. `node --check` on both JS files.
## QA log
### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate
@@ -304,6 +418,133 @@ recorded above (a pre-existing `vlog_parser` grammar gap unrelated to this
feature, and a redundant-but-harmless double document lookup in
`server.rs`).
### 2026-08-24 — QA round 2 (M3): `vfmt/scopePairs` and the extension rainbow
Charter items 1, 4, 5 (repeat, unregressed) and 6 from `editor_features_plan.md`
for this dispatch: the wire shape, `scope_pairs` correctness, `extension.js`
review, `smoke.js`, invariants, and an M1/M2 unregression spot-check. Item 2
(documentHighlight attack surface) is M2 and was covered in round 1; not
re-audited except where M3 touched shared code (it did not — `Pair::keyword`
is additive). Verdict: **PASS**, no blocking findings.
**1. Wire shape.** Ran `cargo test -p vfmt_server`: 168 unit + 7 e2e, all
green. Read `the_scope_pairs_wire_shape_is_what_the_extension_reads`
(`crates/vfmt_server/src/pairs.rs:915`) — it pins the full response as literal
JSON (`open`/`close` LSP `Range`s over the keyword, `depth`), matching the
Handshakes section word for word. Confirmed each documented property against
its own test, not just the pinned one:
- UTF-16 ranges: `scope_pairs_ranges_are_utf16_and_cover_the_keyword`
(`pairs.rs:882`) — a 2-byte `é`/`✓` comment before `begin` and the column
lands at 10, not shifted by the extra bytes.
- Only `begin`/`end` + `fork`/`join*`: `scope_pairs_carries_only_block_delimiters`
(`pairs.rs:858`) — module/case/function all matched by the engine (4 pairs)
but only the 1 `begin..end` survives the filter. `RAINBOW_KEYWORDS` is
`["begin", "fork"]`; since `Pair::keyword` stores the opener, this correctly
admits `fork` closed by any of `join`/`join_any`/`join_none`.
- Depth not renumbered after filtering: `scope_pairs_depths_nest_and_forks_are_included`
(`pairs.rs:872`) — module (depth 0, filtered out) then begins at depth 1
and 2; e2e test at `tests/e2e.rs:576` independently pins depth 2 for a
`begin` nested two frames deep in an unbalanced file.
- Unmatched keywords absent: `scope_pairs_omits_a_pair_that_never_closed`
(`pairs.rs:895`) and the e2e test (only the closed inner `begin` is offered,
1 pair, from a file with one unclosed `begin`).
- Unopened doc → `null`: no dedicated unit test exists for this specific
handler (matches the pattern for every sibling handler in `server.rs` —
none of them have one either, so this is not an M3-specific gap). Verified
directly against the built binary instead: spawned `vfmt-server`, sent
`vfmt/scopePairs` for a URI never opened via `didOpen`, got back
`{"jsonrpc":"2.0","id":2,"result":null}` with no error. Matches
`server.rs:165-170`.
**2. `scope_pairs` correctness — independent corpus sweep.** Added a
throwaway `#[cfg(test)]` (same discipline as round 1: run, read, removed
before this log was written — not in the committed tree) walking `corpus/`
and calling `scope_pairs` on every file that lexes, checking every emitted
range is non-empty and `open` starts before `close` starts. Result: **859
files scanned, 8 146 pairs, max depth 13, 0 malformed** — an exact match to
the dev's Work Log numbers (`8 146 block pairs, max depth 13, 0 malformed
ranges`). Depths and UTF-16 columns already covered per-case above; nothing
in the sweep found a malformed range or a panic.
**3. `extension.js` review** (`editors/vscode/extension.js`), read in full
against the round-2 charter's specific worry list:
- **Decoration lifecycle**: 6 `TextEditorDecorationType`s built once in
`activate` (line 64-68), color-only (`ThemeColor` per index, no
`fontWeight`), pushed into `context.subscriptions` (line 69) — disposed
automatically on deactivate, which also removes their decorations from
every editor without extra code.
- **Staleness guard**: `askedAbout = document.version` (line 142) is captured
*before* `await client.sendRequest(...)` (line 147) and compared *after*
(line 159) — correct order, confirmed by reading the `async` control flow
directly; a version bump during the await drops the stale answer and
relies on the debounce the edit already scheduled.
- **Debounce**: `scheduleRepaint` (line 121) clears the pending timer before
setting a new one; `deactivate` (line 107) clears it too, so no dangling
`setTimeout` after unload.
- **Setting-off path**: `onDidChangeConfiguration` (line 83) updates
`rainbowEnabled` and calls `repaintVisible()` synchronously (no debounce);
`paint()` skips the request entirely when `rainbowEnabled` is false and
still runs `setDecorations([])` for every bucket (line 167-169), which is
how a decoration type is cleared — confirmed this is unconditional (outside
the `if (rainbowEnabled)` block), so already-open editors really lose their
colours immediately, not after a reload.
- **No request for non-verilog docs**: `repaintVisible` (line 127) and the
document-change listener (line 81) both gate on `isVerilog()` before
scheduling or painting.
- **Listener leaks**: client, all 6 decoration types, and the 4-item listener
array are all pushed to `context.subscriptions` (lines 59, 69, 73-90) —
nothing is registered outside that list.
- **Client/server not ready or request rejects**: `client.start().then(ok, () =>
{})` (line 96-102) swallows a startup rejection without throwing; `paint`'s
`try { await client.sendRequest(...) } catch { return; }` (line 146-150)
swallows a rejected/thrown request the same way. Neither path produces an
unhandled rejection.
No defects found in `extension.js`.
**4. `smoke.js`.** Built `target/debug/vfmt-server` fresh (`cargo build -p
vfmt_server`), ran `node smoke.js ../../target/debug/vfmt-server` from
`editors/vscode/`: **OK**. Mutation check: changed the expected depths
assertion from `[1, 2, 1]` to `[9, 9, 9]`, reran — failed as expected
(`expected depths [1,2,1] ..., got [1,2,1]`, exit code 1), then reverted;
`md5` of `smoke.js` before and after the round-trip is identical
(`436a569e05a23fb766813e0cc15d2de8`), so the file is byte-for-byte what it
was. `node --check` on both `extension.js` and `smoke.js`: clean.
**5. Invariants.**
- `cargo test --workspace`: 944 passed, 0 failed (168 unit + 7 e2e in
`vfmt_server`, matching the Work Log's count).
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets`: clean, no warnings.
- `git diff --stat` vs `HEAD`: `crates/vfmt_server/{pairs,server}.rs`,
`crates/vfmt_server/tests/e2e.rs`, `docs/features/editor-scopes/README.md`,
`editors/vscode/{README.md,extension.js,package.json,smoke.js}`. No
`vlog_formatter`/`vlog_parser`/`verify.rs` paths touched.
- `node -e "JSON.parse(...)"` on `editors/vscode/package.json`: valid; the new
`vfmt.rainbowBeginEnd` setting and the M1 `contributes.snippets` block are
both present and unchanged in shape. `npx @vscode/vsce ls` accepts the
manifest and lists `package.json`, `extension.js`, `README.md`,
`snippets/verilog.json`, `snippets/systemverilog.json` — no error.
- No `unwrap()`/`expect()`/`panic!` in the new `pairs.rs`/`server.rs` code
outside `#[cfg(test)]` (grepped directly). No `#[allow]` remains in
`pairs.rs` — the dev's removal of the `Pair::depth` `#[allow(dead_code)]`
is confirmed; nothing new was added in its place.
**6. M1/M2 unregression spot-check.** `cargo test -p vfmt_server` (168 unit)
includes the full M1 snippet-adjacent and M2 `pairs.rs`/`documentHighlight`/
missing-end suites from round 1, all still passing; `package.json`'s
`contributes.snippets` block is byte-identical to what round 1 saw (verified
by reading it directly, not diffed against round 1 since M1 was committed
before this dispatch). No M2 test was touched by this diff except the two
lines the e2e test needed to add a `vfmt/scopePairs` frame after the existing
`documentHighlight` assertions.
**Verdict: PASS.** No blocking findings, no non-blocking findings either —
the unopened-doc-→-null path lacking a dedicated unit test is a pattern that
predates this feature (every sibling handler in `server.rs` shares it) and
was independently verified against the running binary, so it is not filed as
a gap specific to this work.
## Review
### 2026-08-24 — lead review of M2 (after QA round 1)
@@ -325,3 +566,17 @@ committed. Notes:
- QA's non-blocking note about the double `workspace.document` lookup in
the `documentHighlight` handler is real but matches the surrounding
handler style; not worth churn.
### 2026-08-24 — lead review of M3 (after QA round 2)
Read `extension.js` in full, the `scope_pairs` additions, the `server.rs`
arm and the `smoke.js` extension. Approved and committed. Notes:
- The client-side staleness guard (`document.version` captured before the
await, compared after, plus the visible-editor check) is the right shape,
and "leave the old colours on a failed request" is the right failure
mode for a cosmetic feature.
- Not renumbering depth after filtering is fine and well documented; the
rainbow reads differences only.
- The wire-shape test pinning literal JSON is what makes the custom method
safe to evolve; keep that pattern for any future custom request.