Files
lucioandClaude Fable 5 34938fbcf1 LSP §9c: textDocument/linkedEditingRange
SystemVerilog's closing labels now edit as one: module/interface,
package, class, function, task, clocking, generate and statement
blocks, fork/join, and the prefix-labeled b : begin ... end : b form —
every pair read off the AST's own end_label_span fields (the parser
already recorded both halves on one node; no parser change). A pair is
offered only when both halves exist and hold identical plain-identifier
text: mismatched labels, absent labels, and escaped identifiers all
answer null rather than link something a keystroke would corrupt. The
response carries the SV word pattern (with $), whose anchoring QA
verified against VS Code's linked-editing source — full-string
validation, anchors correct.

33 tests added (dev 25 + QA 8): exact-range decoding through the
server's own position converter (never the colon), the both-labels and
stray-second-end tolerant-parse shapes, identically-named nested
blocks pinned by exact ranges, and an 83k-offset corpus sweep
asserting totality and the identical-text/non-overlap invariants over
real labeled RTL. program/property/sequence/covergroup are filed as
parser Handshake wants.

docs/features/linked-editing/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 15:59:13 -07:00
..

linked-editing

Goal

textDocument/linkedEditingRange (TODO.md §9c) makes SystemVerilog's closing labels edit as one name. module m ... endmodule : m writes m twice, and so do function f ... endfunction : f, class c ... endclass : c, package p, interface i, a named begin : blk ... end : blk, a named fork ... join : blk, a generate block's begin : g ... end : g and clocking cb ... endclocking : cb. When the cursor sits on either occurrence the server answers with both ranges, and the editor then applies every keystroke to both at once — which is the one editing operation where SV's optional closing label stops being a maintenance cost. The whole feature is a pure function over one buffer's parse tree: no index, no workspace, no engine change.

Assumptions

  • A closing label is optional in SV, and an absent one is not an invitation. endmodule with no : m gets no linked ranges at all. There is nothing to co-edit, and a linked-editing answer is not a place to offer to create one.
  • Identical text is required, so a mismatched label answers null. The spec says the ranges "must have identical length and contain identical text content"; module m ... endmodule : wrong violates both. Answering the pair anyway would silently "fix" the mismatch on the user's next keystroke — an edit they did not ask for, applied to code they can see is broken. Broken code is the user's to fix; the server declines.
  • Escaped identifiers are excluded. \my$odd.name is an identifier whose extent depends on a trailing space, and the wordPattern this feature sends cannot describe one. Rather than send a pattern that would let a client corrupt the escape, a pair whose name is not a plain [A-Za-z_][A-Za-z0-9_$]* answers null — even when both halves are the same escaped name.
  • The two name spans always come from one AST node, never from a text search for the same word. begin : x begin : x ... end : x end : x has two pairs whose four names are byte-identical; each end's label belongs to the block node that owns it, so the inner cursor answers the inner pair and the outer cursor the outer one. This is the property the "evil fixture" test pins.
  • Name spans never nest and never touch, which is what lets the lookup be a flat "which span covers this offset" over every pair in the file rather than an innermost-wins descent. Two label occurrences are always separated by at least a keyword.
  • A cursor one byte past the end of a name still counts (m|), the same rule pairs::highlights uses: an editor leaves the caret after the character just typed, and linked editing that switched off at the end of the word would be useless exactly while the user is typing.
  • A buffer that does not parse answers whatever its tolerant tree holds. A construct the parser turned into ItemKind::Error has no label spans, so it simply has no pair — the same "no answer" every other position gets.

Handshakes

Consumed from vlog_parser::ast — read-only, and nothing was changed there this round. Every construct this feature serves is one that already records both name spans on the same node:

construct header span closing-label span
module / macromodule / interface Module::name_span Module::end_label_span
package ItemKind::Package::name_span ItemKind::Package::end_label_span
class ClassDecl::name_span ClassDecl::end_label_span
function FunctionDecl::name_span FunctionDecl::end_label_span
task TaskDecl::name_span TaskDecl::end_label_span
clocking ClockingDecl::name (Name::span) ClockingDecl::end_label_span
generate begin : g GenBlock::label_span GenBlock::end_label_span
statement begin : b StmtKind::Block::label_span StmtKind::Block::end_label_span
fork ... join : b StmtKind::ForkJoin::label_span StmtKind::ForkJoin::end_label_span
prefix-labelled b : begin ... end : b StmtKind::Labeled::name_span the wrapped block's end_label_span

The last row is the one indirection: IEEE 1800 §9.3.5 lets a block be named before its keyword, and the parser then puts the name on the enclosing StmtKind::Labeled and leaves the block's own label empty. It is still one syntactic pair — the LRM requires the end label to match that name — so it is served, and only when the block wrote no label of its own (writing both is illegal, and the block's own pair wins there).

Not reachable, and deliberately not chased this round — these constructs can carry a closing label in SV but the tree keeps no span for it, so they get no linked ranges:

  1. program p; ... endprogram : p. program is a keyword the lexer knows (token.rs) but no parse arm claims, so the declaration lands in ItemKind::Error/verbatim text with no name span at all.
  2. property / sequence / covergroup ... endgroup / constraint. Captured byte-for-byte as ItemKind::Verbatim(RawText) by design (docs/features/classes/README.md, docs/features/assertions/README.md), so neither name is a span.
  3. specify / primitive / modport. No closing label exists for these in the grammar, so there is nothing to link.

Requested of vlog_parser: nothing. The one thing this feature would gain from a parser round is (1) above — a program node with the same name_span + end_label_span pair Module already has, at which point it joins the table with no change here beyond one match arm. That is recorded as a want, not as a blocker: the feature is complete for every construct the tree models.

Promised to nobody. linked::linked_editing_ranges(&Document, u32) has one caller, server.rs's LinkedEditingRange arm.

Status / TODO

  • crates/lucisv_server/src/linked.rs: the pair walk and the lookup.
  • linkedEditingRangeProvider advertised (LinkedEditingRangeServerCapabilities::Simple(true)).
  • request::LinkedEditingRange dispatched in server.rs, null for an unopened buffer and for a position on no pair.
  • wordPattern sent, as a const.
  • Unit tests: every construct kind, both directions, cursor at start/middle/end, unlabeled → null, mismatched → null, nesting, identical names at different nesting, escaped identifiers, multibyte text, out-of-range positions.
  • Server-level tests: dispatch, capability, unopened buffer.
  • e2e: the real binary, one round trip decoding both ranges and the wordPattern.
  • TODO.md §9c checkbox with its → delivery line.
  • docs/features/lucisv-server/README.md capability table.

Work log

2026-08-26 — dev agent

  • One new module, one dispatch arm, one capability, no engine change. crates/lucisv_server/src/linked.rs holds the whole feature: linked_editing_ranges(doc, offset) -> Option<LinkedEditingRanges>, a private walk that collects every (header, closing label) pair the tree records, and the two filters that decide whether a pair may be linked. vlog_parser, vlog_semantic and state.rs are untouched.
  • The AST already carried everything. Grepping end_label_span found nine nodes with the pair on them — the ten rows of the Handshakes table, the tenth being the prefix-label indirection — so nothing here searches text or matches names. The pair is a node, which is exactly what makes the begin : x begin : x ... end : x end : x fixture answer correctly instead of by luck.
  • Collect-then-find, not an offset-guided descent. type_def.rs descends by span.contains, because a declaration's window really does nest. Label name spans do not nest and do not touch, so the flat walk is both simpler and the honest model: there is at most one pair a given offset can belong to, and a descent would only be a slower way to find it. The walk is one pass over a tree that was already built for this buffer.
  • Two refusals, both deliberate, both tested. A mismatched label (endmodule : wrong) and an escaped identifier answer null rather than a pair — reasons in Assumptions above. The mismatch decision is the one worth re-reading: linking non-identical text is against the spec's own wording, and a linked edit that silently repairs a mismatch is an edit the user never asked for.
  • wordPattern is sent rather than left to the client's language default. VS Code's fallback word pattern for an unknown language id would not include $, which is legal in an SV identifier after the first character, so a user typing foo$bar would see the link drop halfway. The pattern is one const beside the code that uses it, anchored on both ends, and it deliberately does not try to describe an escaped identifier — those answer null instead.
  • Nothing in editors/ moved. The VS Code client picks linked editing up from the advertised capability, and smoke.js's capability list belongs to docs/features/editor-packaging/README.md (the same call the inlay-hints round made).

Results. cargo test --workspace: 1902 passed, 0 failed (1877 on a stashed tree, measured rather than assumed — 22 unit tests in linked.rs, 2 in server.rs, 1 e2e; the capability assertion joined main.rs's existing every_advertised_capability_is_implemented). cargo clippy --all-targets: silent. cargo fmt --all -- --check: clean. cargo build && node editors/vscode/smoke.js target/debug/lucisv-server: passes. No new dependencies, no version bump, no commits.

QA log

2026-08-26 — QA agent

Gates. cargo fmt --all -- --check: clean (after cargo fmt --all on the tests added below — the dev's own code needed no reformatting). cargo clippy --all-targets --workspace: silent. cargo build && node editors/vscode/smoke.js target/debug/lucisv-server: smoke: OK. cargo test --workspace: 1910 passed, 0 failed (1902 as claimed, +8 new tests added below).

Verdict: committable as-is. No wrong-pairing bug found anywhere the "never nest, never touch" claim was attacked; the one open question worth a second pair of eyes (WORD_PATTERN anchoring) was checked against VS Code's actual source and is correct as shipped. All new tests below are additions to crates/lucisv_server/src/linked.rs's existing #[cfg(test)] mod tests; no production code changed.

1. "Never nest, never touch" — attacked directly, holds.

  • (a) Both a prefix label and the block's own label, on tolerant-parsed code. x : begin : y ... end : y (block writes its own label y, so IEEE 1800 §9.3.5's prefix form is doubly-illegal but the tolerant parser accepts it). Traced through parser.rs: parse_stmt_kind reads the prefix name x into StmtKind::Labeled, then parse_keyword_stmt's "begin" arm reads the block's own : y into Block::label/label_span. In linked.rs, prefix_labelled_end (line 273) checks label: None before firing, so with label: Some(y) it returns None and no pair is pushed for the x node — only the recursion into the block itself pushes (y, y). Verified by new test a_block_named_both_ways_answers_only_the_blocks_own_pair (line 689): x answers nothing at all, y answers the correct pair from both directions. The gate does exactly what the doc comment says. Verified-clean.
  • (a, continued) Prefix label present, block writes no label of its own, but the close doesn't match the prefix name — x : begin ... end : y. Here the gate does fire (label: None) and pushes (x, y), which is a real, syntactically-recorded pair whose two names simply differ. is_linkable (line 93) correctly declines it on the text-equality check — same path as any other mismatch, no special-casing needed. New test a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched (line 707). Verified-clean.
  • (b) Zero-length/overlapping spans from error recovery. Fed the tolerant parser: a label written with end missing (begin : blk never closed before endmodule), no closer at all before EOF, a colon with no name after it (begin : \n end : \n and begin :\n end\n), a block named but the buffer just ends mid-body. All four produce zero pairs (traced: expect_name in parser.rs:633 returns Err on a missing identifier, which propagates out of parse_label/parse_keyword_stmt and is absorbed by the caller's recovery — nothing reaches linked.rs with a label at all in that case) or a pair missing one half, which push's (Some, Some) match (line 121) and its is_empty() guard both filter before it ever reaches the pair list. New test broken_and_unclosed_labeled_constructs_never_panic (line 742) sweeps every offset of all four fixtures for panics via a new assert_total_and_sane helper (also used by the tests below). Verified-clean.
  • (b, continued) Two end : x for one begin : x. begin : x ... end : x \n end : x (the second is leftover after the first closes the block). Confirmed by inspection (items_pairs on the fixture) that exactly one pair is recorded, closing on the first end : x — the second is dead tokens at item-recovery level and answers null everywhere in its own span. No phantom third occurrence, no panic. New test a_stray_second_end_label_after_the_block_already_closed_is_inert (line 719). Verified-clean.
  • (c) Adjacent labels, no separator. endfunction : f immediately followed by endmodule : m on the next line, and the no-space spellings begin:x / end:x. Structurally, two distinct identifier spans can never truly touch (span1.end == span2.start) because the lexer's maximal-munch tokenization requires at least one non-identifier byte (whitespace, :, a keyword) between any two identifier tokens — so Pair::covers's inclusive <= on both ends (line 83) can never make one offset satisfy two different pairs. Verified over the real boundary bytes: adjacent_closing_labels_never_bleed_into_each_other (line 754) plus the assert_total_and_sane sweep inside it. Verified-clean.

2. Identical-text requirement, ranges decoded precisely. New test ranges_cover_exactly_the_identifier_never_the_colon_or_comment (line 769) decodes each answer's Range back to a byte span with Positions::offset (convert.rs:39 — the same function the server uses to turn a client position into an offset) and asserts &text[start..end] == name for three shapes: endmodule : /*c*/ m (comment between colon and name), end:x (no spaces at all), and a label split across a newline (begin :\n x). All three: the range is exactly the identifier, never the colon, a space, or the comment. Also added a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing (line 874): cursor on the colon, one byte after the colon, and on the indentation between the two labels all answer null, even with the label letters immediately adjacent. Verified-clean — no off-by-one that would let a client type into the colon.

3. The evil fixture. Re-read identical_names_at_different_nesting_pair_syntactically (linked.rs, pre-existing) — it already asserts the exact (line, start, end) tuples for both pairs in both directions, not just counts, so no strengthening was needed there. Same for a_module_and_the_function_inside_it_are_separate_pairs (same-named module and function) — already asserts exact ranges. Verified-clean, no changes.

4. wordPattern anchoring — checked against VS Code's actual source, not assumed. Fetched src/vs/editor/contrib/linkedEditing/browser/linkedEditing.ts from microsoft/vscode. The wordPattern sent in LinkedEditingRanges is used only as: referenceValue.match(this._currentWordPattern), then match[0].length === referenceValue.length — a full-string validation against the already-extracted range content, not a per-line scan (that would be editor.wordPattern's job, used by getWordAtText for double-click/hover, which does need an unanchored global pattern — a different code path this feature does not touch). Against referenceValue.match(), an anchored ^...$ and an unanchored pattern give identical results here, because the check is on match[0].length equalling the whole string's length either way. Anchoring is correct, not a bug. This is worth recording so nobody "fixes" it later by stripping the anchors based on the general editor.wordPattern convention — that convention does not apply to this LSP field. Verified-clean.

5. Null conventions + totality. All of: unlabeled construct, cursor on the module keyword, cursor on the colon, cursor in the closer's whitespace, past EOF, empty file, unopened buffer, a buffer the lexer gives up on — all already covered (some newly, item 2 above) and all total. No panics anywhere in this round's ~15 new adversarial fixtures plus the corpus sweep below.

6. Corpus sweep. New test a_corpus_sweep_of_labeled_constructs_is_total_and_sane (line 801), gated on corpus/ being checked out (it is). 11 real files grepped from the corpus for endmodule : / end : shapes (common_cells, ibex, opentitan — file list in the test), every byte offset (0..=len, ~83,000 offsets total) run through linked_editing_ranges: no panics, every Some answer has exactly 2 ranges holding identical text that is a plain identifier (is_simple_identifier), and the two ranges never overlap. All green.

7. CLAUDE.md compliance.

  • No unwrap()/expect()/panic! outside #[cfg(test)] mod tests (module starts at linked.rs:282; grepped lines 1–280, none found). server.rs's pre-existing unwrap_or_default() calls near the dispatch arm are non-panicking and predate this feature.
  • pub fn linked_editing_ranges (line 52) carries a doc comment; so does the module (//! header) and every private item touched.
  • docs/features/linked-editing/README.md: all seven required sections present exactly once, in order (Goal, Assumptions, Handshakes, Status / TODO, Work log, QA log, Review).
  • TODO.md: the §9c item's original text ("Linked editing range — edit module m and its endmodule : m label together...") is byte-for-byte intact; only [ ] → [x] and an appended → delivered block changed.

Tests added (all in crates/lucisv_server/src/linked.rs, all passing, +8 over the dev's count, 1910 workspace tests total): a_block_named_both_ways_answers_only_the_blocks_own_pair, a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched, a_stray_second_end_label_after_the_block_already_closed_is_inert, broken_and_unclosed_labeled_constructs_never_panic, adjacent_closing_labels_never_bleed_into_each_other, ranges_cover_exactly_the_identifier_never_the_colon_or_comment, a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing, a_corpus_sweep_of_labeled_constructs_is_total_and_sane.

No production code changed — every finding above resolved to "verified correct," including the one (wordPattern anchoring) that looked like it could go either way until checked against VS Code's own source.

Review

2026-08-26 — lead

Reviewed the diff, the work log and the QA log; re-ran all gates myself, clean. The construct table in the work log — nine AST node kinds already carrying both name spans, discovered before a line was written — is the round doing its homework, and the decision to skip the pair matcher (a keyword matcher, not a label matcher) was correct. The judgment calls all land right: mismatched and absent labels answer null, escaped identifiers are refused with a test proving the refusal is the filter's choice and not a parse accident, and the prefix-label form gated on the block writing no label of its own handles the both-labels tolerant-parse shape exactly as it should.

Two QA results worth the record: the wordPattern anchoring question was resolved by reading VS Code's linked-editing source — the pattern is full-string validation in this code path, so the anchors are correct as shipped, and the QA log now says so precisely so nobody "fixes" it later against the wrong convention; and the range-precision test decodes every range back to bytes through the server's own converter, pinning that a link never includes the colon a user would otherwise type into. The 83k-offset corpus sweep of the identical-text/non-overlap invariants closes it out. program/property/sequence/covergroup stay filed as parser wants in Handshakes. Accepted as shipped.