New pairs.rs: a stack matcher over the token stream for begin/end and 16 relative pairs, with guards for every no-body construct that spells an opener keyword (extern/DPI prototypes, typedef class, virtual interface, assert property, covergroup with function sample, ...). Non-cascading mismatch recovery makes one missing end point at the exact unclosed begin. Feeds textDocument/documentHighlight (cursor on begin highlights its matching end) and WARNING diagnostics for unmatched openers/closers — gated on the parse already failing, so macro/ifdef keyword imbalance in working code can never warn. Corpus sweep: 840 clean-parsing files, 11,062 matched pairs, 0 false positives (reproduced independently by QA). Co-Authored-By: Claude Fable 5 <[email protected]>
21 KiB
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. This milestone ships the engine and two of its 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.
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. - Analysis is cheap enough to redo per request.
analyzeis 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 totokensinDocument, computed once per change like everything else there.
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 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.
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.
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/scopePairs+ the extension's rainbow — next milestone.- 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.
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).
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.