The rainbow painted depth 3-5 pairs with editorBracketHighlight .foreground4..6, whose VS Code defaults are fully transparent — a begin typed three levels deep vanished with its end. The extension now uses contributed vfmt.rainbow1..6 colors with opaque defaults in every theme variant (dark/light/HC/HC-light), and vfmt/scopePairs additionally reports genuinely unmatched begin/end/fork/join tokens, painted vfmt.rainbowUnmatched bright red — file characters are never hidden. Matched pairs, depths and 78eeef6's counting are unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
editor-scopes
Goal
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. 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 is the extension's rainbow: vfmt/scopePairs hands the client
every begin/end and fork/join* pair with its nesting depth — plus every
block delimiter still waiting for its partner — and extension.js paints each
depth in one of six colours the extension contributes itself, and each lonely
keyword in an error red.
Assumptions
- The token stream is the right substrate, not the text and not the AST.
Document.tokensis already cached and already lexed, so a// endin a comment and a"begin"in a string literal cannot be mistaken for keywords: the lexer detached the comment and made the literal oneStringtoken before the matcher ever sees the stream. The AST would be more precise and is the wrong tool anyway — a file with a missingendis exactly a file with no usable AST, and that is the file the user needs help with. - A macro's body is not in the stream, so the matcher cannot see into it.
`uvm_do_with(...)is oneIdenttoken however manybegins it expands to, and a`defineline is oneDirectivetoken. This is a feature for false positives (a macro can never push or pop) and the reason the diagnostics are gated (a macro that does supply anendmakes a perfectly good file look unbalanced). - Keyword-level matching means labels are free.
begin : outer … end : outermatches on the two keywords; the label is tokens the matcher skips. Nothing checks that the two labels agree — that is a linter's job, not this one's. checker/endcheckerandconfig/endconfigare not in the pair set becausevlog_parser::token::is_keyworddoes not list them: they lex as plain identifiers, and matching identifiers namedcheckerwould be a false-positive machine.table/endtableare keywords but are left out too — they only occur inside aprimitive, which is matched, and the plan did not ask for them. All three are one line each inRULESthe day the lexer or the need arrives.- A prototype ends at the next
;. The flagextern,pure,import,exportandtypedefraise is dropped at the next semicolon, wherever it falls. Atypedef struct { logic a; } t;therefore drops the flag at the member's;rather than the declaration's — harmless, because nothing between the two can open a scope, and far simpler than tracking brace depth. - Every guard in
opens_a_scopeis a construct that spells an opener and opens nothing. They are listed in Handshakes below because getting one 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. - A scope counts toward
depthif and only if it is drawn. Both readings come from one const,RAINBOW_KEYWORDS. M3 assumed the opposite — that counting every frame and filtering afterwards was fine, because "the rainbow only needs nesting differences". That was wrong, and a user found it: a hidden scope between twobegins is a difference the screen cannot explain. Abegininside acasecame out one colour deeper than its sibling outside, so thecaseread as "an invisible begin/end being highlighted" — their words. Colour is only meaningful relative to the other coloured things; a level nobody can see is a level that must not exist. Anything added toRULESmust therefore either joinRAINBOW_KEYWORDSor stay invisible in both senses at once, which is whatthe_depth_counter_and_the_wire_filter_read_the_same_listenforces. - A colour this feature paints is always opaque, and the file is never
hidden. The owner's rule, in their words: "respect the file content and
never hide any characters that are part of the file. You can make their
colour bright red for error in syntax, but don't just hide them." That rules
out borrowing a theme colour whose default is
#00000000, which is what 0.3.1 fixed, and it is why an unmatched keyword is painted rather than left alone. A user or a theme may still override avfmt.rainbow*id with anything they like — including transparent — and that is their decision, not a default of ours. - Analysis is cheap enough to redo per request.
analyzeis one pass over the token vector with a small stack, so nothing is cached and no invalidation rule can go stale. Measured, becausevfmt/scopePairsarrives on a debounce timer rather than on a user gesture: sweeping the corpus, the worst singlescope_pairscall is 2.1 ms (picorv32.v, the largest file), against a 250 ms debounce. If a profile ever says otherwise, the result belongs next totokensinDocument, 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.jscomparesdocument.versionacross the await and drops anything late. Without that, every range after an edit is painted at the wrong offset until the next repaint.
Handshakes
Consumed from state.rs: Document.tokens (the cached lex; empty when the
file does not lex, which the matcher handles by finding nothing),
Document.diagnostics (the parse diagnostics — the gate reads these, and
only these), and Document.positions() for the byte→UTF-16 conversion. No new
field was added to Document and nothing in state.rs changed.
Consumed from vlog_parser: Token, TokenKind, TextRange, and
token::is_keyword's classification. If a keyword is ever added to or removed
from that table, RULES and the guards below must be re-checked: the matcher
only ever looks at TokenKind::Keyword tokens, so a word that stops being a
keyword silently stops being matched.
Promised to diagnostics.rs: pairs::missing_end_diagnostics(doc), called
from diagnostics::all between the parse errors and the lint warnings. It
returns an empty list whenever doc.diagnostics is empty — callers do not have
to check the gate themselves.
Promised to server.rs and main.rs: pairs::highlights(doc, offset) -> Option<Vec<DocumentHighlight>>, and the documentHighlightProvider capability
that advertises it. None means "decline", which the request loop turns into a
JSON null — deliberately not an empty array, because an empty array tells the
editor there are no occurrences anywhere and suppresses its own word
highlighting.
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:
{ "method": "vfmt/scopePairs", "params": { "textDocument": { "uri": "file:///…" } } }
Result:
{
"pairs": [ { "open": Range, "close": Range, "depth": 0 } ],
"unmatched": [ Range ]
}
open/closeare LSPRanges over the keyword itself — UTF-16, like every other position this server sends, converted withdoc.positions().pairsholds onlybegin/endandfork/join/join_any/join_none. Every other scope the engine matches is dropped: a whole-filemodulewould tint its own keywords a colour that means nothing, and lettingcase/endcaseinto the ladder makes the nesting read as deeper than it looks. What the owner asked for is thebegin/endladder.depthcounts only the enclosing scopes that are themselves on the wire —beginandforkframes, nothing else. Abegindirectly inside amoduleis 0; so is abegininside acaseinside that module; abegininside abeginis 1; abegininside aforkinside abeginis 2. The filter and the counter read the sameRAINBOW_KEYWORDSconst, so a scope is counted if and only if it is sent. (This is the M5 reversal — see Assumptions and the work log.)unmatchedholds the block delimiters that never found a partner — everybegin/forkleft on the stack and everyend/join*that closed nothing — as one flat list of keyword ranges in source order. SameRAINBOW_KEYWORDSfilter aspairs, asked of the opener: a strayendis on the wire becausebeginis a rainbow keyword; a strayendmoduleis not. A keyword is inpairsor inunmatched, never in both —analyzeputs each scope on exactly one of its three lists. No depth: half a pair has no nesting level, which is precisely why the extension paints it a fixed error colour instead. (Added in 0.3.1 — see Unmatched tokens below and the work log.)- An unopened document answers
null, matching every other handler here. The extension treats that as "no pairs". - Both lists are always present, empty rather than absent, so the client can
clear a decoration with
|| []and never has to distinguish "none" from "this server does not know about them". A client one version older than the server ignoresunmatched; a client one version newer reads it as[], which is whyextension.jswrites(result && result.unmatched) || [].
Ordering is by opener position, though the extension does not depend on it.
Promised to package.json — the colour ids. The extension contributes
vfmt.rainbow1 … vfmt.rainbow6 and vfmt.rainbowUnmatched under
contributes.colors, and extension.js builds one TextEditorDecorationType
per id. Renaming an id in either file without the other silently paints
nothing: an unknown ThemeColor is not an error, it is simply no colour. See
The palette below for why the ids are ours and not VS Code's.
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:
| Written | Why it opens nothing |
|---|---|
extern function f(); , pure virtual function g(); |
prototype, body elsewhere |
import "DPI-C" function void c();, export "DPI-C" function f; |
foreign, no body here |
extern module m (...); |
header only |
typedef class C; |
forward declaration |
virtual interface bus_if vif; |
a type, not a declaration |
interface class IC; … endclass |
the class opens; the interface must not, or endclass finds the wrong frame |
module m (interface bus); |
generic interface port |
default clocking cb; |
names a block that already exists |
assert property (...), cover sequence (...) |
only a declaration names what it declares |
disable fork;, wait fork; |
statements about a fork, not a new one |
covergroup cg with function sample(...); |
the covergroup's sample method; endgroup closes the lot |
Request to the lead (outside this feature's scope):
docs/features/vfmt-server/README.md carries the server's capability list and
TODO.md §6 carries the shipped/not-shipped list; both now understate the
server by one capability (textDocument/documentHighlight) and one diagnostic
source. Neither file belongs to this feature, so neither was touched.
Unmatched tokens
A begin whose end has not been typed yet is the most common state a
begin is ever in: the user types the opener, presses Enter, and then writes
the body. Until 0.3.1 the wire said nothing about it — pairs carried closed
pairs only — so the extension had nothing to paint, and a half-typed block was
ordinary uncoloured text.
unmatched fixes that with the lists analyze has produced since M2:
unmatched_open (openers left on the stack, including the ones the mismatch
recovery pops out of the middle) and unmatched_close (closers that matched no
frame). scope_pairs filters both with the same RAINBOW_KEYWORDS used for
pairs, merges them, and sorts by position. Three properties are worth stating
because tests pin all three:
- Never both. A keyword that is in
pairscannot be inunmatched. The engine puts each scope on exactly one list, and the two decorations would otherwise fight over one range. - Same filter, asked of the opener.
unmatched_opencarries the opener askeyword;unmatched_closecarries the closer askeywordand the opener it wanted asexpected. The filter readskeywordfor the first andexpectedfor the second, so a lonejoinis reported (its openerforkis a rainbow keyword) and a loneendcaseis not. - Depths do not move. An unmatched frame is still an enclosing scope while
it is on the stack, so a
beginnested inside an unclosedbeginreports depth 1 exactly as it did before — the M5 counting rule is untouched, and its tests were not edited.
There is no gate here, unlike the missing-closer diagnostics, which fire only
when the parse has already failed. A diagnostic asserts the file is wrong; a
colour only says "this keyword has no partner in the token stream", which is
true of a macro-supplied end too — and the honest thing to show for it. The
cost of being wrong is a red keyword on a file that compiles, and the user can
turn the whole rainbow off; the cost of a wrong diagnostic is telling someone
their working code is broken, which is why that one stays gated.
The palette
Why not editorBracketHighlight.foreground1..6. They look like exactly the
right thing to borrow — the user's own theme, six levels, no invented colours —
and M3 did borrow them. But VS Code's colour registry gives visible defaults to
only the first three; foreground4, foreground5 and foreground6 default to
#00000000, fully transparent, on the assumption that a theme which wants
six bracket levels will define them, and most themes define none. VS Code's own
bracket colouriser skips transparent entries when it cycles. Ours did not, so
every pair at depth % 6 ∈ {3, 4, 5} was painted transparent — the keyword
disappeared. A ThemeColor that resolves to nothing is invisible failure by
design: it is not an error, it is just no paint.
So the extension contributes its own ids with contributes.colors, each with a
default for dark, light, highContrast and highContrastLight. A theme
that knows nothing about vfmt gets our default; a theme or a
workbench.colorCustomizations entry that names vfmt.rainbowN still wins,
which is the override story the borrowed ids gave us and the only thing worth
keeping about them.
| Id | Dark | Light | Why |
|---|---|---|---|
vfmt.rainbow1 |
#FFD700 gold |
#0431FA blue |
VS Code's own level-1 bracket colours, both themes |
vfmt.rainbow2 |
#DA70D6 orchid |
#319331 green |
VS Code's own level 2 |
vfmt.rainbow3 |
#179FFF blue (#87CEFA on HC dark) |
#7B3814 brown |
VS Code's own level 3, HC variant included |
vfmt.rainbow4 |
#87D96B green |
#0E7490 teal |
first free hue in each theme; ~11:1 on #1E1E1E, ~5.2:1 on white |
vfmt.rainbow5 |
#FF8C69 salmon |
#6D28D9 violet |
warm against the dark greens/golds, cool against the light greens/browns |
vfmt.rainbow6 |
#4FD6D6 cyan |
#BE185D magenta |
closes the wheel without repeating 1–3 in either theme |
vfmt.rainbowUnmatched |
#FF1212 red |
#B30000 dark red (#A80000 HC light) |
the error state, and the one colour that must read as wrong |
Two things about that table are decisions rather than transcription:
- Levels 1–3 are copied from VS Code per theme, not per colour. The plan said gold/orchid/blue "same in dark and light"; VS Code's actual light defaults are blue/green/brown, and it is right to be: gold on white is about 1.4:1, which is the same invisibility problem in a different costume. Since every reader of this file already has VS Code's bracket colours in muscle memory, matching them exactly per theme is the least surprising choice, and levels that already worked before 0.3.1 keep the colour they had.
- Levels 4–6 differ by hue between dark and light, because the sets they must stay distinguishable from differ: dark 1–3 use up yellow, magenta and blue, light 1–3 use up blue, green and brown. VS Code sets the precedent by using two entirely different trios for its own 1–3. Every value clears 4.5:1 against its theme's default editor background, and the light ones are dark enough to read as text rather than as a highlight.
The unmatched red is deliberately close to a plain error red rather than a seventh rainbow hue: it is a state, not a level, and the salmon at level 5 is the only neighbour it could be confused with — a pale orange-pink against a saturated pure red, and only ever on screen while a block is half-typed.
Status / TODO
pairs.rs:analyze, theRULEStable, the prototype flag, theopens_a_scopeguards, and mismatch recovery that does not cascade.- Unit tests for every hazard in the plan, plus labeled blocks, nested
depth counting, all three
joinflavours, all fourcaseflavours. textDocument/documentHighlightinserver.rs, capability inmain.rs,every_advertised_capability_is_implementedupdated.- Missing-closer WARNING diagnostics, gated on the parse having already failed, capped at 20.
- e2e coverage over the wire (
tests/e2e.rs). - Corpus sweep for false positives (found one class; fixed).
vfmt/scopePairsinserver.rs+pairs::scope_pairs, wire shape pinned by a literal-JSON test.- 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. vfmt.rainbowBeginEnd(default true), honoured live by a configuration-change listener.smoke.jsdrivesvfmt/scopePairsagainst a nested-begin + fork fixture and asserts the depths.- M5: wire
depthcounts only enclosing rainbow pairs, so a scope the rainbow hides cannot shift the colour of one it shows. - 0.3.1: the rainbow's colours are the extension's own
(
vfmt.rainbow1..6), opaque in every theme kind —foreground4..6default to transparent and were painting depths 3–5 invisible. - 0.3.1:
unmatchedon the wire, paintedvfmt.rainbowUnmatched, so a half-typedbeginis bright red rather than uncoloured. - Not done, deliberately: no check that a labeled
end : outeragrees with itsbegin : outer. That is a lint rule with its own fix and its own opinion, not part of matching. - Not done, deliberately: nothing is reported for an unbalanced file that the parser accepts. See the gate, above and below.
Work log
2026-08-24 — M2: the matcher, documentHighlight, missing-closer warnings
pairs.rs. One pass over Document.tokens, one stack, no recursion (so
nothing here can join the parser in the stack-depth conversation) and no
unwrap. RULES is a flat table of 21 openers and their closers; fork is
the only one with more than one (join, join_any, join_none), and the
first entry is the one the warnings name.
Two decisions worth recording.
- Recovery does not cascade. A closer searches the stack from the top down
for a frame it can close. If it finds one below the top, the frames above it
are reported as unclosed and it matches; if it finds nothing, it is reported
on its own and the stack is left completely alone. Popping the top blindly
would pair
beginwithendmoduleand then report the module unclosed — two wrong answers for one missing keyword, and the rainbow would lose every colour below the mistake.a_wrong_closer_does_not_pop_the_frame_it_does_not_matchanda_stray_end_matches_nothing_and_disturbs_nothingpin both halves. highlightsreturnsOption, andNonebecomes JSONnull. An empty array is a positive claim — "no occurrences of this anywhere" — and VS Code honours it by drawing nothing, so answering[]for every cursor that is not on abeginwould cost the user their ordinary word highlighting everywhere in the file. Declining hands the editor back its own behaviour. The cursor is treated as being on a keyword from its first byte to one past its last, so|endandend|both match; keyword spans never touch, so the extra byte cannot claim a neighbour.
The gate. missing_end_diagnostics returns nothing at all unless
doc.diagnostics is non-empty. The rationale is in the module doc: a
token-stream matcher cannot see `ifdef arms or macro bodies, so telling a
user their working file is unbalanced is a failure mode this feature may not
have. the_gate_alone_suppresses_the_warnings proves the gate is load-bearing
rather than decorative — it takes a buffer the matcher genuinely finds
unbalanced, clears the parse diagnostics on it, and asserts the answer goes
empty while analyze still reports the unmatched opener.
Corpus sweep — the part that changed the code. A temporary test (added,
run, removed; it is not in the committed file) ran Document::new + analyze
over all 860 corpus files and reported every file that parses cleanly yet looks
unbalanced to the matcher. First run: 7 false positives out of 840
clean-parsing files, every one of them a function reported unclosed, and
every one of them the same construct —
covergroup rx_fifo_level_cg with function sample(int lvl, bit rst);
with function sample(...) declares the covergroup's sample method in the
covergroup's own header. There is no endfunction; the endgroup closes
everything. It appears in every UVM coverage class in the corpus (uart, ibex
icache, the whole of dv_base_reg) and it is not in the plan's hazard list —
reading the LRM would not have caught it, running the corpus did. One guard
("function" => !is_keyword(prev, "with")) plus
a_covergroup_sample_method_opens_nothing. Second run: 840 clean files,
11 062 matched pairs, max depth 13, 0 false positives.
Deviations from the plan, all recorded above and each with a test.
checker/endcheckerdropped from the pair set:vlog_parserdoes not lex them as keywords, so matching them would mean matching identifiers.- Four guards added beyond the plan's list, three of them for constructs the
plan did not mention:
assert property (/cover sequence ((an assertion is not a declaration — this one is unavoidable, SV assertions are everywhere),disable fork;/wait fork;(idiomatic UVM),module m (interface bus)(generic interface port), andcovergroup … with function(from the sweep). Two of them — the generic interface port andinterface class— cover constructsvlog_parsercannot parse yet, so today they only matter for a file that is already failing; they cost one condition each and stop the matcher from adding a second, wrong complaint on top of the parser's. - The plan's
clockingfallback ("if this gets hairy, drop clocking") was not needed: two tokens of lookahead separatedefault clocking cb;fromclocking cb @(posedge clk);, and both shapes are tested. the_warnings_are_cappeduses 25 flat strayends rather than 41 nestedbegins. The nested version overflowed the test thread's stack inside the parser —docs/features/recursion-limit/README.mddocuments that the parser's 64-level budget needs the 8 MiB main-thread stack and that a spawned thread must be given one, and acargo testthread gets 2 MiB. Nothing to do with this module; the flat shape tests the same cap without inviting it.
Wiring. main.rs: document_highlight_provider advertised, module
declared, capability test extended. server.rs: one arm in the request match.
diagnostics.rs: one line in all(), between the parse errors and the lint
warnings, with the reason in the doc comment. Nothing else in the crate moved,
and no file outside crates/vfmt_server/ was touched.
Tests. cargo test -p vfmt_server: 162 unit (was 130) + 7 e2e (was 6), all
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 Ranges. 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.
- Depth is not renumbered after filtering. A
begindirectly inside amodulereports 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. — Reversed by M5 (2026-08-24): this was the bug. See that entry. The reasoning above is wrong in its last clause: renumbering changes plenty on screen, because a filtered-out scope silently consumes a colour level. - Only
begin/endandfork/join*go on the wire. The engine matches twenty-one scopes; nineteen are dropped here. Colouringmodule/endmoduletints a keyword pair the user never wonders about, and lettingcaseinto the ladder shifts everybegininside it one colour, which reads as deeper nesting than the code has. - The extension guards against its own staleness.
paintrecordsdocument.versionbefore 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 TextEditorDecorationTypes, 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.
2026-08-24 — M5: depth counts only the pairs the rainbow shows
The bug, in the user's words: "for blocks that don't have begin/end, like
inside of a case statement, I can see an invisible begin/end being
highlighted." Nothing was actually drawn on the case — the lead's probe
confirmed every returned range sits on a real keyword — but the begin inside
it was painted one colour deeper than a sibling begin outside it, so the eye
read the missing level as a hidden pair. Pair::depth counted every open
frame, and nineteen of the twenty-one scope kinds never reach the wire.
The fix. depth now counts only enclosing frames whose opener is in
RAINBOW_KEYWORDS, computed at push time by scanning the stack:
let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;
Scanning rather than keeping a running counter is deliberate. The stack is
seven frames deep at worst across the whole corpus, so the cost is nothing, and
a counter would have to be unwound correctly by the mismatch recovery in
close, which pops frames out of the middle — a second thing to get right for
no gain.
RAINBOW_KEYWORDS moved up beside RULES and is now read by both the counter
and scope_pairs' filter through one is_rainbow helper; it used to be
declared next to scope_pairs and duplicated in spirit by the counter's
"count everything" rule. One list, two jobs — a scope is counted if and
only if it is sent, which is the invariant that keeps this bug from returning.
Depths now. Outermost begin = 0. begin inside a case at module level
= 0, the same as a sibling begin outside the case — that is the fix.
begin in begin = 1. begin in fork in begin = 2.
Behaviour deliberately unchanged. documentHighlight and the
missing-closer diagnostics never read depth — they use the pair ranges and
the unmatched lists — so they are untouched by construction, and every one of
their tests passed without edits. Demonstrated rather than asserted: reverting
the one line back to stack.len() fails exactly six tests, all of them
depth assertions (a_module_with_nested_begins_matches_every_pair,
a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows,
no_hidden_scope_counts_toward_the_depth,
only_begins_and_forks_stack_up_the_colours,
scope_pairs_depths_nest_and_forks_are_included,
the_scope_pairs_wire_shape_is_what_the_extension_reads) and none of the
highlight or diagnostic tests. That one experiment proves both halves at once:
the new tests really do catch the bug, and nothing outside depth moved.
Tests. 194 unit (was 190) and 9 e2e in this crate. Updated:
a_module_with_nested_begins_matches_every_pair ([0,1,2] → [0,0,1]),
scope_pairs_depths_nest_and_forks_are_included ([1,2,1] → [0,1,0]), the
pinned-JSON wire test (depth: 1 → 0), the e2e scopePairs assertion (2 →
1), and smoke.js ([1,2,1] → [0,1,0]). Added four:
a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows— the reported bug as a fixture: two siblingbegins, one of them wrapping acasethat wraps a third. Asserts[0, 0, 1]; before M5 this was[0, 0, 2].no_hidden_scope_counts_toward_the_depth— eight wrappers (module, package, generate, task, class, interface, program, specify), each around abeginthat must still come out at depth 0.only_begins_and_forks_stack_up_the_colours—begin/fork/beginis three real levels.the_depth_counter_and_the_wire_filter_read_the_same_list— walksRULESand asserts counted-iff-sent, so a new rule that forgets the question fails here rather than on a user's screen.
Corpus sweep (temporary, run and removed, as in M2/M3): all 860 files.
wire pairs 8 146 — byte-identical to M3's sweep, so nothing changed about
which pairs are sent; max wire depth 13 → 7; 0 malformed ranges. The
depth histogram is a clean decay — {0: 2881, 1: 2424, 2: 1689, 3: 700, 4: 278, 5: 120, 6: 41, 7: 13} — and the populated depth-0 bucket is the fix
made visible: under M3 almost every begin sat inside a module, so depth 0
was nearly empty and the whole palette was rotated by one.
Also closed here (M4 QA finding, accepted by lead review):
a_pushed_exclude_rebuilds_the_index_mid_session in tests/e2e.rs proved the
rescan half of reindex() but not the republish half, because the session had
no open buffer for the republish loop to iterate. It now opens one and counts
publishDiagnostics notifications for it: exactly 3 — one for the
didOpen, one per changed exclude — and the session pushes the same exclude
value twice in a row to assert that the no-op push publishes nothing and does
not rescan. Mutation-checked (expecting 4 fails with left: 3).
Verification. cargo fmt --all clean, cargo clippy --all-targets clean,
cargo test --workspace green, node smoke.js against a freshly built
target/debug/vfmt-server OK.
2026-08-24 — 0.3.1: the rainbow was painting with transparent colours
The bug, as reported. In Clock Divider/clkdivider_tb.v, typing begin
and pressing Enter at line 34 made both that begin and the end below it
invisible — not mis-coloured, gone. Everything else in the file kept its
colours.
Root cause, confirmed against the running server. The server was right: its
vfmt/scopePairs answer put the new pair at depth 3, with correct ranges. The
extension was wrong. It painted depth d with
ThemeColor('editorBracketHighlight.foreground' + (d % 6 + 1)), and VS Code's
colour registry gives visible defaults to only foreground1..3; 4, 5 and
6 default to #00000000, fully transparent, left for themes to define,
and most themes define none. So every pair at depth % 6 ∈ {3, 4, 5} was
painted transparent. VS Code's own bracket colouriser skips transparent entries
while cycling; ours did not. The old comment in extension.js — "an unset
editorBracketHighlight.foregroundN leaves the text its normal colour, which
is the right failure" — was wrong twice over: those keys are not unset, they
are set to transparent, and a keyword you cannot see is not a right failure.
This had been live since M3; M5 made it more visible by renumbering depths
downward, which moved a lot of real code from the safe 0–2 band into 3–5.
The fix, three parts.
- Our own colours.
contributes.colorsinpackage.jsondeclaresvfmt.rainbow1..6andvfmt.rainbowUnmatched, each with a default fordark,light,highContrastandhighContrastLight, and none of them transparent.extension.jsbuilds its decoration types from those ids. The values and the reasoning are in The palette above; the short version is that 1–3 copy VS Code's own bracket defaults per theme (so nothing changes for the depths that already worked) and 4–6 are new hues chosen to stay distinguishable from 1–3 within each theme. unmatchedon the wire.ScopePairsgainedunmatched: Vec<Range>— the block delimitersanalyzealready knew were partnerless, filtered by the sameRAINBOW_KEYWORDSaspairsand sorted by position — andextension.jspaints themvfmt.rainbowUnmatched. This is the owner's rule applied to the state that started it all: abeginyou have just typed has noendyet, so it has no depth and no rainbow colour, and "you can make their colour bright red for error in syntax, but don't just hide them."- Defensive reads in
paint.pair.depthgoes throughNumber.isIntegerbefore indexing the buckets (a non-numeric depth would index withNaNand drop the pair silently), andunmatchedis read as(result && result.unmatched) || [], so a newer extension against an older server keeps the rainbow and simply paints no reds.
Nothing about pairs moved. The filter, the ranges and M5's depth counting
are untouched — 78eeef6's six depth tests were not edited and still pass, and
the new an_opener_that_never_closes_is_reported_as_unmatched pins the
interaction directly: in three nested begins missing one end, the two that
do close still report depths [1, 2], because an unmatched frame is still an
enclosing scope while it sits on the stack.
Tests. vfmt_server: 285 unit (was 279; six new, all in the
vfmt/scopePairs section) and 16 e2e. New unit tests: an opener that never
closes is reported; a closer that opens nothing is reported; a balanced file
reports nothing; a keyword is never both paired and unmatched (three pairs, one
stray end, one unclosed fork, no range on both lists); unmatched carries
only block delimiters (a file with module, function and begin all open
reports one range, while analyze still sees three); a lone join is reported
but a lone endcase is not — the closer filter asks about expected, the
opener it wanted. Updated: the pinned-JSON wire test now carries an unmatched
entry, the empty-file shape test pins {"pairs": [], "unmatched": []}, and
scope_pairs_omits_a_pair_that_never_closed asserts the half-pair reappears in
the new list rather than vanishing. tests/e2e.rs opens a second, balanced
buffer in the same session and asserts unmatched comes back present and
empty; smoke.js does the same and additionally asserts the exact position of
the unclosed begin in a broken buffer.
Mutation-checked, both directions. Clearing lonely just before it is
sorted (so unmatched always ships empty) fails 7 unit tests and exactly one
e2e test (scope_highlights_…, at the new unmatched assertion, after every
older assertion in it has passed) — the new coverage is live, and no
pre-existing test depends on the new field. pairs.rs md5 verified identical
before and after (0182214662224b7782ffeb7b2d3d115b). In smoke.js, changing
the expected unmatched line from 2 to 9 fails with the real position printed;
reverted, md5 identical (0ff5e46f51b9c7f2079d899104776ddb).
Deviations from the plan.
- The plan said levels 1–3 should be gold/orchid/blue "same in dark and light". They are VS Code's dark values only; VS Code's light defaults are blue/green/brown and this follows them instead, because gold on white is ~1.4:1 contrast — the same invisibility bug wearing a different hat.
- Each colour also carries a
highContrastLightdefault, which the plan did not mention: without it a high-contrast light theme falls back to the ordinary light value, which happens to be fine here, but stating all four is one line each and leaves nothing to inference. vfmt.rainbowBeginEnd's description inpackage.jsonand the "Rainbow begin/end" section ofeditors/vscode/README.mdboth said the colours come from the theme's bracket palette. Both are now accurate and document the override recipe; they are this feature's own user-facing text, so they were updated rather than filed as a request.
Version 0.3.1. Cargo.toml [workspace.package], Cargo.lock (via
cargo check --workspace), editors/vscode/package.json,
editors/vscode/package-lock.json (both places), plus the illustrative
version strings in tools/RELEASING.md and README.md's install example — the
same set M5 touched for 0.3.0. target/debug/vfmt --version → vfmt 0.3.1.
CHANGELOG.md has a 0.3.1 — 2026-08-24 section in the changelog's voice.
Verification. cargo fmt --all -- --check clean; cargo clippy --workspace --all-targets 0 warnings; cargo test --workspace 1268 passed, 0
failed; node --check on extension.js and smoke.js clean; node smoke.js ../../target/debug/vfmt-server OK against a freshly built binary;
npx @vscode/vsce ls still accepts the manifest with the new
contributes.colors block. No new dependencies, no unwrap/expect/panic!
outside #[cfg(test)], no #[allow] added, and TODO.md and
docs/features/refactor/README.md were not touched.
QA log
2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate
Charter items 1–3 and 6 from editor_features_plan.md (4/5 are M1/M3, out of
scope this round). Verdict: PASS, no blocking findings.
Method. Read pairs.rs end to end against the hazard list in the plan and
the guard table in Handshakes above; ran the dev's own 162 unit + 7 e2e
tests; then attacked with two throwaway additions to pairs.rs's own
#[cfg(test)] mod tests (same crate access as the real code, since
vfmt_server is bin-only and has no lib target for an external test to link
against) — run, read, and removed before this log was written; nothing
below is in the committed tree.
1. Corpus sweep, reproduced independently. Walked corpus/ (the same
860-file, gitignored directory the dev used), tokenized each file, and for
every file whose Document::new produced zero parse diagnostics, ran
pairs::analyze and asserted zero unmatched opens/closes. Result: 860 files
scanned, 840 clean-parsing, 11 062 matched pairs, max depth 13, 0 false
positives — exact match to the dev's reported numbers in the Work log above.
2. Targeted attacks beyond the dev's own test list, each run as a single
probe printing (parse_diags_empty, pairs.len(), unmatched_open, unmatched_close):
| Probe | Result | Verdict |
|---|---|---|
virtual interface class IC; ... endclass (plan mentions this combination but the dev's tests only cover interface class without virtual) |
clean matcher: class..endclass, no unmatched. Parser itself does not yet accept this construct (parse_diags_empty=false) |
correct — gate stays consistent with the parser's own limits, and even so the matcher reports nothing false |
assert property (...) begin ... end else begin ... end — pass/fail action blocks, a common real-world idiom the plan/tests don't mention |
parses clean, 3 pairs (module + both action blocks), 0 unmatched | correct — confirms the property-only guard doesn't leak into ordinary begin/end inside the assertion statement |
covergroup cg with function sample(int lvl) extends base_cg; (the corpus-found guard, with extends appended) |
parses clean, 0 unmatched | correct — guard checks only the token immediately before function, unaffected by what follows |
typedef class C; forward decl followed by an unrelated class D before the real class C (package-scoped, three classes total) |
parses clean, 3 pairs, 0 unmatched | correct — confirms the prototype flag clears at ; and doesn't bleed into the next real declaration |
default clocking cb @(posedge clk); endclocking — the body form written with default on the same line as a real event (not a bare reference) |
parses clean, 2 pairs incl. clocking..endclocking |
correct — the two-token lookahead (ident then ;) correctly tells this apart from default clocking cb; |
`define DO_BEGIN begin then invoking `DO_BEGIN in place of a real begin, leaving a real end orphaned |
parser fails (as expected — the file really is broken without macro expansion); matcher: 1 pair (module), end correctly reported as the only unmatched closer, begin inside the `define line does not register as a keyword |
correct — confirms directive lines are opaque in full, body text included, not just macro invocations |
Same, mirrored (macro supplies the end, real begin left open) |
parser fails; matcher reports begin as the sole unmatched opener |
correct, symmetric to the above |
`ifdef/`elsif arms with two begins and one end (asymmetric arms, the literal hazard the charter names) |
parser fails (the raw token stream really is unbalanced, since this server does not evaluate conditions — confirmed at crates/vlog_parser/src/parser.rs:5482); matcher correctly reports one begin unmatched, matching reality of the raw text |
correct — this is not a case of "clean parse but matcher confused"; the file is genuinely malformed as written, both parser and matcher agree |
`ifdef/`else arms where one arm uses begin/end for two statements and the other is a single bare statement (a very common real idiom) |
parser fails — not because of begin/end, but because the second arm's statement lands illegally at module-item scope once both arms are read literally; matcher itself finds 0 unmatched |
correct — the parse failure is a pre-existing, unrelated diagnostic-quality question (bare statement outside a procedural block), not a pairs.rs defect; no missing-end warning is produced either way |
Labeled begin : a ... end : totally_different_name |
parses clean, matches on keywords alone as designed | correct, matches the documented "labels are not part of the match" assumption |
No probe produced a file that parses clean yet the matcher calls unbalanced — the property under test in charter item 3 held in every case tried, not only the ones the dev's own suite encodes.
3. Incidental, non-blocking finding (not a defect in this feature):
vlog_parser does not yet accept virtual interface class IC; ... endclass
or global clocking cb; (only default clocking cb; was checked by the dev).
Both are pre-existing parser gaps, not pairs.rs bugs — the matcher behaves
correctly on both regardless, and the diagnostics gate means neither can ever
produce a wrong warning. Filed as an FYI for whoever next touches
vlog_parser's grammar coverage, not a blocker here. (global clocking is
the one of the two the dev's guard table doesn't already list — worth a line
if the table is touched again, not worth blocking on.)
4. crates/vfmt_server/src/server.rs:109-121 (DocumentHighlightRequest
handler): self.offset(&uri, position) internally calls
self.workspace.document(&uri), and the closure passed to .and_then calls
self.workspace.document(&uri) a second time. Harmless — Document::new
isn't re-run, it's a cheap map lookup, and correctness is unaffected either
way (the second call cannot see a different document than the first inside
one synchronous request handler) — but it is two lookups where one would do.
Non-blocking style nit, left as-is per "you verify, you don't redesign."
5. Invariants.
cargo test --workspace: every crate green, 0 failures (162 unit + 7 e2e invfmt_serveralone, matching the Work log's count exactly).cargo fmt --all -- --check: clean.cargo clippy --all-targets --workspace: clean, no warnings.git diff --stat(working tree vsHEAD): onlycrates/vfmt_server/{diagnostics,main,server}.rsandcrates/vfmt_server/tests/e2e.rs, plus the untracked newcrates/vfmt_server/src/pairs.rsanddocs/features/editor-scopes/. No formatter,verify.rs, orvlog_parserfiles touched, confirmed by listing (git status) as well as the stat diff.- No
unwrap()/expect()/panic!inpairs.rs,server.rs, ordiagnostics.rsoutside#[cfg(test)], checked directly (grep over the code above each file's test module). - The one
#[allow(dead_code)](Pair::depth) carries an explanatory comment, satisfying CLAUDE.md's rule.
Verdict: PASS. No blocking findings. Two informational, non-blocking notes
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 Ranges 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 beforebeginand 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 1begin..endsurvives the filter.RAINBOW_KEYWORDSis["begin", "fork"]; sincePair::keywordstores the opener, this correctly admitsforkclosed by any ofjoin/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 attests/e2e.rs:576independently pins depth 2 for abeginnested 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 innerbeginis offered, 1 pair, from a file with one unclosedbegin). - Unopened doc →
null: no dedicated unit test exists for this specific handler (matches the pattern for every sibling handler inserver.rs— none of them have one either, so this is not an M3-specific gap). Verified directly against the built binary instead: spawnedvfmt-server, sentvfmt/scopePairsfor a URI never opened viadidOpen, got back{"jsonrpc":"2.0","id":2,"result":null}with no error. Matchesserver.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
TextEditorDecorationTypes built once inactivate(line 64-68), color-only (ThemeColorper index, nofontWeight), pushed intocontext.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 beforeawait client.sendRequest(...)(line 147) and compared after (line 159) — correct order, confirmed by reading theasynccontrol 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 danglingsetTimeoutafter unload. - Setting-off path:
onDidChangeConfiguration(line 83) updatesrainbowEnabledand callsrepaintVisible()synchronously (no debounce);paint()skips the request entirely whenrainbowEnabledis false and still runssetDecorations([])for every bucket (line 167-169), which is how a decoration type is cleared — confirmed this is unconditional (outside theif (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 onisVerilog()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'stry { 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 invfmt_server, matching the Work Log's count).cargo fmt --all -- --check: clean.cargo clippy --all-targets: clean, no warnings.git diff --statvsHEAD: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}. Novlog_formatter/vlog_parser/verify.rspaths touched.node -e "JSON.parse(...)"oneditors/vscode/package.json: valid; the newvfmt.rainbowBeginEndsetting and the M1contributes.snippetsblock are both present and unchanged in shape.npx @vscode/vsce lsaccepts the manifest and listspackage.json,extension.js,README.md,snippets/verilog.json,snippets/systemverilog.json— no error.- No
unwrap()/expect()/panic!in the newpairs.rs/server.rscode outside#[cfg(test)](grepped directly). No#[allow]remains inpairs.rs— the dev's removal of thePair::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.
2026-08-24 — QA round 4 (M5): rainbow depth renumbering + M4 gap closure
Charter: editor_features_plan.md's M5 section (the user-reported "invisible
begin/end" bug fix) plus the M4 exclude-republish gap the lead accepted last
round. Scope: uncommitted working tree only, diff vs 9a3a92c —
crates/vfmt_server/src/pairs.rs, crates/vfmt_server/tests/e2e.rs,
editors/vscode/smoke.js, docs/features/editor-scopes/README.md. Verdict:
PASS, one non-blocking finding (item 2 below).
Method. Same discipline as rounds 1–3: throwaway additions to pairs.rs's
own #[cfg(test)] mod tests for attacks that need the crate's private API,
run, read, and removed before this entry was written — each removal verified
md5-identical to the file's state before the addition. All three files
(pairs.rs, tests/e2e.rs, smoke.js) were confirmed byte-identical
(md5) after every mutation-and-restore cycle below; final git diff --stat
matches the four files in the charter exactly, same line counts as at
dispatch.
1. Adversarial depth probes, beyond the dev's own eight-wrapper table and the reported-bug fixture. Added four throwaway tests, all passed:
begininsidefunctioninsidemodule→[0]. Neither wrapper counts.- The generate-for hazard the charter calls out by name: a named generate
block (
for (...) begin : g ... end) is itself a realbeginkeyword and therefore is a rainbow frame — it is not the same thing as the enclosing (uncounted)generate.generate → for (...) begin : g → if (i == 0) begingives[0, 1]: the named block at 0, a begin nested inside it at 1. Checked this against both the dev's tests and the README (docs/features/editor-scopes/README.md:415, theno_hidden_scope_...case list) — the dev's owngeneratecase is an if-generate with a single anonymousbegin(no_hidden_scope_counts_toward_the_depth,crates/vfmt_server/src/pairs.rs:944), which never exercises a second begin nested inside a named generate-for block. No inconsistency between the dev's tests and the README, though: the depth logic is opener-keyword- based, not context-based, so a generate-for's named begin behaves identically to any other begin regardless of what encloses it. The dev's table and the README's claims both hold; the scenario was simply untested, and now is (as a throwaway, not left in the tree — see below). forkinsidecaseinsidebegin→[0, 1]: the case is hidden, the fork sees one enclosing rainbow frame (the begin).- Deeply mixed:
begin/ siblingbegininside afunction(itself inside a hiddenfunction, wrappingcase→fork→begin) →[0, 0, 1, 2].
No inconsistency found; removed before writing this entry
(pairs.rs md5 before/after: 975e8a4a80530309841415bd403cc71d, both
times).
2. The invariant test — mutation-checked, and it is weaker than its name
claims. Non-blocking, filed as a finding rather than fixed directly (it
would mean rewriting the test's structure, past "small unambiguous fix").
the_depth_counter_and_the_wire_filter_read_the_same_list
(crates/vfmt_server/src/pairs.rs:978-994) has two parts: a loop over RULES
comparing is_rainbow(rule.open) against RAINBOW_KEYWORDS.contains(&rule.open)
— which is tautological, since is_rainbow is defined as exactly that
.contains call (pairs.rs:74-76); the loop can never fail regardless of
what analyze or scope_pairs actually do — and a trailing pinned literal,
assert_eq!(RAINBOW_KEYWORDS, ["begin", "fork"], ...), which is the only line
that has ever caught anything.
- Mutation A: added
"case"toRAINBOW_KEYWORDSand, separately, changedscope_pairs's filter to a disconnected hardcoded["begin", "fork"].contains(...)(recreating the pre-M5 shape: a keyword counted byanalyzebut not sent byscope_pairs). Result: the test did fail — but at the trailing pinned assert (left: ["begin", "fork", "case"], right: ["begin", "fork"],pairs.rs:993), not at the per-rule loop. The loop ran to completion without incident. - Mutation B, isolating the loop from the pinned literal: left
RAINBOW_KEYWORDSat["begin", "fork"](so the trailing assert cannot fire) and made onlyanalyze's counter diverge —stack.iter().filter(|f| f.rule.open == "begin"), silently droppingforkfrom what gets counted, without touchingscope_pairs's filter oris_rainbow. Result:the_depth_counter_and_the_wire_filter_read_the_same_listpassed (both its loop and its pinned assert are blind to this, since neither callsanalyzeorscope_pairs). The only failure was an ordinary depth test,only_begins_and_forks_stack_up_the_colours(pairs.rs:967-975), which caught it because it happens to nest a fork under a begin. - Conclusion: the charter's premise — "confirm it actually fails if a
keyword is added to
RAINBOW_KEYWORDSwithout the filter following" — holds for the specific case where the two functions stay wired throughis_rainbowand only the set itself changes (mutation A), but that protection comes entirely from the pinned literal, which will need editing by hand on every legitimate future addition to the rainbow — exactly the "canary, not proof" pattern. It does not hold for a regression whereanalyzeandscope_pairsare rewired to read from different sources independently ofRAINBOW_KEYWORDS(mutation B) — the comment's claim that this is "asserted over the whole rule table" and that a divergence "fails here" is not accurate; the real backstop for mutation B's shape is coincidental coverage from the ordinary depth tests, not this test. Today's single-shared-list design (is_rainbowcalled from both sites) makes mutation B's shape unlikely to arise by accident, but the test as named and commented would not catch it if it did. Suggest either renaming/re-scoping the test to describe what it actually checks (a pinned-value canary onRAINBOW_KEYWORDS), or strengthening the loop to callanalyzeandscope_pairson a per-rule fixture and compare their outputs directly rather than comparingis_rainbowto itself. Left as a finding, not fixed, since either direction is a design choice for the dev/lead. - Both mutations reverted;
pairs.rsmd5confirmed975e8a4a80530309841415bd403cc71dbefore, during isolation, and after.
3. Mutation-check the core depth line. Reverted
stack.iter().filter(|f| is_rainbow(f.rule.open)).count() (pairs.rs:157)
to stack.len() as u32. cargo test -p vfmt_server (unit): exactly six
failures, all depth assertions, names matching the dev's Work Log list
exactly (a_module_with_nested_begins_matches_every_pair,
a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows,
no_hidden_scope_counts_toward_the_depth,
only_begins_and_forks_stack_up_the_colours,
scope_pairs_depths_nest_and_forks_are_included,
the_scope_pairs_wire_shape_is_what_the_extension_reads) — 188 unit tests
still passed. The e2e suite adds one more failure under this mutation,
scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire, but
confirmed with --nocapture that it panics specifically at
tests/e2e.rs:590 (the pairs[0]["depth"] assertion, left: Number(2), right: 1) — every documentHighlight assertion earlier in that same test
runs and passes first. So "no documentHighlight or missing-end diagnostic
test moves" holds exactly as claimed; the dev's "six" was scoped to the unit
suite, and the one e2e test that also carries a depth assertion fails only on
that line. Reverted; pairs.rs md5 confirmed unchanged.
4. M4 gap closure — the republish assertion.
a_pushed_exclude_rebuilds_the_index_mid_session
(crates/vfmt_server/tests/e2e.rs) passes as committed. Mutation-checked the
new count: changed assert_eq!(publishes, 3, ...) to 4
(tests/e2e.rs:766) — failed as expected (left: 3, right: 4); reverted,
md5 confirmed unchanged (ce62cbe2d094214d0e132cda9c252507 before and
after).
5. Corpus sweep, reproduced independently. Same throwaway-test discipline
as rounds 1–2: walked the 860-file corpus/ directory (.v/.sv/.vh/.svh),
ran scope_pairs on every file that lexes, and checked every emitted range
for a sane open ≤ close ordering. Removed before writing this entry.
Result: scanned 860, wire pairs 8 146 — matches M3's sweep exactly, matches
the dev's claim — max depth 7 (was 13 under M3/M4), 0 malformed ranges.
Histogram (depth → pair count): {0: 2881, 1: 2424, 2: 1689, 3: 700, 4: 278, 5: 120, 6: 41, 7: 13} — identical to the dev's reported histogram in the Work
log. pairs.rs md5 confirmed 975e8a4a80530309841415bd403cc71d after
removal, matching its state before the sweep test was added.
6. smoke.js and invariants.
- Built
target/debug/vfmt-serverfresh (cargo build -p vfmt_server), rannode smoke.js ../../target/debug/vfmt-server: OK. Mutation check: changed the expected-depths literal from[0, 1, 0]to[9, 9, 9], reran — failed as expected (smoke: FAIL — expected depths [0,1,0] ..., got [0,1,0], exit code 1 confirmed separately from the pipeline's own exit code), reverted;md5ofsmoke.jsbefore and after is identical (2092dbb2331bd040932f3ccb76246398). node --checkon bothsmoke.jsandextension.js: clean.cargo test --workspace: every crate green (194 unit + 9 e2e invfmt_server, matching the Work Log's count), 0 failures, both before any mutation and again after every mutation was reverted.cargo fmt --all -- --check: clean.cargo clippy --workspace --all-targets: clean, no warnings (re-checked after touching the two Rust files to defeat incremental-build caching).git diff --statvsHEAD(9a3a92c): exactly the four files in the charter, same shape as at dispatch —crates/vfmt_server/src/pairs.rs,crates/vfmt_server/tests/e2e.rs,docs/features/editor-scopes/README.md,editors/vscode/smoke.js. Novlog_formatter/vlog_parser/verify.rspath touched.- No
unwrap()/expect()/panic!added outside#[cfg(test)]in the diff (grepped the diff hunks directly); no#[allow]added.
Verdict: PASS. No blocking findings. One non-blocking finding (item 2):
the_depth_counter_and_the_wire_filter_read_the_same_list's per-rule loop is
tautological and its real protection is a pinned-literal canary rather than a
comparison of analyze's and scope_pairs's actual behavior against each
other — worth a rename or a rewrite next time this test is touched, not
blocking today's fix (which is correct and well covered by the ordinary depth
tests).
2026-08-24 — QA round 5 (0.3.1): the transparent-colour fix and unmatched
Charter: the owner-confirmed root cause (transparent foreground4..6
defaults) and its fix — the extension's own opaque colour ids, unmatched on
the wire, and the defensive reads in paint. Scope: uncommitted working tree,
diff vs HEAD (d8e3708) — CHANGELOG.md, Cargo.toml, Cargo.lock,
README.md, crates/vfmt_server/src/pairs.rs, crates/vfmt_server/tests/e2e.rs,
docs/features/editor-scopes/README.md, editors/vscode/{README.md, extension.js, package-lock.json, package.json, smoke.js}, tools/RELEASING.md.
Verdict: ship-after-fixes — one fix applied directly (below), one
low-severity non-blocking finding filed.
Method. Same discipline as rounds 1–4: throwaway additions to pairs.rs's
own #[cfg(test)] mod tests, run, read, removed before this entry was
written; md5 of pairs.rs confirmed 0182214662224b7782ffeb7b2d3d115b
before, and identical again after removal — matching the dev's own reported
hash for the same file, so the working tree really is what the Work Log
describes.
1. Gates. cargo fmt --all -- --check: clean. cargo clippy --workspace --all-targets: clean, 0 warnings. cargo test --workspace: 1268 passed, 0
failed — summed the per-crate test result: lines independently rather than
trusting the dev's total; vfmt_server alone is 285 unit + 16 e2e, an
exact match to the Work Log. node --check on extension.js and smoke.js:
both clean. node smoke.js ../../target/debug/vfmt-server against a freshly
built (cargo build -p vfmt_server) binary: OK.
2. The real user scenario, end to end. Drove the built debug server over
stdio (a hand-rolled probe mirroring smoke.js's framing, since the crate
exposes no lib target) against the actual file named in the bug report,
/Users/guoliangchen/repo/Verilog-Design-Examples/Clock Divider/clkdivider_tb.v
— note this required url.pathToFileURL() to percent-encode the space in the
directory name; a naive file://${path} template gave the server a URI it
rejected with unexpected character at index 61, which is a probe-tooling
gotcha and not a server defect (LSP URIs are always supposed to arrive
percent-encoded; VS Code's own document.uri.toString() does this correctly).
Findings, both exactly as claimed:
- The depth-3 pair survives. The
beginat 0-based line 33, character 29 (1-based line 34, the exact keyword the bug report named) is still inpairs, atdepth: 3, closed by theendat 0-based line 35. Confirms the server-side data was correct all along — this was always a client-painting bug, as the root-cause writeup says. unmatchedcorrectly names the actual orphan, which is not the line-34begin. The file's real structure (traced by hand against the returned ranges):repeat (30) beginat 0-based line 27 / char 18 opens a frame that is never closed — the file is missing oneendbeforeendtask. The line-34beginthe user typed does have a partner two lines down; it is three frames deep inside the unclosedrepeat, which is exactly why the bug was invisible in the first place (depth 3 is whereforeground4starts).unmatchedreports one entry, at 0-based line 27 / char 18–23 — therepeat'sbegin, not line 34's. This is a stronger check than any synthetic fixture in the suite: it is a real, messy, 78-line file with a pre-existing authoring bug, and the matcher still finds the one keyword that is genuinely alone rather than the one a naive "most recently typed" guess would name.
3. Colour-id audit, programmatic. Extracted every vfmt.rainbow* id
extension.js references (vfmt.rainbow${index + 1} for index 0–5, plus
the literal vfmt.rainbowUnmatched) and diffed against package.json's
contributes.colors array. All 7 declared, all 7 referenced, no orphans
either direction. For each, checked all four defaults keys
(dark/light/highContrast/highContrastLight) are present and parsed
each as #RRGGBB (alpha 255) or #RRGGBBAA (alpha from the last byte),
flagging anything below alpha 200/255. 0 findings — every default is a
plain 6-digit opaque hex; none of the eight-digit "looks opaque but has a
sneaky alpha byte" shape the bug's root cause would predict appears anywhere.
4. Adversarial probes (seven throwaway #[cfg(test)] additions to
pairs.rs, run together, all passed, then removed — see Method):
| Probe | Result |
|---|---|
A file that is only end (first token, nothing else) |
one unmatched entry at 0:0; no crash on an empty stack |
Every join/join_any/join_none alone (no fork) |
each reported as unmatched_close with expected: "fork"; an unclosed fork itself names join (the first, canonical closer) — never join_any/join_none |
Unmatched begin at EOF with no trailing newline |
still reported; scope_pairs correctly narrows the raw engine's ["module", "begin"] (the module is also unclosed in this fixture) down to ["begin"] |
begin/end/fork/join spelled inside a // comment and a $display string |
zero pairs, zero unmatched from the fake text — only the one real begin/end counted, confirming comments/strings never reach the matcher even for the unmatched path, not just the matched one |
Both a stray end and an unclosed begin in one file |
both reported, sorted by position (stray end first, unclosed begin second, matching source order) |
An unclosed begin after a comment with é, ✓, and 日本語 |
UTF-16 character offset lands on the keyword exactly (10), unaffected by the multibyte text before it |
A minimized reproduction of the clkdivider_tb.v shape (an unclosed repeat-style outer begin wrapping three cleanly-nested begins) |
the three inner pairs close normally at depths [1, 2, 3], unaffected by their unmatched enclosing frame; only the outer begin is reported unmatched — same shape as finding 2 above, now pinned as a minimal fixture |
No probe found a false positive, a false negative, a panic, or a misattributed range.
5. 78eeef6's pinned depth tests, independently diffed rather than taken on
faith. git diff 78eeef6 -- crates/vfmt_server/src/pairs.rs, checked for
each of the six tests the Work Log names as unedited:
a_module_with_nested_begins_matches_every_pair,
a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows,
no_hidden_scope_counts_toward_the_depth,
only_begins_and_forks_stack_up_the_colours,
scope_pairs_depths_nest_and_forks_are_included — byte-identical, zero
diff hunks touching any of the five. The sixth,
the_scope_pairs_wire_shape_is_what_the_extension_reads, does appear in the
diff, but only for the documented reason: the pinned JSON literal gained the
new unmatched field and a comment update, not a depth-logic change. Matches
the claim exactly.
6. extension.js — the two specific code paths named in the charter.
- Old-server response with no
unmatchedkey. Readeditors/vscode/extension.js:194:for (const range of (result && result.unmatched) || []) { unmatched.push(asRange(range)); }. A missing key makesresult.unmatchedundefined,(result && undefined) || []evaluates to[], and the loop is a no-op. Correct, matches the claim. depth: null/ negative from a hostile server.extension.js:188:const depth = Number.isInteger(pair.depth) ? pair.depth : 0;— the guard is genuinely reached beforebuckets[depth % RAINBOW_COLORS]on the next line, andNumber.isInteger(null)isfalse, sonullis caught and substituted with0correctly. But the guard does not fully do what its comment claims for a negative integer.Number.isInteger(-1)istrue(it is a real integer), so-1passes through unchanged; JavaScript's%is not Euclidean, so-1 % RAINBOW_COLORSis-1, not5, andbuckets[-1]isundefined. The next line,ranges.push(...), then throwsTypeError: Cannot read properties of undefined (reading 'push')— confirmed with a standalone Node repro, not just by reading the code. That throw is inside thefor (const pair of ...)loop inpaint(), which is not inside the function'stry/catch(only theclient.sendRequestawait is guarded), so it propagates out ofpaint()as an unhandled rejection from the caller inrepaintVisible's loop, aborting that repaint partway through — the buckets already painted stay painted, the rest of that call's decorations (includingunmatched) never get set, and there is no console-visible failure beyond whatever VS Code's extension host logs for an unhandled rejection. Severity: low, non-blocking. The real server'sdepthis a Rustu32serialized throughserde, which cannot be negative — this path is unreachable against the server this extension actually ships with, and every invariant this feature exists to protect (never hide a character, never corrupt code) is about the file, which this cannot touch; the worst case is a skipped repaint of a cosmetic decoration, self-healing on the next debounce tick against a well-behaved server. Filed because the work log's own framing — "a non-numeric depth would index withNaNand drop the pair silently" — describes theNaNcase correctly but is silent about the negative-integer case, which behaves differently (a thrown exception, not a silent drop) and is exactly the shape the charter asked to be probed. Worth eitherMath.absbefore the modulo, an explicitdepth >= 0check alongsideNumber.isInteger, or a code comment admitting the assumption — not worth blocking this release, since it requires a server this extension does not have.
7. Version bump — found and fixed directly. Grepped the tree for stray
0.3.0 outside changelog history and cache fixtures. cargo metadata: all
eight workspace crates report 0.3.1. Both package-lock.json spots
(top-level version and packages[""].version): 0.3.1. Cargo.lock's
diff against HEAD is eight version = "0.3.0" → "0.3.1" line pairs, one
per workspace crate, nothing else — confirmed with a diff filtered to
added/removed lines only, no dependency added or removed. CHANGELOG.md's
0.3.1 section read in full: accurate to the diff, including the one line
that could have overclaimed and doesn't — "Matched pairs, their nesting
depths and the missing-end warnings are unchanged" — verified true by
finding 5 above.
One gap: editors/vscode/README.md:49 and :56 still read
vfmt-0.3.0.vsix in the install-example commands, while the parallel example
in the repo-root README.md:584 correctly reads vfmt-0.3.1.vsix. This file
is not pristine — this very diff touches it for the rainbow-palette
documentation (git diff HEAD -- editors/vscode/README.md, the
workbench.colorCustomizations snippet and the "seven colours" rewrite) —
but the two version strings were already stale at 0.3.0 before this diff
(git show HEAD:editors/vscode/README.md shows the same vfmt-0.3.0.vsix
text, so this is not a regression this diff introduced), and the Work Log's
own version-bump list names only tools/RELEASING.md and (root) README.md
as the "illustrative version strings" set, omitting this file even though it
carries the same kind of string. A one-line-each, unambiguous doc fix per
this role's charter — fixed directly, both occurrences now read
vfmt-0.3.1.vsix, no code or test changes involved.
8. Invariants. No unwrap()/expect()/panic!()/#[allow] added
anywhere in the pairs.rs diff (grepped every added line of git diff HEAD -- pairs.rs for all four, programmatically — 0 hits, including inside the new
test module, since the new tests use only assert_eq!/assert!). git diff --stat vs HEAD matches the charter's file list exactly, confirmed by
listing rather than assumed.
Verdict: ship-after-fixes. No blocking findings — the reported bug is
genuinely fixed, confirmed against the real file from the bug report rather
than only synthetic fixtures, and unmatched correctly distinguishes "has a
partner but is deeply nested" from "genuinely alone" on a real 78-line file
with a pre-existing authoring bug. One doc staleness was small and
unambiguous enough to fix directly (item 7). One low-severity, non-blocking
finding remains for the lead/dev to accept or schedule (item 6, the
negative-depth modulo gap) — it cannot fire against this server as shipped,
so it does not block 0.3.1, but the work log's defensive-reads claim should
either be corrected or the code tightened next time this file is touched.
Review
2026-08-24 — lead review of M2 (after QA round 1)
Read pairs.rs in full plus the four integration diffs. Approved and
committed. Notes:
- The non-cascading recovery rule and the parse-error gate are the two load-bearing decisions; both are stated in comments where they live and both are pinned by tests that would fail if either were "simplified". Good.
- The
covergroup ... with function sampleguard coming from a corpus sweep rather than the plan is exactly why the sweep is worth its cost; keep sweeping in future rounds. randsequence(LRM: closed byendsequence) is not in the pair set. Acceptable today — the parser rejects those files anyway, so the gate never lets a wrong warning out — but worth a line in Assumptions if the parser ever learns it.- QA's non-blocking note about the double
workspace.documentlookup in thedocumentHighlighthandler 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.versioncaptured 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.
2026-08-24 — lead review of M5 (after QA round 4)
Read the diff (one-line core change, the const hoist, tests, docs). Approved and committed. Notes:
- M3's "depth reads differences only" reasoning — endorsed in the M3 review above — was wrong, and the user's report is the counterexample: a hidden scope between two begins is a difference the screen cannot explain. The corrected Assumptions bullet says this well.
- QA's non-blocking finding on
the_depth_counter_and_the_wire_filter_read_the_same_listis accepted as-is: the per-rule loop is tautological throughis_rainbow, but the invariant it names is genuinely held by the trailing pinned-literal assert plus the ordinary depth tests (QA's mutation B was caught byonly_begins_and_forks_stack_up_the_colours). Coverage is real; it just lives across tests rather than in the one with the name. Not worth restructuring now; noted so the next reader of that test knows.
2026-08-24 — lead review of the invisibility fix (after QA round 5)
Root cause was mine to confirm before the dev brief: the server's answers
were correct, and the invisibility came from painting depth 3–5 with
editorBracketHighlight.foreground4..6, whose VS Code defaults are
transparent. The fix is the right shape — extension-contributed
vfmt.rainbow1..6 colors that are never transparent in any theme variant,
plus vfmt.rainbowUnmatched bright red for genuinely unmatched tokens,
exactly the owner's never-hide/red-for-errors ruling. Dev's deviation
(VS Code's real light-palette for 1–3 instead of gold-on-white) is
approved: it avoids re-shipping the same bug in light themes. QA verified
the actual reported file end-to-end — the depth-3 pair renders and the
true orphan (repeat (30) begin, line 28) is the one reported unmatched —
and audited every color default programmatically. I applied QA's LOW
myself: the depth guard now also rejects negative integers
(extension.js:188), so a hostile depth can never throw mid-repaint.
Gates re-run after that one-liner: 1268 tests, 0 failures, smoke OK.
Accepted; ships as 0.3.1.