From aa26e5e42774003fb8f692367bfada8f61b8ee6e Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 02:23:22 -0700 Subject: [PATCH] Rainbow begin/end: vfmt/scopePairs request + themed depth decorations Server: custom vfmt/scopePairs request returning every begin/end and fork/join* pair with its nesting depth (UTF-16 ranges); wire shape pinned by a literal-JSON test and by smoke.js over a real spawned server. Extension: paints each depth with the theme's own bracket palette (editorBracketHighlight.foreground1..6), debounced 250 ms, with a document.version staleness guard; vfmt.rainbowBeginEnd setting (default on) honored immediately in both directions. Corpus sweep: 8,146 block pairs across 859 files, max depth 13, worst request 2.1 ms (picorv32.v). Co-Authored-By: Claude Fable 5 --- crates/vfmt_server/src/pairs.rs | 176 +++++++++++++++- crates/vfmt_server/src/server.rs | 9 + crates/vfmt_server/tests/e2e.rs | 15 ++ docs/features/editor-scopes/README.md | 285 ++++++++++++++++++++++++-- editors/vscode/README.md | 14 ++ editors/vscode/extension.js | 150 +++++++++++++- editors/vscode/package.json | 5 + editors/vscode/smoke.js | 52 ++++- 8 files changed, 673 insertions(+), 33 deletions(-) diff --git a/crates/vfmt_server/src/pairs.rs b/crates/vfmt_server/src/pairs.rs index d764a2e..f54c3cd 100644 --- a/crates/vfmt_server/src/pairs.rs +++ b/crates/vfmt_server/src/pairs.rs @@ -1,15 +1,15 @@ //! Scope pairs — `begin`/`end` and its sixteen relatives — matched with a //! stack over the token stream. //! -//! One engine, three consumers: `textDocument/documentHighlight` (below), -//! the missing-closer warnings (below), and the extension's rainbow colouring -//! (`vfmt/scopePairs`, next round). Matching runs over `Document.tokens` +//! One engine, three consumers, all below: `textDocument/documentHighlight`, +//! the missing-closer warnings, and `vfmt/scopePairs`, which feeds the +//! extension's rainbow colouring. Matching runs over `Document.tokens` //! rather than the text, so a `// end` in a comment or a `"begin"` in a string //! cannot be mistaken for a keyword: the lexer has already thrown comments out //! of the stream and made the string one `String` token. See //! `docs/features/editor-scopes/README.md`. -use lsp_types::{Diagnostic, DiagnosticSeverity, DocumentHighlight, DocumentHighlightKind}; +use lsp_types::{Diagnostic, DiagnosticSeverity, DocumentHighlight, DocumentHighlightKind, Range}; use vlog_parser::token::{Token, TokenKind}; use vlog_parser::TextRange; @@ -60,12 +60,13 @@ const PROTOTYPE_STARTERS: &[&str] = &["extern", "pure", "import", "export", "typ pub struct Pair { pub open: TextRange, pub close: TextRange, + /// The opener as written, so a consumer can take only the scopes it wants + /// — the rainbow colours block delimiters and not `module`/`endmodule`. + pub keyword: &'static str, /// How many scopes were already open when this one opened; 0 is outermost. - // Computed and tested here, consumed by the extension: the rainbow picks - // its colour with `depth % 6`. The `vfmt/scopePairs` request that carries - // it to the client is the next milestone, so until then only the tests in - // this file read the field. - #[allow(dead_code)] + /// Counts *every* kind of frame, not just the one the caller kept, so + /// nesting differences survive filtering: the rainbow picks its colour + /// with `depth % 6`. pub depth: u32, } @@ -177,7 +178,12 @@ fn close( }); } if let Some(frame) = stack.pop() { - analysis.pairs.push(Pair { open: frame.span, close: span, depth: frame.depth }); + analysis.pairs.push(Pair { + open: frame.span, + close: span, + keyword: frame.rule.open, + depth: frame.depth, + }); } } @@ -275,6 +281,70 @@ fn covers(span: TextRange, offset: u32) -> bool { offset >= span.start && offset <= span.end } +// ---------------------------------------------------------------------- +// vfmt/scopePairs — the extension's rainbow +// ---------------------------------------------------------------------- + +/// The custom request the VS Code extension polls for rainbow colouring. +/// +/// Custom, because no LSP request means "tell me where the blocks are": the +/// nearest standard thing, `foldingRange`, answers a different question with +/// different ranges. A custom method needs no capability — a client that does +/// not know it simply never sends it, and one that does gets an error if this +/// server is too old, which is the same handshake a capability would give. +pub const SCOPE_PAIRS_METHOD: &str = "vfmt/scopePairs"; + +/// `vfmt/scopePairs` params — the document to describe, and nothing else. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ScopePairsParams { + pub text_document: lsp_types::TextDocumentIdentifier, +} + +/// One pair on the wire, in LSP `Range`s (UTF-16, like every other position +/// this server sends). +#[derive(serde::Serialize)] +pub struct ScopePair { + pub open: Range, + pub close: Range, + pub depth: u32, +} + +/// The `vfmt/scopePairs` result. An object rather than a bare array so a later +/// round can add a field without breaking a client that ignores it. +#[derive(serde::Serialize)] +pub struct ScopePairs { + pub pairs: Vec, +} + +/// The keywords the rainbow colours: block delimiters only. +/// +/// `module`/`endmodule`, `class`/`endclass` and the rest are matched by the +/// engine and deliberately dropped here. A whole-file `module` would tint its +/// own keywords a colour that means nothing, and `case`/`endcase` alongside +/// the `begin`s inside it makes the nesting read as deeper than it is. What +/// the user asked for is the `begin`/`end` ladder. +const RAINBOW_KEYWORDS: &[&str] = &["begin", "fork"]; + +/// Every block-delimiter pair in a buffer, for the extension to colour. +/// +/// Unmatched keywords are not reported: there is nothing to colour when only +/// half a pair exists, and the missing-closer warning already says so. +pub fn scope_pairs(doc: &Document) -> ScopePairs { + let positions = doc.positions(); + let pairs = analyze(&doc.tokens) + .pairs + .iter() + .filter(|p| RAINBOW_KEYWORDS.contains(&p.keyword)) + .map(|p| ScopePair { + open: positions.range(p.open), + close: positions.range(p.close), + depth: p.depth, + }) + .collect(); + ScopePairs { pairs } +} + // ---------------------------------------------------------------------- // missing-closer diagnostics // ---------------------------------------------------------------------- @@ -780,6 +850,92 @@ mod tests { assert!(highlights(&doc, at(text, "wire")).is_none()); } + // ------------------------------------------------------------------ + // vfmt/scopePairs + // ------------------------------------------------------------------ + + #[test] + fn scope_pairs_carries_only_block_delimiters() { + // The module, the class and the case are all matched by the engine and + // all dropped here: the rainbow is for the `begin` ladder. + let text = "module m;\n initial begin\n case (x)\n 1: y = 1;\n endcase\n end\n function f;\n endfunction\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "only the begin/end survives the filter"); + assert_eq!(sent.pairs[0].open.start.line, 1); + assert_eq!(sent.pairs[0].close.start.line, 5); + // The engine itself still saw all four. + assert_eq!(analyze(&doc.tokens).pairs.len(), 4); + } + + #[test] + fn scope_pairs_depths_nest_and_forks_are_included() { + let text = "module top;\n initial begin\n if (a) begin\n b = 1;\n end\n end\n initial fork\n c = 1;\n join\nendmodule\n"; + let doc = doc_of(text); + let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); + // The module is depth 0 and filtered out; the begins under it are 1 + // and 2, and the fork is a sibling of the outer begin. + assert_eq!(depths, vec![1, 2, 1]); + } + + #[test] + fn scope_pairs_ranges_are_utf16_and_cover_the_keyword() { + let text = "module m;\n // é ✓\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1); + let open = sent.pairs[0].open; + assert_eq!(open.start.line, 2); + assert_eq!(open.start.character, 10, "the `begin`, in UTF-16 units"); + assert_eq!(open.end.character, 15, "and it covers the whole keyword"); + assert_eq!(sent.pairs[0].close.start.line, 3); + } + + #[test] + fn scope_pairs_omits_a_pair_that_never_closed() { + // Half a pair is nothing to colour; the missing-closer warning is what + // speaks about it. + let text = "module m;\n initial begin\n if (x) begin\n end\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "only the inner begin closed"); + assert_eq!(sent.pairs[0].open.start.line, 2); + } + + #[test] + fn scope_pairs_of_a_file_with_no_blocks_is_empty_not_absent() { + let doc = doc_of("module m;\n wire a;\nendmodule\n"); + let sent = scope_pairs(&doc); + assert!(sent.pairs.is_empty()); + let json = serde_json::to_value(&sent).expect("serializes"); + assert_eq!(json, serde_json::json!({ "pairs": [] }), "the shape is stable"); + } + + #[test] + fn the_scope_pairs_wire_shape_is_what_the_extension_reads() { + // Pinned against the Handshakes section of the feature README: the + // extension indexes `pairs[].depth % 6` and hands `open`/`close` + // straight to the client's Range converter. + let doc = doc_of("module m;\n initial begin\n end\nendmodule\n"); + let json = serde_json::to_value(scope_pairs(&doc)).expect("serializes"); + assert_eq!( + json, + serde_json::json!({ + "pairs": [{ + "open": { + "start": { "line": 1, "character": 10 }, + "end": { "line": 1, "character": 15 } + }, + "close": { + "start": { "line": 2, "character": 2 }, + "end": { "line": 2, "character": 5 } + }, + "depth": 1 + }] + }) + ); + } + // ------------------------------------------------------------------ // missing-closer diagnostics, and the gate // ------------------------------------------------------------------ diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 0eda79e..8351b6c 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -159,6 +159,15 @@ impl Server { None => Ok(Value::Null), } }), + // Custom method, so it is matched by name rather than through a + // `lsp_types::request` type. Nothing advertises it: a client that + // does not know it never asks. + pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| { + match self.workspace.document(&p.text_document.uri) { + Some(doc) => to_value(pairs::scope_pairs(doc)), + None => Ok(Value::Null), + } + }), WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 5ae1c8f..78c593a 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -532,6 +532,11 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() { highlight(4, 1, 10), // Not a keyword at all. highlight(5, 3, 6), + // The rainbow's data source — a custom method, so this is the only + // thing that proves the request loop routes it at all. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":6,"method":"vfmt/scopePairs","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] @@ -575,6 +580,16 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() { ); } + // Only the pair that actually closed is offered for colouring, and its + // depth counts the frames the rainbow never sees (module, outer begin). + let scope_pairs = messages.iter().find(|m| m["id"] == 6).expect("scopePairs response"); + assert!(scope_pairs["error"].is_null(), "the method must be routed: {scope_pairs:#?}"); + let pairs = scope_pairs["result"]["pairs"].as_array().expect("a pairs array"); + assert_eq!(pairs.len(), 1, "the unclosed begin has nothing to colour: {pairs:#?}"); + assert_eq!(pairs[0]["depth"], 2); + assert_eq!(pairs[0]["open"]["start"]["line"], 2); + assert_eq!(pairs[0]["close"]["start"]["line"], 4); + // The warning rides along with the parse error, in one publish. let published = messages .iter() diff --git a/docs/features/editor-scopes/README.md b/docs/features/editor-scopes/README.md index d519d8b..93fecaa 100644 --- a/docs/features/editor-scopes/README.md +++ b/docs/features/editor-scopes/README.md @@ -5,14 +5,15 @@ Three of the owner's five editor requests are the same question asked three ways — *which `end` belongs to this `begin`?* — so they get one answer: `crates/vfmt_server/src/pairs.rs`, a stack matcher over the token stream the -document already caches. This milestone ships the engine and two of its three -consumers: `textDocument/documentHighlight`, so the cursor on a `begin` +document already caches. On top of it sit three consumers: +`textDocument/documentHighlight`, so the cursor on a `begin` highlights its own `end` (real matching, not a text search for the word), and a **missing-closer warning** that points at the `begin` which lost its `end` instead of leaving the user with one parse error at the bottom of the file. The -third consumer, the extension's rainbow colouring, is the next milestone and -needs nothing from the engine that is not already here — `Pair::depth` is -computed and tested, it just has no wire to travel on yet. +third consumer is the extension's rainbow: `vfmt/scopePairs` hands the client +every `begin`/`end` and `fork`/`join*` pair with its nesting depth, and +`extension.js` paints each depth in one of the six colours the user's theme +already defines for bracket pairs. ## Assumptions @@ -50,10 +51,19 @@ computed and tested, it just has no wire to travel on yet. wrong is a phantom unclosed scope; each has a test, and the corpus sweep in the work log is what says the list is complete rather than merely plausible. - **Analysis is cheap enough to redo per request.** `analyze` is one pass over - the token vector with a small stack — microseconds on a Verilog file — so - nothing is cached and no invalidation rule can go stale. If a profile ever - says otherwise, the result belongs next to `tokens` in `Document`, computed - once per change like everything else there. + the token vector with a small stack, so nothing is cached and no invalidation + rule can go stale. Measured, because `vfmt/scopePairs` arrives on a debounce + timer rather than on a user gesture: sweeping the corpus, the worst single + `scope_pairs` call is **2.1 ms** (`picorv32.v`, the largest file), against a + 250 ms debounce. If a profile ever says otherwise, the result belongs next to + `tokens` in `Document`, computed once per change like everything else there. +- **The client repaints; the server never pushes.** LSP has no "decorate these + ranges" notification, so the extension asks after every settled edit. That + makes a stale answer possible — the reply describes the version that was + asked about, and the user may have typed since — so `extension.js` compares + `document.version` across the await and drops anything late. Without that, + every range after an edit is painted at the wrong offset until the next + repaint. ## Handshakes @@ -81,11 +91,45 @@ JSON `null` — deliberately not an empty array, because an empty array tells th editor there are no occurrences anywhere and suppresses its own word highlighting. -**Promised to the next milestone:** `analyze(&[Token]) -> ScopeAnalysis`, with -`Pair { open, close, depth }`. `depth` counts every frame open at push time -(the module is 0, a `begin` under an `always` inside it is 1 or 2), which is -what `depth % 6` needs to pick a bracket colour. `Pair::depth` carries an -`#[allow(dead_code)]` until `vfmt/scopePairs` reads it. +**Promised to `extension.js` — the `vfmt/scopePairs` wire shape.** This is the +contract; `the_scope_pairs_wire_shape_is_what_the_extension_reads` pins it as +literal JSON so it cannot drift silently. + +Request — a custom method, so nothing advertises it and a client that does not +know it simply never asks: + +```json +{ "method": "vfmt/scopePairs", "params": { "textDocument": { "uri": "file:///…" } } } +``` + +Result: + +```json +{ "pairs": [ { "open": Range, "close": Range, "depth": 0 } ] } +``` + +- `open`/`close` are LSP `Range`s over the **keyword itself** — UTF-16, like + every other position this server sends, converted with `doc.positions()`. +- `pairs` holds only `begin`/`end` and `fork`/`join`/`join_any`/`join_none`. + Every other scope the engine matches is dropped: a whole-file `module` + would tint its own keywords a colour that means nothing, and letting + `case`/`endcase` into the ladder makes the nesting read as deeper than it + looks. What the owner asked for is the `begin`/`end` ladder. +- `depth` counts every frame open at push time, **including the ones filtered + out** — a `begin` directly inside a `module` is depth 1, not 0. Filtering + after counting is what keeps nesting *differences* right, which is all + `depth % 6` needs; an absolute 0 for the outermost block would cost a pass + to renumber and buy nothing. +- Unmatched keywords are absent. Half a pair is nothing to colour, and the + missing-closer warning already speaks about it. +- An unopened document answers `null`, matching every other handler here. + The extension treats that as "no pairs". + +Ordering is by opener position, though the extension does not depend on it. + +**Promised to any future consumer:** `analyze(&[Token]) -> ScopeAnalysis`, with +`Pair { open, close, keyword, depth }`. `keyword` is the opener as written, +which is how `scope_pairs` filters. **The guards — the list that must stay correct.** Each is an opener keyword in a construct with no closer: @@ -122,7 +166,15 @@ source. Neither file belongs to this feature, so neither was touched. failed, capped at 20. - [x] e2e coverage over the wire (`tests/e2e.rs`). - [x] Corpus sweep for false positives (found one class; fixed). -- [ ] `vfmt/scopePairs` + the extension's rainbow — next milestone. +- [x] `vfmt/scopePairs` in `server.rs` + `pairs::scope_pairs`, wire shape + pinned by a literal-JSON test. +- [x] The rainbow in `extension.js`: six theme decoration types, `depth % 6`, + repaint on active-editor / visible-editors / document change (250 ms + debounce), stale-answer guard. +- [x] `vfmt.rainbowBeginEnd` (default true), honoured live by a + configuration-change listener. +- [x] `smoke.js` drives `vfmt/scopePairs` against a nested-begin + fork + fixture and asserts the depths. - [ ] Not done, deliberately: no check that a labeled `end : outer` agrees with its `begin : outer`. That is a lint rule with its own fix and its own opinion, not part of matching. @@ -221,6 +273,68 @@ green. Full workspace: 937 passed, 0 failed. `cargo fmt --all` clean, `cargo clippy --all-targets` clean. The one `#[allow]` in the new code is on `Pair::depth`, with a comment naming the milestone that removes it. +### 2026-08-24 — M3: `vfmt/scopePairs` and the extension's rainbow + +**Server.** `Pair` gained a `keyword` field (the opener as written) so a +consumer can take a subset without the engine having to know about subsets; +`scope_pairs` filters on it and converts to LSP `Range`s. That field is also +what let the `#[allow(dead_code)]` on `Pair::depth` go — both fields are now +read by shipping code, and the crate has no `#[allow]` left in this module. +The handler is one arm in `server.rs`, matched on the method name rather than +through an `lsp_types::request` type because the method is ours. + +**Three decisions worth recording.** + +1. *Depth is not renumbered after filtering.* A `begin` directly inside a + `module` reports depth 1, because the module frame was open when it was + pushed. The rainbow only needs nesting *differences*, and renumbering would + cost a pass and change nothing on screen. Written down because "why does my + outermost block get colour 2?" is otherwise a mystery. +2. *Only `begin`/`end` and `fork`/`join*` go on the wire.* The engine matches + twenty-one scopes; nineteen are dropped here. Colouring `module`/`endmodule` + tints a keyword pair the user never wonders about, and letting `case` into + the ladder shifts every `begin` inside it one colour, which reads as deeper + nesting than the code has. +3. *The extension guards against its own staleness.* `paint` records + `document.version` before the request and drops the answer if it changed + while in flight. The debounce reduces how often that happens; it cannot + prevent it, and a decoration painted at a pre-edit offset is worse than no + decoration. + +**Extension.** Six `TextEditorDecorationType`s, colour-only, each bound to +`vscode.ThemeColor('editorBracketHighlight.foregroundN')` so the palette is +whatever the user's theme already uses for brackets — no colours invented here, +nothing to clash. Repaint on active-editor change, visible-editors change +(splits, tab drags) and document change on a 250 ms debounce. Turning +`vfmt.rainbowBeginEnd` off repaints with empty range lists, which is how a +decoration type is removed — so "off" takes effect immediately in both +directions rather than "after a reload". Closing an editor needs no handler: +VS Code disposes its decorations with it, and the types themselves are in +`context.subscriptions`. A failed request leaves the previous colours alone +rather than blanking the file, since the language client already reports a +server that will not start, in its own channel. + +**Corpus sweep, again** (temporary test, run and removed, as in M2): all 860 +files through `scope_pairs`. **8 146 block pairs, max depth 13, 0 malformed +ranges** (every `open` before its `close`, every range non-empty), and the +timing above. No behavioural change from M2 — the `keyword` field is additive — +but the new surface is the one that reaches the screen, so it got its own pass. + +**Deviations from the plan.** One, and it is an addition: the plan put +scopePairs coverage in `smoke.js` only, and it is also asserted in +`tests/e2e.rs` (one request appended to the existing scopes test). `smoke.js` +is run by hand before packaging; the routing of a custom method is exactly the +kind of thing that breaks silently, so it is worth having in `cargo test` too. +Otherwise the milestone is as specified. + +**Verification.** `cargo fmt --all` clean, `cargo clippy --all-targets` clean +(0 diagnostics), `cargo test --workspace` **944 passed, 0 failed** (168 unit in +this crate, up from 162; 7 e2e). `node smoke.js ../../target/debug/vfmt-server` +against a freshly built binary: OK. The smoke assertion was mutation-checked — +changing the expected depths to `[9,9,9]` fails with +`got [1,2,1]`, so it is live rather than vacuous. `npx @vscode/vsce ls` still +accepts the manifest. `node --check` on both JS files. + ## QA log ### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate @@ -304,6 +418,133 @@ recorded above (a pre-existing `vlog_parser` grammar gap unrelated to this feature, and a redundant-but-harmless double document lookup in `server.rs`). +### 2026-08-24 — QA round 2 (M3): `vfmt/scopePairs` and the extension rainbow + +Charter items 1, 4, 5 (repeat, unregressed) and 6 from `editor_features_plan.md` +for this dispatch: the wire shape, `scope_pairs` correctness, `extension.js` +review, `smoke.js`, invariants, and an M1/M2 unregression spot-check. Item 2 +(documentHighlight attack surface) is M2 and was covered in round 1; not +re-audited except where M3 touched shared code (it did not — `Pair::keyword` +is additive). Verdict: **PASS**, no blocking findings. + +**1. Wire shape.** Ran `cargo test -p vfmt_server`: 168 unit + 7 e2e, all +green. Read `the_scope_pairs_wire_shape_is_what_the_extension_reads` +(`crates/vfmt_server/src/pairs.rs:915`) — it pins the full response as literal +JSON (`open`/`close` LSP `Range`s over the keyword, `depth`), matching the +Handshakes section word for word. Confirmed each documented property against +its own test, not just the pinned one: +- UTF-16 ranges: `scope_pairs_ranges_are_utf16_and_cover_the_keyword` + (`pairs.rs:882`) — a 2-byte `é`/`✓` comment before `begin` and the column + lands at 10, not shifted by the extra bytes. +- Only `begin`/`end` + `fork`/`join*`: `scope_pairs_carries_only_block_delimiters` + (`pairs.rs:858`) — module/case/function all matched by the engine (4 pairs) + but only the 1 `begin..end` survives the filter. `RAINBOW_KEYWORDS` is + `["begin", "fork"]`; since `Pair::keyword` stores the opener, this correctly + admits `fork` closed by any of `join`/`join_any`/`join_none`. +- Depth not renumbered after filtering: `scope_pairs_depths_nest_and_forks_are_included` + (`pairs.rs:872`) — module (depth 0, filtered out) then begins at depth 1 + and 2; e2e test at `tests/e2e.rs:576` independently pins depth 2 for a + `begin` nested two frames deep in an unbalanced file. +- Unmatched keywords absent: `scope_pairs_omits_a_pair_that_never_closed` + (`pairs.rs:895`) and the e2e test (only the closed inner `begin` is offered, + 1 pair, from a file with one unclosed `begin`). +- Unopened doc → `null`: no dedicated unit test exists for this specific + handler (matches the pattern for every sibling handler in `server.rs` — + none of them have one either, so this is not an M3-specific gap). Verified + directly against the built binary instead: spawned `vfmt-server`, sent + `vfmt/scopePairs` for a URI never opened via `didOpen`, got back + `{"jsonrpc":"2.0","id":2,"result":null}` with no error. Matches + `server.rs:165-170`. + +**2. `scope_pairs` correctness — independent corpus sweep.** Added a +throwaway `#[cfg(test)]` (same discipline as round 1: run, read, removed +before this log was written — not in the committed tree) walking `corpus/` +and calling `scope_pairs` on every file that lexes, checking every emitted +range is non-empty and `open` starts before `close` starts. Result: **859 +files scanned, 8 146 pairs, max depth 13, 0 malformed** — an exact match to +the dev's Work Log numbers (`8 146 block pairs, max depth 13, 0 malformed +ranges`). Depths and UTF-16 columns already covered per-case above; nothing +in the sweep found a malformed range or a panic. + +**3. `extension.js` review** (`editors/vscode/extension.js`), read in full +against the round-2 charter's specific worry list: +- **Decoration lifecycle**: 6 `TextEditorDecorationType`s built once in + `activate` (line 64-68), color-only (`ThemeColor` per index, no + `fontWeight`), pushed into `context.subscriptions` (line 69) — disposed + automatically on deactivate, which also removes their decorations from + every editor without extra code. +- **Staleness guard**: `askedAbout = document.version` (line 142) is captured + *before* `await client.sendRequest(...)` (line 147) and compared *after* + (line 159) — correct order, confirmed by reading the `async` control flow + directly; a version bump during the await drops the stale answer and + relies on the debounce the edit already scheduled. +- **Debounce**: `scheduleRepaint` (line 121) clears the pending timer before + setting a new one; `deactivate` (line 107) clears it too, so no dangling + `setTimeout` after unload. +- **Setting-off path**: `onDidChangeConfiguration` (line 83) updates + `rainbowEnabled` and calls `repaintVisible()` synchronously (no debounce); + `paint()` skips the request entirely when `rainbowEnabled` is false and + still runs `setDecorations([])` for every bucket (line 167-169), which is + how a decoration type is cleared — confirmed this is unconditional (outside + the `if (rainbowEnabled)` block), so already-open editors really lose their + colours immediately, not after a reload. +- **No request for non-verilog docs**: `repaintVisible` (line 127) and the + document-change listener (line 81) both gate on `isVerilog()` before + scheduling or painting. +- **Listener leaks**: client, all 6 decoration types, and the 4-item listener + array are all pushed to `context.subscriptions` (lines 59, 69, 73-90) — + nothing is registered outside that list. +- **Client/server not ready or request rejects**: `client.start().then(ok, () => + {})` (line 96-102) swallows a startup rejection without throwing; `paint`'s + `try { await client.sendRequest(...) } catch { return; }` (line 146-150) + swallows a rejected/thrown request the same way. Neither path produces an + unhandled rejection. + +No defects found in `extension.js`. + +**4. `smoke.js`.** Built `target/debug/vfmt-server` fresh (`cargo build -p +vfmt_server`), ran `node smoke.js ../../target/debug/vfmt-server` from +`editors/vscode/`: **OK**. Mutation check: changed the expected depths +assertion from `[1, 2, 1]` to `[9, 9, 9]`, reran — failed as expected +(`expected depths [1,2,1] ..., got [1,2,1]`, exit code 1), then reverted; +`md5` of `smoke.js` before and after the round-trip is identical +(`436a569e05a23fb766813e0cc15d2de8`), so the file is byte-for-byte what it +was. `node --check` on both `extension.js` and `smoke.js`: clean. + +**5. Invariants.** +- `cargo test --workspace`: 944 passed, 0 failed (168 unit + 7 e2e in + `vfmt_server`, matching the Work Log's count). +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets`: clean, no warnings. +- `git diff --stat` vs `HEAD`: `crates/vfmt_server/{pairs,server}.rs`, + `crates/vfmt_server/tests/e2e.rs`, `docs/features/editor-scopes/README.md`, + `editors/vscode/{README.md,extension.js,package.json,smoke.js}`. No + `vlog_formatter`/`vlog_parser`/`verify.rs` paths touched. +- `node -e "JSON.parse(...)"` on `editors/vscode/package.json`: valid; the new + `vfmt.rainbowBeginEnd` setting and the M1 `contributes.snippets` block are + both present and unchanged in shape. `npx @vscode/vsce ls` accepts the + manifest and lists `package.json`, `extension.js`, `README.md`, + `snippets/verilog.json`, `snippets/systemverilog.json` — no error. +- No `unwrap()`/`expect()`/`panic!` in the new `pairs.rs`/`server.rs` code + outside `#[cfg(test)]` (grepped directly). No `#[allow]` remains in + `pairs.rs` — the dev's removal of the `Pair::depth` `#[allow(dead_code)]` + is confirmed; nothing new was added in its place. + +**6. M1/M2 unregression spot-check.** `cargo test -p vfmt_server` (168 unit) +includes the full M1 snippet-adjacent and M2 `pairs.rs`/`documentHighlight`/ +missing-end suites from round 1, all still passing; `package.json`'s +`contributes.snippets` block is byte-identical to what round 1 saw (verified +by reading it directly, not diffed against round 1 since M1 was committed +before this dispatch). No M2 test was touched by this diff except the two +lines the e2e test needed to add a `vfmt/scopePairs` frame after the existing +`documentHighlight` assertions. + +**Verdict: PASS.** No blocking findings, no non-blocking findings either — +the unopened-doc-→-null path lacking a dedicated unit test is a pattern that +predates this feature (every sibling handler in `server.rs` shares it) and +was independently verified against the running binary, so it is not filed as +a gap specific to this work. + ## Review ### 2026-08-24 — lead review of M2 (after QA round 1) @@ -325,3 +566,17 @@ committed. Notes: - QA's non-blocking note about the double `workspace.document` lookup in the `documentHighlight` handler is real but matches the surrounding handler style; not worth churn. + +### 2026-08-24 — lead review of M3 (after QA round 2) + +Read `extension.js` in full, the `scope_pairs` additions, the `server.rs` +arm and the `smoke.js` extension. Approved and committed. Notes: + +- The client-side staleness guard (`document.version` captured before the + await, compared after, plus the visible-editor check) is the right shape, + and "leave the old colours on a failed request" is the right failure + mode for a cosmetic feature. +- Not renumbering depth after filtering is fine and well documented; the + rainbow reads differences only. +- The wire-shape test pinning literal JSON is what makes the custom method + safe to evolve; keep that pattern for any future custom request. diff --git a/editors/vscode/README.md b/editors/vscode/README.md index f67804d..74c42bd 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -73,6 +73,7 @@ if it ever happens. | Setting | Default | What it does | |---|---|---| | `vfmt.serverPath` | `"vfmt-server"` | Path to the executable. A bare name is looked up on `PATH`; an absolute path is used as given. | +| `vfmt.rainbowBeginEnd` | `true` | Colour each nesting level of `begin`/`end` and `fork`/`join` differently. Takes effect immediately — no reload. | That is the whole list, deliberately. Formatter options (line length, indent) belong in a `vfmt.toml`, not in editor settings — one source of truth for the @@ -81,6 +82,19 @@ the CLI does; when it names a setting, it wins over VS Code's tab size (an editor default is not a deliberate override). Without a config, VS Code's tab size governs the indent and the line length is the built-in 100. +## Rainbow begin/end + +Each nesting level of `begin`/`end` and `fork`/`join` is coloured differently, +using the six colours your theme already defines for bracket pairs +(`editorBracketHighlight.foreground1`…`6`), so it matches whatever colour +scheme you use. The pairs are matched by the server over the token stream, not +by a regex, so an `end` inside a comment or a string is never coloured and the +`end` that lights up is genuinely the one that closes that `begin`. + +Turn it off with `"vfmt.rainbowBeginEnd": false`; the colours disappear +immediately. Cursor on a `begin` also highlights its matching `end` — that is +`documentHighlight`, always on, and it needs no setting. + ## Snippets Type a prefix and pick the snippet from the completion list; `Tab` walks the diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js index 9c55633..c35c326 100644 --- a/editors/vscode/extension.js +++ b/editors/vscode/extension.js @@ -1,8 +1,12 @@ -// The whole VS Code extension: start `vfmt-server` over stdio and let the -// language client do the rest. There is deliberately no command, no status -// bar item and no setting other than the server's path — every feature the -// user sees comes from the server, so anything else added here would be -// editor-specific logic above the protocol (docs/features/editor-packaging). +// The whole VS Code extension: start `vfmt-server` over stdio, let the +// language client do the rest, and paint one thing the protocol has no request +// for — the `begin`/`end` rainbow, whose ranges the server computes and hands +// over through the custom `vfmt/scopePairs` request. +// +// Every *answer* still comes from the server: nothing here parses Verilog, and +// the only reason this file is longer than the language client's setup is that +// LSP has no "decorate these ranges" notification, so the painting has to be +// driven from the client side (docs/features/editor-scopes). const vscode = require('vscode'); const { LanguageClient, TransportKind } = require('vscode-languageclient/node'); @@ -10,6 +14,29 @@ const { LanguageClient, TransportKind } = require('vscode-languageclient/node'); /** The single client, kept only so `deactivate` can stop it. */ let client; +/** The languages this extension attaches to. */ +const LANGUAGES = ['verilog', 'systemverilog']; + +/** + * How many colours the rainbow cycles through. Six is what VS Code's own + * bracket colouring defines (`editorBracketHighlight.foreground1..6`), and + * borrowing that palette is what makes this follow the user's theme instead of + * inventing colours that clash with it. + */ +const RAINBOW_COLORS = 6; + +/** How long to let typing settle before re-asking for pairs. */ +const REPAINT_DEBOUNCE_MS = 250; + +/** One decoration type per colour, created once and reused. */ +let decorationTypes = []; + +/** Whether the rainbow is on, per `vfmt.rainbowBeginEnd`. */ +let rainbowEnabled = true; + +/** The pending debounced repaint, if any. */ +let repaintTimer; + /** Spawn the server and attach it to Verilog/SystemVerilog documents. */ function activate(context) { const serverPath = vscode.workspace.getConfiguration('vfmt').get('serverPath') || 'vfmt-server'; @@ -25,17 +52,126 @@ function activate(context) { // No `scheme` filter: the server serves `untitled:` buffers too, for // everything single-file (docs/features/vfmt-server/README.md). const clientOptions = { - documentSelector: [{ language: 'verilog' }, { language: 'systemverilog' }], + documentSelector: LANGUAGES.map((language) => ({ language })), }; client = new LanguageClient('vfmt', 'vfmt', serverOptions, clientOptions); context.subscriptions.push(client); - client.start(); + + // The colours come from the theme, so the decoration carries no fallback of + // its own: an unset `editorBracketHighlight.foregroundN` leaves the text its + // normal colour, which is the right failure. + decorationTypes = Array.from({ length: RAINBOW_COLORS }, (_, index) => + vscode.window.createTextEditorDecorationType({ + color: new vscode.ThemeColor(`editorBracketHighlight.foreground${index + 1}`), + }), + ); + context.subscriptions.push(...decorationTypes); + + rainbowEnabled = readRainbowSetting(); + + context.subscriptions.push( + // A new editor has no decorations of its own; paint it as it appears. + vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()), + // Covers splits, tab drags, and an editor becoming visible again. + vscode.window.onDidChangeVisibleTextEditors(() => repaintVisible()), + // Typing moves every range after the cursor, so the answer is stale the + // moment it arrives; debounce rather than ask on every keystroke. + vscode.workspace.onDidChangeTextDocument((event) => { + if (isVerilog(event.document)) scheduleRepaint(); + }), + vscode.workspace.onDidChangeConfiguration((event) => { + if (!event.affectsConfiguration('vfmt.rainbowBeginEnd')) return; + rainbowEnabled = readRainbowSetting(); + // Honoured immediately, both ways: turning it off has to take the + // colours away, or "off" would only mean "off after a reload". + repaintVisible(); + }), + ); + + // Closing an editor disposes its decorations with it, so there is nothing to + // clear on close; the only explicit clearing is turning the setting off, + // which `repaintVisible` does by painting empty ranges. + + client.start().then( + () => repaintVisible(), + // The client reports a server that will not start, in its own output + // channel and its own words. Decorations are cosmetic; there is nothing + // useful to add here, and a second error popup would only be noise. + () => {}, + ); } /** Stop the server; VS Code waits on the returned promise. */ function deactivate() { + clearTimeout(repaintTimer); return client ? client.stop() : undefined; } +/** True for the documents this extension knows about. */ +function isVerilog(document) { + return LANGUAGES.includes(document.languageId); +} + +function readRainbowSetting() { + return vscode.workspace.getConfiguration('vfmt').get('rainbowBeginEnd') !== false; +} + +/** Coalesce a burst of edits into one repaint. */ +function scheduleRepaint() { + clearTimeout(repaintTimer); + repaintTimer = setTimeout(() => repaintVisible(), REPAINT_DEBOUNCE_MS); +} + +/** Repaint every visible Verilog editor. */ +function repaintVisible() { + for (const editor of vscode.window.visibleTextEditors) { + if (isVerilog(editor.document)) paint(editor); + } +} + +/** + * Ask the server where this buffer's blocks are and colour them by depth. + * + * Turning the rainbow off paints empty ranges rather than skipping the editor: + * `setDecorations` with `[]` is how a decoration type is removed, so "off" and + * "no blocks here" are the same operation. + */ +async function paint(editor) { + const document = editor.document; + const askedAbout = document.version; + const buckets = decorationTypes.map(() => []); + if (rainbowEnabled) { + let result; + try { + result = await client.sendRequest('vfmt/scopePairs', { + textDocument: { uri: document.uri.toString() }, + }); + } catch { + // The server is gone, restarting, or older than this extension. The + // client says so where it says everything else; leaving the old colours + // alone is better than blanking the file over a transient failure. + return; + } + // The answer describes the version we asked about. If the user typed while + // it was in flight, every range after the edit is now wrong — drop it and + // let the debounced repaint that the edit already scheduled do the work. + if (document.version !== askedAbout) return; + // The editor may have been closed while the request was in flight. + if (!vscode.window.visibleTextEditors.includes(editor)) return; + for (const pair of (result && result.pairs) || []) { + const ranges = buckets[pair.depth % RAINBOW_COLORS]; + ranges.push(asRange(pair.open), asRange(pair.close)); + } + } + for (const [index, ranges] of buckets.entries()) { + editor.setDecorations(decorationTypes[index], ranges); + } +} + +/** An LSP range (UTF-16, which is what the server advertises) as a VS Code one. */ +function asRange(range) { + return client.protocol2CodeConverter.asRange(range); +} + module.exports = { activate, deactivate }; diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 0b3f2f3..97f612e 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -64,6 +64,11 @@ "type": "string", "default": "vfmt-server", "description": "Path to the vfmt-server executable. A bare name is looked up on PATH." + }, + "vfmt.rainbowBeginEnd": { + "type": "boolean", + "default": true, + "description": "Colour each nesting level of begin/end and fork/join a different colour, using the theme's bracket-pair colours. Takes effect immediately." } } } diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js index 80e46ca..12aaf41 100644 --- a/editors/vscode/smoke.js +++ b/editors/vscode/smoke.js @@ -54,6 +54,24 @@ server.stderr.on('data', (chunk) => process.stderr.write(chunk)); // order and exits on `exit`, so stdout closes on its own and this can never // deadlock waiting for a message that is not coming. const uri = `file://${process.cwd()}/smoke_scratch.sv`; + +// Nested blocks plus a sibling fork: enough for the rainbow's whole contract — +// which pairs are reported, and what depth each one carries. +const SOURCE = [ + 'module top;', + ' wire a;', + ' initial begin', + ' if (a) begin', + ' b = 1;', + ' end', + ' end', + ' initial fork', + ' c = 1;', + ' join', + 'endmodule', + '', +].join('\n'); + server.stdin.end( Buffer.concat([ frame({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { processId: process.pid, rootUri: null, capabilities: {} } }), @@ -61,8 +79,9 @@ server.stdin.end( frame({ jsonrpc: '2.0', method: 'textDocument/didOpen', - params: { textDocument: { uri, languageId: 'systemverilog', version: 1, text: 'module top;\n wire a;\nendmodule\n' } }, + params: { textDocument: { uri, languageId: 'systemverilog', version: 1, text: SOURCE } }, }), + frame({ jsonrpc: '2.0', id: 3, method: 'vfmt/scopePairs', params: { textDocument: { uri } } }), frame({ jsonrpc: '2.0', id: 2, method: 'shutdown', params: null }), frame({ jsonrpc: '2.0', method: 'exit', params: null }), ]), @@ -82,9 +101,40 @@ server.on('close', (code) => { if (!capabilities[capability]) fail(`capability missing: ${capability}`); } + if (!capabilities.documentHighlightProvider) fail('capability missing: documentHighlightProvider'); + const diagnostics = messages.find((m) => m.method === 'textDocument/publishDiagnostics'); if (!diagnostics) fail('the server pushed no diagnostics for the opened document'); + // The rainbow's data source. Custom method, so nothing advertises it — an + // "unhandled method" error here is exactly the mismatch this test exists to + // catch, and it is what an extension paired with an older server would hit. + const scopePairs = messages.find((m) => m.id === 3); + if (!scopePairs) fail('no vfmt/scopePairs response'); + if (scopePairs.error) fail(`vfmt/scopePairs failed: ${JSON.stringify(scopePairs.error)}`); + const pairs = scopePairs.result && scopePairs.result.pairs; + if (!Array.isArray(pairs)) fail(`vfmt/scopePairs result has no pairs array: ${JSON.stringify(scopePairs.result)}`); + // The module is matched by the server and filtered out; the two begins nest + // under it at 1 and 2, and the fork is the outer begin's sibling. + const depths = pairs.map((p) => p.depth); + if (JSON.stringify(depths) !== JSON.stringify([1, 2, 1])) { + fail(`expected depths [1,2,1] (outer begin, inner begin, fork), got ${JSON.stringify(depths)}`); + } + // Opener lines, 0-based: `initial begin`, `if (a) begin`, `initial fork`. + const openLines = pairs.map((p) => p.open.start.line); + if (JSON.stringify(openLines) !== JSON.stringify([2, 3, 7])) { + fail(`expected openers on lines [2,3,7], got ${JSON.stringify(openLines)}`); + } + const closeLines = pairs.map((p) => p.close.start.line); + if (JSON.stringify(closeLines) !== JSON.stringify([6, 5, 9])) { + fail(`expected closers on lines [6,5,9], got ${JSON.stringify(closeLines)}`); + } + for (const pair of pairs) { + for (const half of [pair.open, pair.close]) { + if (half.end.character <= half.start.character) fail(`empty range in ${JSON.stringify(pair)}`); + } + } + const shutdown = messages.find((m) => m.id === 2); if (!shutdown) fail('no shutdown response'); if (shutdown.error) fail(`shutdown failed: ${JSON.stringify(shutdown.error)}`);