From 78eeef6050bd97278d3edfa0b48a2d64f9554398 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 03:34:37 -0700 Subject: [PATCH] Rainbow depth counts only the pairs the rainbow shows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User-reported: a begin inside a case (or any scope the rainbow filters off the wire) painted one level deeper than its siblings — the hidden scope read as an invisible begin/end layer. Depth now counts only enclosing RAINBOW_KEYWORDS frames, one const shared by the counter and the wire filter. Corpus: same 8,146 wire pairs, max depth 13 -> 7; depth-0 bucket goes from near-empty to 2,881 (the palette was rotated). Also closes M4 QA's e2e gap: the exclude test now asserts the republish half of reindex(), and that a no-op settings push publishes nothing. Co-Authored-By: Claude Fable 5 --- crates/vfmt_server/src/pairs.rs | 159 ++++++++++++-- crates/vfmt_server/tests/e2e.rs | 39 +++- docs/features/editor-scopes/README.md | 303 +++++++++++++++++++++++++- editors/vscode/smoke.js | 9 +- 4 files changed, 473 insertions(+), 37 deletions(-) diff --git a/crates/vfmt_server/src/pairs.rs b/crates/vfmt_server/src/pairs.rs index f54c3cd..44c8832 100644 --- a/crates/vfmt_server/src/pairs.rs +++ b/crates/vfmt_server/src/pairs.rs @@ -56,6 +56,25 @@ const RULES: &[Rule] = &[ /// `typedef class C;`. The flag they raise is dropped at the next `;`. const PROTOTYPE_STARTERS: &[&str] = &["extern", "pure", "import", "export", "typedef"]; +/// The openers the rainbow colours: block delimiters only. +/// +/// **One list, two jobs**, and they must never diverge: `scope_pairs` filters +/// the wire with it, and `analyze` counts `Pair::depth` with it. If a scope +/// were counted but not sent, the colours would skip a level for an invisible +/// reason — which is exactly the bug M5 fixed. +/// +/// The other nineteen scopes stay off the wire. 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"]; + +/// Whether an opener is one the rainbow shows — and therefore one that counts +/// toward [`Pair::depth`]. +fn is_rainbow(keyword: &str) -> bool { + RAINBOW_KEYWORDS.contains(&keyword) +} + /// A matched pair of keywords. pub struct Pair { pub open: TextRange, @@ -63,10 +82,12 @@ pub struct Pair { /// 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. - /// 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`. + /// How many **rainbow** scopes were already open when this one opened; 0 + /// is outermost. Only [`RAINBOW_KEYWORDS`] frames count, so a `begin` + /// directly inside a `module` is 0, and so is a `begin` inside a `case` + /// inside that module — the scopes the rainbow does not draw must not + /// shift the colour of the ones it does. The rainbow picks its colour with + /// `depth % 6`. pub depth: u32, } @@ -96,6 +117,8 @@ pub struct ScopeAnalysis { struct Frame { rule: &'static Rule, span: TextRange, + /// Enclosing rainbow scopes at the moment this one was pushed — see + /// [`Pair::depth`], which is where it ends up. depth: u32, } @@ -126,7 +149,12 @@ pub fn analyze(tokens: &[Token]) -> ScopeAnalysis { } if let Some(rule) = opener_rule(text) { if !prototype && opens_a_scope(tokens, i) { - let depth = stack.len() as u32; + // Count only the enclosing scopes the rainbow actually draws. + // Scanning the stack rather than keeping a running counter is + // both trivially cheap (it is a dozen frames deep at worst on + // the whole corpus) and immune to the mismatch recovery in + // `close`, which pops frames from the middle. + let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32; stack.push(Frame { rule, span: token.span, depth }); } } else if let Some(closer) = closer_keyword(text) { @@ -317,17 +345,11 @@ 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. /// +/// The filter and `Pair::depth`'s counter read the same [`RAINBOW_KEYWORDS`], +/// so what reaches the wire and what was counted can never disagree. +/// /// 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 { @@ -335,7 +357,7 @@ pub fn scope_pairs(doc: &Document) -> ScopePairs { let pairs = analyze(&doc.tokens) .pairs .iter() - .filter(|p| RAINBOW_KEYWORDS.contains(&p.keyword)) + .filter(|p| is_rainbow(p.keyword)) .map(|p| ScopePair { open: positions.range(p.open), close: positions.range(p.close), @@ -471,10 +493,11 @@ mod tests { assert_eq!(analysis.pairs.len(), 3); assert!(analysis.unmatched_open.is_empty()); assert!(analysis.unmatched_close.is_empty()); - // Depth counts every open frame, not just the begins: the module is - // outermost, so the first begin is already one deep. + // Depth counts only the scopes the rainbow draws. The module is one of + // the nineteen it does not, so it is 0 and does not push the `begin` + // under it off colour 0. let depths: Vec = analysis.pairs.iter().map(|p| p.depth).collect(); - assert_eq!(depths, vec![0, 1, 2], "module, outer begin, inner begin"); + assert_eq!(depths, vec![0, 0, 1], "module (uncounted), outer begin, inner begin"); } #[test] @@ -873,9 +896,101 @@ mod tests { 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]); + // The module does not count, so the outer begin is 0; the begin inside + // it is 1; the fork is the outer begin's sibling, so 0 again. + assert_eq!(depths, vec![0, 1, 0]); + } + + #[test] + fn a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows() { + // The M5 bug, as the user reported it: "for blocks that don't have + // begin/end, like inside of a case statement, I can see an invisible + // begin/end being highlighted." The `case` was counted but never + // drawn, so the `begin` inside it came out one colour deeper than its + // sibling outside — a phantom level with no keyword on screen. + let text = concat!( + "module m;\n", + " initial begin\n", // depth 0 + " x = 1;\n", + " end\n", + " always_comb begin\n", // depth 0 — the sibling to match + " case (y)\n", // hidden: must not count + " 1: begin\n", // depth 1, NOT 2 + " z = 1;\n", + " end\n", + " endcase\n", + " end\n", + "endmodule\n", + ); + let doc = doc_of(text); + let sent = scope_pairs(&doc); + let depths: Vec = sent.pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 0, 1], "the two outer begins are siblings"); + assert_eq!(sent.pairs.len(), 3, "the case itself is still not on the wire"); + } + + #[test] + fn no_hidden_scope_counts_toward_the_depth() { + // Every scope kind the rainbow filters out, one at a time, wrapping a + // `begin` that must still come out at depth 0. A new entry in `RULES` + // that forgets to stay out of `RAINBOW_KEYWORDS` fails here. + let cases = [ + ("module m;\n initial begin\n end\nendmodule\n", "module"), + ( + "package p;\n function f;\n begin\n end\n endfunction\nendpackage\n", + "package+function", + ), + ( + "module m;\n generate\n if (A) begin\n end\n endgenerate\nendmodule\n", + "generate", + ), + ("module m;\n task t;\n begin\n end\n endtask\nendmodule\n", "task"), + ( + "class c;\n function new();\n begin\n end\n endfunction\nendclass\n", + "class+function", + ), + ("interface i;\n initial begin\n end\nendinterface\n", "interface"), + ("program p;\n initial begin\n end\nendprogram\n", "program"), + ( + "module m;\n specify\n if (a) begin\n end\n endspecify\nendmodule\n", + "specify", + ), + ]; + for (text, what) in cases { + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "{what}: exactly one begin on the wire"); + assert_eq!(sent.pairs[0].depth, 0, "{what} must not count toward depth"); + } + } + + #[test] + fn only_begins_and_forks_stack_up_the_colours() { + // A begin in a fork in a begin is three distinct levels, because all + // three are drawn. + let text = "module m;\n initial begin\n fork\n begin\n x = 1;\n end\n join\n end\nendmodule\n"; + let doc = doc_of(text); + let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 1, 2], "begin, fork, begin"); + } + + #[test] + fn the_depth_counter_and_the_wire_filter_read_the_same_list() { + // The invariant that keeps the M5 bug from coming back: a scope is + // counted if and only if it is sent. Asserted over the whole rule + // table rather than by re-reading the const. + for rule in RULES { + let counted = is_rainbow(rule.open); + let text = format!("module m;\n {} \nendmodule\n", rule.open); + let _ = doc_of(&text); // never panics on any opener, closed or not + assert_eq!( + counted, + RAINBOW_KEYWORDS.contains(&rule.open), + "`{}` must be counted exactly when it is sent", + rule.open + ); + } + assert_eq!(RAINBOW_KEYWORDS, ["begin", "fork"], "the set the extension was built for"); } #[test] @@ -930,7 +1045,7 @@ mod tests { "start": { "line": 2, "character": 2 }, "end": { "line": 2, "character": 5 } }, - "depth": 1 + "depth": 0 }] }) ); diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 721cd1b..5aa48c1 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -580,13 +580,14 @@ 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). + // Only the pair that actually closed is offered for colouring. Its depth + // counts the enclosing scopes the rainbow *draws* — the still-open outer + // `begin`, but not the `module` around it. 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]["depth"], 1); assert_eq!(pairs[0]["open"]["start"]["line"], 2); assert_eq!(pairs[0]["close"]["start"]["line"], 4); @@ -712,18 +713,33 @@ fn a_pushed_exclude_rebuilds_the_index_mid_session() { r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"exclude":{patterns}}}}}}}}}"# )) }; + // An open buffer, so the *republish* half of `reindex()` has somewhere to + // land — `didSave` and the exclude push share that code, and without an + // open document the loop it runs is empty and proves nothing. + let open_uri = format!("file://{}", dir.join("kept.sv").display()); + let source = std::fs::read_to_string(dir.join("kept.sv")).expect("read"); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + // Publish #1. + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&source).expect("json") + )), query(2, "scratch_pkg"), + // A real change: rescan, and publish #2. exclude(r#"["scratch"]"#), query(3, "scratch_pkg"), query(4, "kept_pkg"), - // Clearing it puts the file back — the rescan runs in both directions. - exclude("[]"), + // The same value again is not a change: no rescan, and no publish. + exclude(r#"["scratch"]"#), query(5, "scratch_pkg"), + // Clearing it puts the file back — the rescan runs in both directions, + // and publishes #3. + exclude("[]"), + query(6, "scratch_pkg"), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] @@ -740,7 +756,18 @@ fn a_pushed_exclude_rebuilds_the_index_mid_session() { assert_eq!(hits(2), 1, "premise: indexed before the push"); assert_eq!(hits(3), 0, "the pushed exclude took it out of the index"); assert_eq!(hits(4), 1, "and left the file it does not match alone"); - assert_eq!(hits(5), 1, "clearing the setting puts it back"); + assert_eq!(hits(5), 0, "re-pushing the same value changes nothing"); + assert_eq!(hits(6), 1, "clearing the setting puts it back"); + + // The other half of `reindex()`: every open buffer is republished against + // the new index. One publish for the `didOpen`, then one per *changed* + // exclude — and none for the push that changed nothing. + let publishes = messages + .iter() + .filter(|m| m["method"] == "textDocument/publishDiagnostics") + .filter(|m| m["params"]["uri"] == open_uri.as_str()) + .count(); + assert_eq!(publishes, 3, "didOpen + two changed excludes, in {messages:#?}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/features/editor-scopes/README.md b/docs/features/editor-scopes/README.md index 93fecaa..1861909 100644 --- a/docs/features/editor-scopes/README.md +++ b/docs/features/editor-scopes/README.md @@ -50,6 +50,18 @@ already defines for bracket pairs. 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 `depth` if 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 two `begin`s is a difference the screen cannot explain. + A `begin` inside a `case` came out one colour deeper than its sibling + outside, so the `case` read 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 to `RULES` must therefore either join `RAINBOW_KEYWORDS` or stay + invisible in both senses at once, which is what + `the_depth_counter_and_the_wire_filter_read_the_same_list` enforces. - **Analysis is cheap enough to redo per request.** `analyze` is one pass over 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 @@ -115,11 +127,13 @@ Result: 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. +- `depth` counts **only the enclosing scopes that are themselves on the wire** + — `begin` and `fork` frames, nothing else. A `begin` directly inside a + `module` is 0; so is a `begin` inside a `case` inside that module; a `begin` + inside a `begin` is 1; a `begin` inside a `fork` inside a `begin` is 2. The + filter and the counter read the same `RAINBOW_KEYWORDS` const, so a scope is + counted if and only if it is sent. (This is the M5 reversal — see + Assumptions and the work log.) - 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. @@ -175,6 +189,8 @@ source. Neither file belongs to this feature, so neither was touched. configuration-change listener. - [x] `smoke.js` drives `vfmt/scopePairs` against a nested-begin + fork fixture and asserts the depths. +- [x] **M5:** wire `depth` counts only enclosing rainbow pairs, so a scope the + rainbow hides cannot shift the colour of one it shows. - [ ] 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. @@ -290,6 +306,9 @@ through an `lsp_types::request` type because the method is ours. 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. 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 @@ -335,6 +354,93 @@ 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: + +```rust +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 sibling `begin`s, one of them wrapping a + `case` that 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 a `begin` + that must still come out at depth 0. +- `only_begins_and_forks_stack_up_the_colours` — `begin`/`fork`/`begin` is + three real levels. +- `the_depth_counter_and_the_wire_filter_read_the_same_list` — walks `RULES` + and 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. + ## QA log ### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate @@ -545,6 +651,175 @@ 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: +- `begin` inside `function` inside `module` → `[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 real `begin` keyword and + therefore **is** a rainbow frame — it is not the same thing as the + enclosing (uncounted) `generate`. `generate → for (...) begin : g → if (i + == 0) begin` gives `[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`, the `no_hidden_scope_...` + case list) — the dev's own `generate` case is an *if*-generate with a + single anonymous `begin` (`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). +- `fork` inside `case` inside `begin` → `[0, 1]`: the case is hidden, the + fork sees one enclosing rainbow frame (the begin). +- Deeply mixed: `begin` / sibling `begin` inside a `function` (itself inside + a hidden `function`, wrapping `case` → `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"` to `RAINBOW_KEYWORDS` and, separately, changed + `scope_pairs`'s filter to a disconnected hardcoded `["begin", + "fork"].contains(...)` (recreating the pre-M5 shape: a keyword counted by + `analyze` but not sent by `scope_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_KEYWORDS` at `["begin", "fork"]` (so the trailing assert cannot + fire) and made only `analyze`'s counter diverge — `stack.iter().filter(|f| + f.rule.open == "begin")`, silently dropping `fork` from what gets + counted, without touching `scope_pairs`'s filter or `is_rainbow`. Result: + `the_depth_counter_and_the_wire_filter_read_the_same_list` **passed** + (both its loop and its pinned assert are blind to this, since neither + calls `analyze` or `scope_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_KEYWORDS` without the filter following" — + holds for the specific case where the two functions stay wired through + `is_rainbow` and 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 where `analyze` and `scope_pairs` are rewired to read from + different sources independently of `RAINBOW_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_rainbow` + called 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 on `RAINBOW_KEYWORDS`), or + strengthening the loop to call `analyze` and `scope_pairs` on a per-rule + fixture and compare their outputs directly rather than comparing + `is_rainbow` to itself. Left as a finding, not fixed, since either + direction is a design choice for the dev/lead. + - Both mutations reverted; `pairs.rs` `md5` confirmed + `975e8a4a80530309841415bd403cc71d` before, 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-server` fresh (`cargo build -p vfmt_server`), ran + `node 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; `md5` of `smoke.js` before and after is identical + (`2092dbb2331bd040932f3ccb76246398`). +- `node --check` on both `smoke.js` and `extension.js`: clean. +- `cargo test --workspace`: every crate green (194 unit + 9 e2e in + `vfmt_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 --stat` vs `HEAD` (`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`. No `vlog_formatter`/`vlog_parser`/`verify.rs` + path 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). + ## Review ### 2026-08-24 — lead review of M2 (after QA round 1) @@ -580,3 +855,21 @@ arm and the `smoke.js` extension. Approved and committed. Notes: 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_list` is accepted + as-is: the per-rule loop is tautological through `is_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 by + `only_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. diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js index c263d9c..44b73bf 100644 --- a/editors/vscode/smoke.js +++ b/editors/vscode/smoke.js @@ -133,11 +133,12 @@ server.on('close', (code) => { 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. + // Depth counts only the scopes the rainbow draws, so the enclosing module + // does not count: the outer begin is 0, the begin inside it is 1, and the + // fork is the outer begin's sibling at 0. 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)}`); + if (JSON.stringify(depths) !== JSON.stringify([0, 1, 0])) { + fail(`expected depths [0,1,0] (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);