Rainbow 0.3.1: never paint begin/end invisible; unmatched go red

The rainbow painted depth 3-5 pairs with editorBracketHighlight
.foreground4..6, whose VS Code defaults are fully transparent — a begin
typed three levels deep vanished with its end. The extension now uses
contributed vfmt.rainbow1..6 colors with opaque defaults in every theme
variant (dark/light/HC/HC-light), and vfmt/scopePairs additionally
reports genuinely unmatched begin/end/fork/join tokens, painted
vfmt.rainbowUnmatched bright red — file characters are never hidden.
Matched pairs, depths and 78eeef6's counting are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 15:45:54 -07:00
1 parent d8e37086df
commit ab89152264
13 files changed
+827 -60

No files matched your search

+25
View File
@@ -4,6 +4,31 @@ All notable changes to vfmt are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.3.1 — 2026-08-24
A fix for the `begin`/`end` rainbow, which could make the keywords it was
supposed to colour **invisible**. The extension painted each nesting level with
`editorBracketHighlight.foreground1..6`, VS Code's own bracket colours — but
only the first three of those have a visible default: `foreground4`, `5` and
`6` default to fully transparent and are left for themes to define, which most
themes never do. Any `begin`/`end` at nesting depth 3, 4 or 5 was therefore
painted transparent, and the keyword vanished from the screen. The rainbow now
uses its own colours, `vfmt.rainbow1` … `vfmt.rainbow6`, contributed by the
extension with an opaque default for dark, light and both high-contrast themes;
they appear under Workbench → Appearance → Color Customizations like any other
theme colour, so a theme or a `workbench.colorCustomizations` entry can still
override them. Levels 1–3 keep VS Code's familiar bracket hues so nothing
changes for the depths that already worked.
The same round makes the other half of the story visible: `vfmt/scopePairs` now
also reports **unmatched** block delimiters — a `begin` whose `end` never
arrived, an `end` that closes nothing — and the extension paints them in a
bright error red (`vfmt.rainbowUnmatched`) instead of leaving them as ordinary
uncoloured text. Typing a fresh `begin` now shows red until its `end` exists,
rather than showing nothing at all. Matched pairs, their nesting depths and the
missing-`end` warnings are unchanged. Details:
[editor-scopes](docs/features/editor-scopes/README.md).
## 0.3.0 — 2026-08-24
The refactoring release. `0.2.0` shipped a formatter, a linter and a language
Generated
+8 -8
View File
@@ -217,7 +217,7 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vfmt"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"rayon",
"vfmt_core",
@@ -228,11 +228,11 @@ dependencies = [
[[package]]
name = "vfmt_core"
version = "0.3.0"
version = "0.3.1"
[[package]]
name = "vfmt_server"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ dependencies = [
[[package]]
name = "vlog_formatter"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -263,11 +263,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.3.0"
version = "0.3.1"
[[package]]
name = "vlog_refactor"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -275,7 +275,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.3.0"
version = "0.3.1"
edition = "2021"
license = "MIT"
+1 -1
View File
@@ -581,7 +581,7 @@ registering the file types and starting the server:
```bash
tools/release.sh # builds dist/vfmt-<version>.vsix
code --install-extension dist/vfmt-0.3.0.vsix
code --install-extension dist/vfmt-0.3.1.vsix
```
Sideloading that `.vsix` is the supported install; the extension is not on any
+142 -12
View File
@@ -343,18 +343,27 @@ pub struct ScopePair {
#[derive(serde::Serialize)]
pub struct ScopePairs {
pub pairs: Vec<ScopePair>,
/// Block delimiters whose counterpart never arrived, in source order. The
/// extension paints these in its error colour: a keyword with no partner
/// has no depth and therefore no rainbow colour, and leaving it out of the
/// answer entirely is what used to leave it looking like ordinary text.
pub unmatched: Vec<Range>,
}
/// Every block-delimiter pair in a buffer, for the extension to colour.
/// Every block-delimiter pair in a buffer, plus the block delimiters that never
/// found a partner, 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.
/// so what reaches the wire and what was counted can never disagree. The same
/// list decides `unmatched`: a lone `end` is on the wire, a lone `endmodule` is
/// not, exactly as for matched pairs.
///
/// Unmatched keywords are not reported: there is nothing to colour when only
/// half a pair exists, and the missing-closer warning already says so.
/// A keyword is in `pairs` or in `unmatched`, never in both — `analyze` puts a
/// scope on exactly one of the three lists it returns.
pub fn scope_pairs(doc: &Document) -> ScopePairs {
let positions = doc.positions();
let pairs = analyze(&doc.tokens)
let analysis = analyze(&doc.tokens);
let pairs = analysis
.pairs
.iter()
.filter(|p| is_rainbow(p.keyword))
@@ -364,7 +373,19 @@ pub fn scope_pairs(doc: &Document) -> ScopePairs {
depth: p.depth,
})
.collect();
ScopePairs { pairs }
// An unmatched opener is a rainbow keyword itself; an unmatched closer
// names its opener in `expected`, which is the one to ask about (`end`
// belongs to `begin`, `endmodule` to `module`).
let mut lonely: Vec<TextRange> = analysis
.unmatched_open
.iter()
.filter(|u| is_rainbow(u.keyword))
.chain(analysis.unmatched_close.iter().filter(|u| is_rainbow(u.expected)))
.map(|u| u.span)
.collect();
lonely.sort_by_key(|span| span.start);
let unmatched = lonely.into_iter().map(|span| positions.range(span)).collect();
ScopePairs { pairs, unmatched }
}
// ----------------------------------------------------------------------
@@ -1008,13 +1029,15 @@ mod tests {
#[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.
// Half a pair is nothing to *colour by depth* — it has none — so it
// stays out of `pairs` and goes on the wire as `unmatched` instead.
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);
assert_eq!(sent.unmatched.len(), 1, "the outer begin is reported, not dropped");
assert_eq!(sent.unmatched[0].start.line, 1);
}
#[test]
@@ -1022,16 +1045,119 @@ mod tests {
let doc = doc_of("module m;\n wire a;\nendmodule\n");
let sent = scope_pairs(&doc);
assert!(sent.pairs.is_empty());
assert!(sent.unmatched.is_empty());
let json = serde_json::to_value(&sent).expect("serializes");
assert_eq!(json, serde_json::json!({ "pairs": [] }), "the shape is stable");
assert_eq!(
json,
serde_json::json!({ "pairs": [], "unmatched": [] }),
"the shape is stable"
);
}
// ------------------------------------------------------------------
// vfmt/scopePairs — unmatched block delimiters
// ------------------------------------------------------------------
/// The unmatched ranges of a buffer as `(line, character)` starts.
fn unmatched_starts(text: &str) -> Vec<(u32, u32)> {
scope_pairs(&doc_of(text))
.unmatched
.iter()
.map(|r| (r.start.line, r.start.character))
.collect()
}
#[test]
fn an_opener_that_never_closes_is_reported_as_unmatched() {
// The 0.3.1 bug's own shape: three nested `begin`s in a task, the
// outermost one missing its `end`. Before this, the wire said nothing
// about it and the extension painted it with no decoration at all.
let text = concat!(
"module m;\n",
" task t;\n",
" begin\n", // line 2 — never closes
" begin\n", // line 3 — closes on line 6
" begin\n",
" end\n",
" end\n",
" endtask\n",
"endmodule\n",
);
assert_eq!(unmatched_starts(text), vec![(2, 4)], "the `begin` that lost its `end`");
// And the pairs that *did* close still carry the depth they always
// did: an unmatched frame is still an enclosing scope.
let depths: Vec<u32> = scope_pairs(&doc_of(text)).pairs.iter().map(|p| p.depth).collect();
assert_eq!(depths, vec![1, 2], "the two inner begins, unshifted");
}
#[test]
fn a_closer_that_opens_nothing_is_reported_as_unmatched() {
let text = "module m;\n initial begin\n end\n end\nendmodule\n";
assert_eq!(unmatched_starts(text), vec![(3, 2)], "the second `end` closes nothing");
assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 1, "the real pair is untouched");
}
#[test]
fn a_balanced_file_reports_nothing_unmatched() {
let text =
"module m;\n initial begin\n fork\n x = 1;\n join\n end\nendmodule\n";
assert!(scope_pairs(&doc_of(text)).unmatched.is_empty());
assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 2);
}
#[test]
fn a_keyword_is_never_both_paired_and_unmatched() {
// The two lists are painted with different colours, so an overlap
// would be two decorations fighting over one keyword.
let text = concat!(
"module m;\n",
" initial begin\n",
" begin\n",
" end\n",
" end\n",
" initial begin\n",
" end\n",
" end\n",
" initial fork\n",
"endmodule\n",
);
let sent = scope_pairs(&doc_of(text));
let paired: Vec<Range> = sent.pairs.iter().flat_map(|p| [p.open, p.close]).collect();
assert_eq!(paired.len(), 6, "three pairs");
assert_eq!(sent.unmatched.len(), 2, "the stray `end` and the unclosed `fork`");
for lonely in &sent.unmatched {
assert!(!paired.contains(lonely), "{lonely:?} is on both lists");
}
}
#[test]
fn unmatched_carries_only_block_delimiters() {
// Same filter as `pairs`: the rainbow does not draw `module` or
// `function`, so it does not report their halves either.
let text = "module m;\n function f;\n begin\n";
let sent = scope_pairs(&doc_of(text));
assert!(sent.pairs.is_empty());
assert_eq!(sent.unmatched.len(), 1, "the begin only, not the module or the function");
assert_eq!(sent.unmatched[0].start.line, 2);
// The engine itself still saw all three unclosed.
assert_eq!(analyze(&doc_of(text).tokens).unmatched_open.len(), 3);
}
#[test]
fn an_unmatched_join_is_reported_but_an_unmatched_endcase_is_not() {
// `unmatched_close` carries the closer; the filter asks about the
// *opener* it wanted, which is what `expected` holds.
assert_eq!(unmatched_starts("module m;\n join\nendmodule\n"), vec![(1, 2)]);
assert!(unmatched_starts("module m;\n endcase\nendmodule\n").is_empty());
}
#[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");
// extension indexes `pairs[].depth % 6`, paints `unmatched` in its
// error colour, and hands every range straight to the client's Range
// converter.
let doc = doc_of("module m;\n initial begin\n end\n begin\nendmodule\n");
let json = serde_json::to_value(scope_pairs(&doc)).expect("serializes");
assert_eq!(
json,
@@ -1046,6 +1172,10 @@ mod tests {
"end": { "line": 2, "character": 5 }
},
"depth": 0
}],
"unmatched": [{
"start": { "line": 3, "character": 2 },
"end": { "line": 3, "character": 7 }
}]
})
);
+33
View File
@@ -502,13 +502,21 @@ fn the_binary_serves_a_whole_session_over_stdio() {
const UNBALANCED: &str =
"module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n";
/// The same file with the missing `end` put back — the other half of the
/// `unmatched` contract: present and empty rather than absent.
const BALANCED: &str =
"module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n";
#[test]
fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
let dir = temp_dir("scopes");
let file = dir.join("m.sv");
std::fs::write(&file, UNBALANCED).expect("write");
let clean_file = dir.join("clean.sv");
std::fs::write(&clean_file, BALANCED).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let clean_uri = format!("file://{}", clean_file.display());
let highlight = |id: u32, line: u32, character: u32| {
frame(&format!(
@@ -537,6 +545,16 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"vfmt/scopePairs","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
// The same request against a balanced buffer: `unmatched` has to come
// back present and empty, because that is what clears the extension's
// error decoration.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{clean_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(BALANCED).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"vfmt/scopePairs","params":{{"textDocument":{{"uri":"{clean_uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
@@ -591,6 +609,21 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
assert_eq!(pairs[0]["open"]["start"]["line"], 2);
assert_eq!(pairs[0]["close"]["start"]["line"], 4);
// The `begin` that lost its `end` is reported so the extension can paint
// it in its error colour instead of leaving it undecorated.
let unmatched = scope_pairs["result"]["unmatched"].as_array().expect("an unmatched array");
assert_eq!(unmatched.len(), 1, "the unclosed begin on line 1: {unmatched:#?}");
assert_eq!(unmatched[0]["start"]["line"], 1);
assert_eq!(unmatched[0]["start"]["character"], 10);
let clean = messages.iter().find(|m| m["id"] == 7).expect("scopePairs response");
assert_eq!(clean["result"]["pairs"].as_array().map(Vec::len), Some(2), "{clean:#?}");
assert_eq!(
clean["result"]["unmatched"].as_array().map(Vec::len),
Some(0),
"a balanced buffer answers with an empty list, not a missing field: {clean:#?}"
);
// The warning rides along with the parse error, in one publish.
let published = messages
.iter()
+443 -6
View File
@@ -11,9 +11,10 @@ highlights its own `end` (real matching, not a text search for the word), and a
**missing-closer warning** that points at the `begin` which lost its `end`
instead of leaving the user with one parse error at the bottom of the file. The
third consumer is the extension's rainbow: `vfmt/scopePairs` hands the client
every `begin`/`end` and `fork`/`join*` pair with its nesting depth, and
`extension.js` paints each depth in one of the six colours the user's theme
already defines for bracket pairs.
every `begin`/`end` and `fork`/`join*` pair with its nesting depth — plus every
block delimiter still waiting for its partner — and `extension.js` paints each
depth in one of six colours the extension contributes itself, and each lonely
keyword in an error red.
## Assumptions
@@ -62,6 +63,15 @@ already defines for bracket pairs.
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.
- **A colour this feature paints is always opaque, and the file is never
hidden.** The owner's rule, in their words: *"respect the file content and
never hide any characters that are part of the file. You can make their
colour bright red for error in syntax, but don't just hide them."* That rules
out borrowing a theme colour whose default is `#00000000`, which is what
0.3.1 fixed, and it is why an unmatched keyword is painted rather than left
alone. A user or a theme may still override a `vfmt.rainbow*` id with
anything they like — including transparent — and that is their decision, not
a default of ours.
- **Analysis is cheap enough to redo per request.** `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
@@ -117,7 +127,10 @@ know it simply never asks:
Result:
```json
{ "pairs": [ { "open": Range, "close": Range, "depth": 0 } ] }
{
"pairs": [ { "open": Range, "close": Range, "depth": 0 } ],
"unmatched": [ Range ]
}
```
- `open`/`close` are LSP `Range`s over the **keyword itself** — UTF-16, like
@@ -134,13 +147,32 @@ Result:
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.
- `unmatched` holds the **block delimiters that never found a partner** — every
`begin`/`fork` left on the stack and every `end`/`join*` that closed nothing —
as one flat list of keyword ranges in source order. Same `RAINBOW_KEYWORDS`
filter as `pairs`, asked of the *opener*: a stray `end` is on the wire
because `begin` is a rainbow keyword; a stray `endmodule` is not. A keyword
is in `pairs` or in `unmatched`, never in both — `analyze` puts each scope on
exactly one of its three lists. No depth: half a pair has no nesting level,
which is precisely why the extension paints it a fixed error colour instead.
(Added in 0.3.1 — see *Unmatched tokens* below and the work log.)
- An unopened document answers `null`, matching every other handler here.
The extension treats that as "no pairs".
- Both lists are always present, empty rather than absent, so the client can
clear a decoration with `|| []` and never has to distinguish "none" from
"this server does not know about them". A client one version older than the
server ignores `unmatched`; a client one version *newer* reads it as `[]`,
which is why `extension.js` writes `(result && result.unmatched) || []`.
Ordering is by opener position, though the extension does not depend on it.
**Promised to `package.json` — the colour ids.** The extension contributes
`vfmt.rainbow1` … `vfmt.rainbow6` and `vfmt.rainbowUnmatched` under
`contributes.colors`, and `extension.js` builds one `TextEditorDecorationType`
per id. Renaming an id in either file without the other silently paints
nothing: an unknown `ThemeColor` is not an error, it is simply no colour. See
*The palette* below for why the ids are ours and not VS Code's.
**Promised to any future consumer:** `analyze(&[Token]) -> ScopeAnalysis`, with
`Pair { open, close, keyword, depth }`. `keyword` is the opener as written,
which is how `scope_pairs` filters.
@@ -168,6 +200,93 @@ a construct with no closer:
server by one capability (`textDocument/documentHighlight`) and one diagnostic
source. Neither file belongs to this feature, so neither was touched.
## Unmatched tokens
A `begin` whose `end` has not been typed yet is the most common state a
`begin` is ever in: the user types the opener, presses Enter, and *then* writes
the body. Until 0.3.1 the wire said nothing about it — `pairs` carried closed
pairs only — so the extension had nothing to paint, and a half-typed block was
ordinary uncoloured text.
`unmatched` fixes that with the lists `analyze` has produced since M2:
`unmatched_open` (openers left on the stack, including the ones the mismatch
recovery pops out of the middle) and `unmatched_close` (closers that matched no
frame). `scope_pairs` filters both with the same `RAINBOW_KEYWORDS` used for
`pairs`, merges them, and sorts by position. Three properties are worth stating
because tests pin all three:
1. **Never both.** A keyword that is in `pairs` cannot be in `unmatched`. The
engine puts each scope on exactly one list, and the two decorations would
otherwise fight over one range.
2. **Same filter, asked of the opener.** `unmatched_open` carries the opener as
`keyword`; `unmatched_close` carries the closer as `keyword` and the opener
it wanted as `expected`. The filter reads `keyword` for the first and
`expected` for the second, so a lone `join` is reported (its opener `fork`
is a rainbow keyword) and a lone `endcase` is not.
3. **Depths do not move.** An unmatched frame is still an enclosing scope while
it is on the stack, so a `begin` nested inside an unclosed `begin` reports
depth 1 exactly as it did before — the M5 counting rule is untouched, and
its tests were not edited.
There is no gate here, unlike the missing-closer *diagnostics*, which fire only
when the parse has already failed. A diagnostic asserts the file is wrong; a
colour only says "this keyword has no partner in the token stream", which is
true of a macro-supplied `end` too — and the honest thing to show for it. The
cost of being wrong is a red keyword on a file that compiles, and the user can
turn the whole rainbow off; the cost of a wrong *diagnostic* is telling someone
their working code is broken, which is why that one stays gated.
## The palette
**Why not `editorBracketHighlight.foreground1..6`.** They look like exactly the
right thing to borrow — the user's own theme, six levels, no invented colours —
and M3 did borrow them. But VS Code's colour registry gives visible defaults to
only the first three; `foreground4`, `foreground5` and `foreground6` default to
**`#00000000`, fully transparent**, on the assumption that a theme which wants
six bracket levels will define them, and most themes define none. VS Code's own
bracket colouriser skips transparent entries when it cycles. Ours did not, so
every pair at `depth % 6 ∈ {3, 4, 5}` was painted transparent — the keyword
disappeared. A `ThemeColor` that resolves to nothing is invisible failure by
design: it is not an error, it is just no paint.
So the extension contributes its own ids with `contributes.colors`, each with a
default for `dark`, `light`, `highContrast` and `highContrastLight`. A theme
that knows nothing about vfmt gets our default; a theme or a
`workbench.colorCustomizations` entry that names `vfmt.rainbowN` still wins,
which is the override story the borrowed ids gave us and the only thing worth
keeping about them.
| Id | Dark | Light | Why |
|---|---|---|---|
| `vfmt.rainbow1` | `#FFD700` gold | `#0431FA` blue | VS Code's own level-1 bracket colours, both themes |
| `vfmt.rainbow2` | `#DA70D6` orchid | `#319331` green | VS Code's own level 2 |
| `vfmt.rainbow3` | `#179FFF` blue (`#87CEFA` on HC dark) | `#7B3814` brown | VS Code's own level 3, HC variant included |
| `vfmt.rainbow4` | `#87D96B` green | `#0E7490` teal | first free hue in each theme; ~11:1 on `#1E1E1E`, ~5.2:1 on white |
| `vfmt.rainbow5` | `#FF8C69` salmon | `#6D28D9` violet | warm against the dark greens/golds, cool against the light greens/browns |
| `vfmt.rainbow6` | `#4FD6D6` cyan | `#BE185D` magenta | closes the wheel without repeating 1–3 in either theme |
| `vfmt.rainbowUnmatched` | `#FF1212` red | `#B30000` dark red (`#A80000` HC light) | the error state, and the one colour that must read as *wrong* |
Two things about that table are decisions rather than transcription:
- **Levels 1–3 are copied from VS Code per theme, not per colour.** The plan
said gold/orchid/blue "same in dark and light"; VS Code's actual light
defaults are blue/green/brown, and it is right to be: gold on white is about
1.4:1, which is the same invisibility problem in a different costume. Since
every reader of this file already has VS Code's bracket colours in muscle
memory, matching them exactly per theme is the least surprising choice, and
levels that already worked before 0.3.1 keep the colour they had.
- **Levels 4–6 differ by hue between dark and light**, because the sets they
must stay distinguishable from differ: dark 1–3 use up yellow, magenta and
blue, light 1–3 use up blue, green and brown. VS Code sets the precedent by
using two entirely different trios for its own 1–3. Every value clears 4.5:1
against its theme's default editor background, and the light ones are dark
enough to read as text rather than as a highlight.
The unmatched red is deliberately close to a plain error red rather than a
seventh rainbow hue: it is a state, not a level, and the salmon at level 5 is
the only neighbour it could be confused with — a pale orange-pink against a
saturated pure red, and only ever on screen while a block is half-typed.
## Status / TODO
- [x] `pairs.rs`: `analyze`, the `RULES` table, the prototype flag, the
@@ -191,6 +310,11 @@ source. Neither file belongs to this feature, so neither was touched.
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.
- [x] **0.3.1:** the rainbow's colours are the extension's own
(`vfmt.rainbow1..6`), opaque in every theme kind — `foreground4..6`
default to transparent and were painting depths 3–5 invisible.
- [x] **0.3.1:** `unmatched` on the wire, painted `vfmt.rainbowUnmatched`, so a
half-typed `begin` is bright red rather than uncoloured.
- [ ] 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.
@@ -441,6 +565,116 @@ not rescan. Mutation-checked (expecting 4 fails with `left: 3`).
`cargo test --workspace` green, `node smoke.js` against a freshly built
`target/debug/vfmt-server` OK.
### 2026-08-24 — 0.3.1: the rainbow was painting with transparent colours
**The bug, as reported.** In `Clock Divider/clkdivider_tb.v`, typing `begin`
and pressing Enter at line 34 made *both* that `begin` and the `end` below it
**invisible** — not mis-coloured, gone. Everything else in the file kept its
colours.
**Root cause, confirmed against the running server.** The server was right: its
`vfmt/scopePairs` answer put the new pair at depth 3, with correct ranges. The
extension was wrong. It painted depth `d` with
`ThemeColor('editorBracketHighlight.foreground' + (d % 6 + 1))`, and VS Code's
colour registry gives visible defaults to only `foreground1..3`; `4`, `5` and
`6` default to **`#00000000`, fully transparent**, left for themes to define,
and most themes define none. So every pair at `depth % 6 ∈ {3, 4, 5}` was
painted transparent. VS Code's own bracket colouriser skips transparent entries
while cycling; ours did not. The old comment in `extension.js` — "an unset
`editorBracketHighlight.foregroundN` leaves the text its normal colour, which
is the right failure" — was wrong twice over: those keys are not unset, they
are set to transparent, and a keyword you cannot see is not a right failure.
This had been live since M3; M5 made it *more* visible by renumbering depths
downward, which moved a lot of real code from the safe 0–2 band into 3–5.
**The fix, three parts.**
1. **Our own colours.** `contributes.colors` in `package.json` declares
`vfmt.rainbow1..6` and `vfmt.rainbowUnmatched`, each with a default for
`dark`, `light`, `highContrast` and `highContrastLight`, and none of them
transparent. `extension.js` builds its decoration types from those ids. The
values and the reasoning are in *The palette* above; the short version is
that 1–3 copy VS Code's own bracket defaults **per theme** (so nothing
changes for the depths that already worked) and 4–6 are new hues chosen to
stay distinguishable from 1–3 within each theme.
2. **`unmatched` on the wire.** `ScopePairs` gained
`unmatched: Vec<Range>` — the block delimiters `analyze` already knew were
partnerless, filtered by the same `RAINBOW_KEYWORDS` as `pairs` and sorted
by position — and `extension.js` paints them `vfmt.rainbowUnmatched`. This
is the owner's rule applied to the state that started it all: a `begin` you
have just typed has no `end` yet, so it has no depth and no rainbow colour,
and *"you can make their colour bright red for error in syntax, but don't
just hide them."*
3. **Defensive reads in `paint`.** `pair.depth` goes through
`Number.isInteger` before indexing the buckets (a non-numeric depth would
index with `NaN` and drop the pair silently), and `unmatched` is read as
`(result && result.unmatched) || []`, so a newer extension against an older
server keeps the rainbow and simply paints no reds.
**Nothing about `pairs` moved.** The filter, the ranges and M5's depth counting
are untouched — `78eeef6`'s six depth tests were not edited and still pass, and
the new `an_opener_that_never_closes_is_reported_as_unmatched` pins the
interaction directly: in three nested `begin`s missing one `end`, the two that
do close still report depths `[1, 2]`, because an unmatched frame is still an
enclosing scope while it sits on the stack.
**Tests.** `vfmt_server`: **285 unit** (was 279; six new, all in the
`vfmt/scopePairs` section) and **16 e2e**. New unit tests: an opener that never
closes is reported; a closer that opens nothing is reported; a balanced file
reports nothing; a keyword is never both paired and unmatched (three pairs, one
stray `end`, one unclosed `fork`, no range on both lists); `unmatched` carries
only block delimiters (a file with `module`, `function` and `begin` all open
reports one range, while `analyze` still sees three); a lone `join` is reported
but a lone `endcase` is not — the closer filter asks about `expected`, the
opener it wanted. Updated: the pinned-JSON wire test now carries an `unmatched`
entry, the empty-file shape test pins `{"pairs": [], "unmatched": []}`, and
`scope_pairs_omits_a_pair_that_never_closed` asserts the half-pair reappears in
the new list rather than vanishing. `tests/e2e.rs` opens a second, *balanced*
buffer in the same session and asserts `unmatched` comes back present and
empty; `smoke.js` does the same and additionally asserts the exact position of
the unclosed `begin` in a broken buffer.
**Mutation-checked, both directions.** Clearing `lonely` just before it is
sorted (so `unmatched` always ships empty) fails **7 unit tests and exactly one
e2e test** (`scope_highlights_…`, at the new `unmatched` assertion, after every
older assertion in it has passed) — the new coverage is live, and no
pre-existing test depends on the new field. `pairs.rs` md5 verified identical
before and after (`0182214662224b7782ffeb7b2d3d115b`). In `smoke.js`, changing
the expected unmatched line from 2 to 9 fails with the real position printed;
reverted, md5 identical (`0ff5e46f51b9c7f2079d899104776ddb`).
**Deviations from the plan.**
- The plan said levels 1–3 should be gold/orchid/blue "same in dark and light".
They are VS Code's dark values only; VS Code's light defaults are
blue/green/brown and this follows them instead, because gold on white is
~1.4:1 contrast — the same invisibility bug wearing a different hat.
- Each colour also carries a `highContrastLight` default, which the plan did
not mention: without it a high-contrast *light* theme falls back to the
ordinary light value, which happens to be fine here, but stating all four is
one line each and leaves nothing to inference.
- `vfmt.rainbowBeginEnd`'s description in `package.json` and the "Rainbow
begin/end" section of `editors/vscode/README.md` both said the colours come
from the theme's bracket palette. Both are now accurate and document the
override recipe; they are this feature's own user-facing text, so they were
updated rather than filed as a request.
**Version 0.3.1.** `Cargo.toml` `[workspace.package]`, `Cargo.lock` (via
`cargo check --workspace`), `editors/vscode/package.json`,
`editors/vscode/package-lock.json` (both places), plus the illustrative
version strings in `tools/RELEASING.md` and `README.md`'s install example — the
same set M5 touched for 0.3.0. `target/debug/vfmt --version` → `vfmt 0.3.1`.
`CHANGELOG.md` has a `0.3.1 — 2026-08-24` section in the changelog's voice.
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy --workspace
--all-targets` **0 warnings**; `cargo test --workspace` **1268 passed, 0
failed**; `node --check` on `extension.js` and `smoke.js` clean; `node smoke.js
../../target/debug/vfmt-server` **OK** against a freshly built binary;
`npx @vscode/vsce ls` still accepts the manifest with the new
`contributes.colors` block. No new dependencies, no `unwrap`/`expect`/`panic!`
outside `#[cfg(test)]`, no `#[allow]` added, and `TODO.md` and
`docs/features/refactor/README.md` were not touched.
## QA log
### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate
@@ -820,6 +1054,190 @@ other — worth a rename or a rewrite next time this test is touched, not
blocking today's fix (which is correct and well covered by the ordinary depth
tests).
### 2026-08-24 — QA round 5 (0.3.1): the transparent-colour fix and `unmatched`
Charter: the owner-confirmed root cause (transparent `foreground4..6`
defaults) and its fix — the extension's own opaque colour ids, `unmatched` on
the wire, and the defensive reads in `paint`. Scope: uncommitted working tree,
diff vs `HEAD` (`d8e3708`) — `CHANGELOG.md`, `Cargo.toml`, `Cargo.lock`,
`README.md`, `crates/vfmt_server/src/pairs.rs`, `crates/vfmt_server/tests/e2e.rs`,
`docs/features/editor-scopes/README.md`, `editors/vscode/{README.md,
extension.js, package-lock.json, package.json, smoke.js}`, `tools/RELEASING.md`.
Verdict: **ship-after-fixes** — one fix applied directly (below), one
low-severity non-blocking finding filed.
**Method.** Same discipline as rounds 1–4: throwaway additions to `pairs.rs`'s
own `#[cfg(test)] mod tests`, run, read, removed before this entry was
written; `md5` of `pairs.rs` confirmed `0182214662224b7782ffeb7b2d3d115b`
before, and identical again after removal — matching the dev's own reported
hash for the same file, so the working tree really is what the Work Log
describes.
**1. Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --workspace
--all-targets`: clean, 0 warnings. `cargo test --workspace`: **1268 passed, 0
failed** — summed the per-crate `test result:` lines independently rather than
trusting the dev's total; `vfmt_server` alone is **285 unit + 16 e2e**, an
exact match to the Work Log. `node --check` on `extension.js` and `smoke.js`:
both clean. `node smoke.js ../../target/debug/vfmt-server` against a freshly
built (`cargo build -p vfmt_server`) binary: **OK**.
**2. The real user scenario, end to end.** Drove the built debug server over
stdio (a hand-rolled probe mirroring `smoke.js`'s framing, since the crate
exposes no lib target) against the actual file named in the bug report,
`/Users/guoliangchen/repo/Verilog-Design-Examples/Clock Divider/clkdivider_tb.v`
— note this required `url.pathToFileURL()` to percent-encode the space in the
directory name; a naive `file://${path}` template gave the server a URI it
rejected with `unexpected character at index 61`, which is a probe-tooling
gotcha and not a server defect (LSP URIs are always supposed to arrive
percent-encoded; VS Code's own `document.uri.toString()` does this correctly).
Findings, both exactly as claimed:
- **The depth-3 pair survives.** The `begin` at 0-based line 33, character 29
(1-based line 34, the exact keyword the bug report named) is still in
`pairs`, at `depth: 3`, closed by the `end` at 0-based line 35. Confirms the
server-side data was correct all along — this was always a client-painting
bug, as the root-cause writeup says.
- **`unmatched` correctly names the *actual* orphan, which is not the line-34
`begin`.** The file's real structure (traced by hand against the returned
ranges): `repeat (30) begin` at 0-based line 27 / char 18 opens a frame that
is never closed — the file is missing one `end` before `endtask`. The
line-34 `begin` the user typed *does* have a partner two lines down; it is
three frames deep inside the unclosed `repeat`, which is exactly why the
bug was invisible in the first place (depth 3 is where `foreground4`
starts). `unmatched` reports one entry, at 0-based line 27 / char 18–23 —
the `repeat`'s `begin`, not line 34's. This is a stronger check than any
synthetic fixture in the suite: it is a real, messy, 78-line file with a
pre-existing authoring bug, and the matcher still finds the one keyword
that is genuinely alone rather than the one a naive "most recently typed"
guess would name.
**3. Colour-id audit, programmatic.** Extracted every `vfmt.rainbow*` id
`extension.js` references (`vfmt.rainbow${index + 1}` for `index` 0–5, plus
the literal `vfmt.rainbowUnmatched`) and diffed against `package.json`'s
`contributes.colors` array. All 7 declared, all 7 referenced, no orphans
either direction. For each, checked all four `defaults` keys
(`dark`/`light`/`highContrast`/`highContrastLight`) are present and parsed
each as `#RRGGBB` (alpha 255) or `#RRGGBBAA` (alpha from the last byte),
flagging anything below alpha 200/255. **0 findings** — every default is a
plain 6-digit opaque hex; none of the eight-digit "looks opaque but has a
sneaky alpha byte" shape the bug's root cause would predict appears anywhere.
**4. Adversarial probes** (seven throwaway `#[cfg(test)]` additions to
`pairs.rs`, run together, all passed, then removed — see Method):
| Probe | Result |
|---|---|
| A file that is *only* `end` (first token, nothing else) | one `unmatched` entry at 0:0; no crash on an empty stack |
| Every `join`/`join_any`/`join_none` alone (no `fork`) | each reported as `unmatched_close` with `expected: "fork"`; an unclosed `fork` itself names `join` (the first, canonical closer) — never `join_any`/`join_none` |
| Unmatched `begin` at EOF with no trailing newline | still reported; `scope_pairs` correctly narrows the raw engine's `["module", "begin"]` (the module is also unclosed in this fixture) down to `["begin"]` |
| `begin`/`end`/`fork`/`join` spelled inside a `//` comment and a `$display` string | zero pairs, zero unmatched from the fake text — only the one real `begin`/`end` counted, confirming comments/strings never reach the matcher even for the *unmatched* path, not just the matched one |
| Both a stray `end` and an unclosed `begin` in one file | both reported, sorted by position (stray `end` first, unclosed `begin` second, matching source order) |
| An unclosed `begin` after a comment with `é`, `✓`, and `日本語` | UTF-16 character offset lands on the keyword exactly (10), unaffected by the multibyte text before it |
| A minimized reproduction of the `clkdivider_tb.v` shape (an unclosed `repeat`-style outer `begin` wrapping three cleanly-nested `begin`s) | the three inner pairs close normally at depths `[1, 2, 3]`, unaffected by their unmatched enclosing frame; only the outer `begin` is reported unmatched — same shape as finding 2 above, now pinned as a minimal fixture |
No probe found a false positive, a false negative, a panic, or a misattributed
range.
**5. `78eeef6`'s pinned depth tests, independently diffed rather than taken on
faith.** `git diff 78eeef6 -- crates/vfmt_server/src/pairs.rs`, checked for
each of the six tests the Work Log names as unedited:
`a_module_with_nested_begins_matches_every_pair`,
`a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows`,
`no_hidden_scope_counts_toward_the_depth`,
`only_begins_and_forks_stack_up_the_colours`,
`scope_pairs_depths_nest_and_forks_are_included` — **byte-identical**, zero
diff hunks touching any of the five. The sixth,
`the_scope_pairs_wire_shape_is_what_the_extension_reads`, does appear in the
diff, but only for the documented reason: the pinned JSON literal gained the
new `unmatched` field and a comment update, not a depth-logic change. Matches
the claim exactly.
**6. `extension.js` — the two specific code paths named in the charter.**
- *Old-server response with no `unmatched` key.* Read
`editors/vscode/extension.js:194`: `for (const range of (result &&
result.unmatched) || []) { unmatched.push(asRange(range)); }`. A missing
key makes `result.unmatched` `undefined`, `(result && undefined) || []`
evaluates to `[]`, and the loop is a no-op. Correct, matches the claim.
- *`depth: null` / negative from a hostile server.* `extension.js:188`:
`const depth = Number.isInteger(pair.depth) ? pair.depth : 0;` — the guard
is genuinely reached before `buckets[depth % RAINBOW_COLORS]` on the next
line, and `Number.isInteger(null)` is `false`, so `null` is caught and
substituted with `0` correctly. **But the guard does not fully do what its
comment claims for a negative integer.** `Number.isInteger(-1)` is `true`
(it is a real integer), so `-1` passes through unchanged; JavaScript's `%`
is not Euclidean, so `-1 % RAINBOW_COLORS` is `-1`, not `5`, and
`buckets[-1]` is `undefined`. The next line, `ranges.push(...)`, then
throws `TypeError: Cannot read properties of undefined (reading 'push')`
— confirmed with a standalone Node repro, not just by reading the code.
That throw is inside the `for (const pair of ...)` loop in `paint()`,
which is *not* inside the function's `try`/`catch` (only the
`client.sendRequest` await is guarded), so it propagates out of `paint()`
as an unhandled rejection from the caller in `repaintVisible`'s loop,
aborting that repaint partway through — the buckets already painted stay
painted, the rest of that call's decorations (including `unmatched`) never
get set, and there is no console-visible failure beyond whatever VS Code's
extension host logs for an unhandled rejection.
**Severity: low, non-blocking.** The real server's `depth` is a Rust `u32`
serialized through `serde`, which cannot be negative — this path is
unreachable against the server this extension actually ships with, and
every invariant this feature exists to protect (never hide a character,
never corrupt code) is about the *file*, which this cannot touch; the
worst case is a skipped repaint of a cosmetic decoration, self-healing on
the next debounce tick against a well-behaved server. Filed because the
work log's own framing — "a non-numeric depth would index with `NaN` and
drop the pair silently" — describes the `NaN` case correctly but is silent
about the negative-integer case, which behaves differently (a thrown
exception, not a silent drop) and is exactly the shape the charter asked
to be probed. Worth either `Math.abs` before the modulo, an explicit
`depth >= 0` check alongside `Number.isInteger`, or a code comment
admitting the assumption — not worth blocking this release, since it
requires a server this extension does not have.
**7. Version bump — found and fixed directly.** Grepped the tree for stray
`0.3.0` outside changelog history and cache fixtures. `cargo metadata`: all
eight workspace crates report `0.3.1`. Both `package-lock.json` spots
(top-level `version` and `packages[""].version`): `0.3.1`. `Cargo.lock`'s
diff against `HEAD` is eight `version = "0.3.0"` → `"0.3.1"` line pairs, one
per workspace crate, nothing else — confirmed with a diff filtered to
added/removed lines only, no dependency added or removed. `CHANGELOG.md`'s
`0.3.1` section read in full: accurate to the diff, including the one line
that could have overclaimed and doesn't — "Matched pairs, their nesting
depths and the missing-`end` warnings are unchanged" — verified true by
finding 5 above.
One gap: `editors/vscode/README.md:49` and `:56` still read
`vfmt-0.3.0.vsix` in the install-example commands, while the parallel example
in the repo-root `README.md:584` correctly reads `vfmt-0.3.1.vsix`. This file
is not pristine — this very diff touches it for the rainbow-palette
documentation (`git diff HEAD -- editors/vscode/README.md`, the
`workbench.colorCustomizations` snippet and the "seven colours" rewrite) —
but the two version strings were already stale at `0.3.0` before this diff
(`git show HEAD:editors/vscode/README.md` shows the same `vfmt-0.3.0.vsix`
text, so this is not a regression this diff introduced), and the Work Log's
own version-bump list names only `tools/RELEASING.md` and (root) `README.md`
as the "illustrative version strings" set, omitting this file even though it
carries the same kind of string. A one-line-each, unambiguous doc fix per
this role's charter — **fixed directly**, both occurrences now read
`vfmt-0.3.1.vsix`, no code or test changes involved.
**8. Invariants.** No `unwrap()`/`expect()`/`panic!()`/`#[allow]` added
anywhere in the `pairs.rs` diff (grepped every added line of `git diff HEAD --
pairs.rs` for all four, programmatically — 0 hits, including inside the new
test module, since the new tests use only `assert_eq!`/`assert!`). `git diff
--stat` vs `HEAD` matches the charter's file list exactly, confirmed by
listing rather than assumed.
**Verdict: ship-after-fixes.** No blocking findings — the reported bug is
genuinely fixed, confirmed against the real file from the bug report rather
than only synthetic fixtures, and `unmatched` correctly distinguishes "has a
partner but is deeply nested" from "genuinely alone" on a real 78-line file
with a pre-existing authoring bug. One doc staleness was small and
unambiguous enough to fix directly (item 7). One low-severity, non-blocking
finding remains for the lead/dev to accept or schedule (item 6, the
negative-depth modulo gap) — it cannot fire against this server as shipped,
so it does not block 0.3.1, but the work log's defensive-reads claim should
either be corrected or the code tightened next time this file is touched.
## Review
### 2026-08-24 — lead review of M2 (after QA round 1)
@@ -873,3 +1291,22 @@ Approved and committed. Notes:
`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.
### 2026-08-24 — lead review of the invisibility fix (after QA round 5)
Root cause was mine to confirm before the dev brief: the server's answers
were correct, and the invisibility came from painting depth 3–5 with
`editorBracketHighlight.foreground4..6`, whose VS Code defaults are
transparent. The fix is the right shape — extension-contributed
`vfmt.rainbow1..6` colors that are never transparent in any theme variant,
plus `vfmt.rainbowUnmatched` bright red for genuinely unmatched tokens,
exactly the owner's never-hide/red-for-errors ruling. Dev's deviation
(VS Code's real light-palette for 1–3 instead of gold-on-white) is
approved: it avoids re-shipping the same bug in light themes. QA verified
the actual reported file end-to-end — the depth-3 pair renders and the
true orphan (`repeat (30) begin`, line 28) is the one reported unmatched —
and audited every color default programmatically. I applied QA's LOW
myself: the depth guard now also rejects negative integers
(extension.js:188), so a hostile depth can never throw mid-repaint.
Gates re-run after that one-liner: 1268 tests, 0 failures, smoke OK.
Accepted; ships as 0.3.1.
+23 -8
View File
@@ -46,14 +46,14 @@ catches "the binary moved" or "the handshake broke" without launching VS Code.
```bash
npm ci # installs vscode-languageclient (the only dependency)
npx @vscode/vsce package
code --install-extension vfmt-0.3.0.vsix
code --install-extension vfmt-0.3.1.vsix
```
Then reload VS Code and open a `.v`/`.sv`/`.vh`/`.svh` file.
`tools/release.sh` from the repo root does all of the above (plus the release
binaries and checksums) and drops the `.vsix` in `dist/`, so
`code --install-extension dist/vfmt-0.3.0.vsix` is the one-command path.
`code --install-extension dist/vfmt-0.3.1.vsix` is the one-command path.
`editors/vscode/LICENSE` is a copy of the repo's MIT license and is what lets
`vsce package` run without `--skip-license`. If you are packaging a fork that
dropped `package.json`'s `repository` field, add `--allow-missing-repository`.
@@ -73,7 +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. |
| `vfmt.rainbowBeginEnd` | `true` | Colour each nesting level of `begin`/`end` and `fork`/`join` differently, and half a pair in an error colour. Takes effect immediately — no reload. |
| `vfmt.lineLength` | unset | Maximum line width, same as `line-length` in a `vfmt.toml`. 40–400. |
| `vfmt.indent` | unset | Indent width in spaces, same as `indent` in a `vfmt.toml`. 1–8. |
| `vfmt.exclude` | `[]` | Extra patterns to keep out of the workspace index, same as `exclude` in a `vfmt.toml`. **Added to** the project's excludes, never replacing them. |
@@ -120,11 +120,26 @@ walking the folder — the index is never silently empty.
## 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`.
and a keyword whose counterpart is missing — a `begin` you have just typed, an
`end` that closes nothing — is painted in a bright error red until you finish
the pair. 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`.
The seven colours are the extension's own, so they are always visible whatever
theme you use, and you can change any of them in
`workbench.colorCustomizations`:
```jsonc
"workbench.colorCustomizations": {
"vfmt.rainbow1": "#FFD700", // and rainbow2 … rainbow6
"vfmt.rainbowUnmatched": "#FF1212" // the half-pair colour
}
```
(They are deliberately *not* `editorBracketHighlight.foreground1`…`6`: VS Code
defaults the last three of those to transparent, so borrowing them made deeply
nested `begin`s invisible in most themes.)
Turn it off with `"vfmt.rainbowBeginEnd": false`; the colours disappear
immediately. Cursor on a `begin` also highlights its matching `end` — that is
+36 -10
View File
@@ -18,10 +18,14 @@ let client;
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.
* How many colours the rainbow cycles through. Six, to match VS Code's own
* bracket colouring — but the colours are **this extension's own**
* (`vfmt.rainbow1..6`, contributed with visible defaults for every theme kind
* in `package.json`), not `editorBracketHighlight.foreground1..6`. Those look
* like the obvious thing to borrow and are a trap: VS Code's registry defaults
* `foreground4`, `5` and `6` to `#00000000` — fully transparent — and leaves it
* to themes to define them, which most do not. Painting with them made every
* `begin` at depth 3, 4 or 5 invisible.
*/
const RAINBOW_COLORS = 6;
@@ -31,6 +35,9 @@ const REPAINT_DEBOUNCE_MS = 250;
/** One decoration type per colour, created once and reused. */
let decorationTypes = [];
/** The decoration for a `begin`/`end` whose counterpart is missing. */
let unmatchedType;
/** Whether the rainbow is on, per `vfmt.rainbowBeginEnd`. */
let rainbowEnabled = true;
@@ -64,15 +71,24 @@ function activate(context) {
client = new LanguageClient('vfmt', 'vfmt', serverOptions, clientOptions);
context.subscriptions.push(client);
// 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.
// Every colour is one this extension contributes, so every one of them has
// an opaque default in every theme kind: a theme that says nothing about
// `vfmt.rainbowN` gets our default, and a theme or user that overrides it
// gets what they asked for. Nothing here may ever be transparent — the
// rainbow colours code, it never hides it.
decorationTypes = Array.from({ length: RAINBOW_COLORS }, (_, index) =>
vscode.window.createTextEditorDecorationType({
color: new vscode.ThemeColor(`editorBracketHighlight.foreground${index + 1}`),
color: new vscode.ThemeColor(`vfmt.rainbow${index + 1}`),
}),
);
context.subscriptions.push(...decorationTypes);
// Half a pair has no nesting level and therefore no rainbow colour. It is
// still real text, so it is painted in the error colour rather than left
// undecorated: a `begin` that lost its `end` is exactly what the user wants
// to see.
unmatchedType = vscode.window.createTextEditorDecorationType({
color: new vscode.ThemeColor('vfmt.rainbowUnmatched'),
});
context.subscriptions.push(...decorationTypes, unmatchedType);
rainbowEnabled = readRainbowSetting();
@@ -147,6 +163,7 @@ async function paint(editor) {
const document = editor.document;
const askedAbout = document.version;
const buckets = decorationTypes.map(() => []);
const unmatched = [];
if (rainbowEnabled) {
let result;
try {
@@ -166,13 +183,22 @@ async function paint(editor) {
// 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];
// `depth` is a `u32` from our own server; a server that answered
// anything else would otherwise index the buckets with `NaN`.
const depth = Number.isInteger(pair.depth) && pair.depth >= 0 ? pair.depth : 0;
const ranges = buckets[depth % RAINBOW_COLORS];
ranges.push(asRange(pair.open), asRange(pair.close));
}
// A server older than this extension answers without the field; `|| []`
// is what lets that pairing keep the rainbow and simply skip the reds.
for (const range of (result && result.unmatched) || []) {
unmatched.push(asRange(range));
}
}
for (const [index, ranges] of buckets.entries()) {
editor.setDecorations(decorationTypes[index], ranges);
}
editor.setDecorations(unmatchedType, unmatched);
}
/** An LSP range (UTF-16, which is what the server advertises) as a VS Code one. */
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "vfmt",
"version": "0.3.0",
"version": "0.3.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vfmt",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+74 -2
View File
@@ -2,7 +2,7 @@
"name": "vfmt",
"displayName": "vfmt — Verilog/SystemVerilog",
"description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the vfmt language server.",
"version": "0.3.0",
"version": "0.3.1",
"publisher": "REPLACE-ME",
"license": "MIT",
"repository": {
@@ -57,6 +57,78 @@
"path": "./snippets/systemverilog.json"
}
],
"colors": [
{
"id": "vfmt.rainbow1",
"description": "begin/end nesting level 1 (and every 6th level below it).",
"defaults": {
"dark": "#FFD700",
"light": "#0431FA",
"highContrast": "#FFD700",
"highContrastLight": "#0431FA"
}
},
{
"id": "vfmt.rainbow2",
"description": "begin/end nesting level 2 (and every 6th level below it).",
"defaults": {
"dark": "#DA70D6",
"light": "#319331",
"highContrast": "#DA70D6",
"highContrastLight": "#319331"
}
},
{
"id": "vfmt.rainbow3",
"description": "begin/end nesting level 3 (and every 6th level below it).",
"defaults": {
"dark": "#179FFF",
"light": "#7B3814",
"highContrast": "#87CEFA",
"highContrastLight": "#7B3814"
}
},
{
"id": "vfmt.rainbow4",
"description": "begin/end nesting level 4 (and every 6th level below it).",
"defaults": {
"dark": "#87D96B",
"light": "#0E7490",
"highContrast": "#87D96B",
"highContrastLight": "#0E7490"
}
},
{
"id": "vfmt.rainbow5",
"description": "begin/end nesting level 5 (and every 6th level below it).",
"defaults": {
"dark": "#FF8C69",
"light": "#6D28D9",
"highContrast": "#FF8C69",
"highContrastLight": "#6D28D9"
}
},
{
"id": "vfmt.rainbow6",
"description": "begin/end nesting level 6 (and every 6th level below it).",
"defaults": {
"dark": "#4FD6D6",
"light": "#BE185D",
"highContrast": "#4FD6D6",
"highContrastLight": "#BE185D"
}
},
{
"id": "vfmt.rainbowUnmatched",
"description": "A begin/end or fork/join keyword whose counterpart is missing.",
"defaults": {
"dark": "#FF1212",
"light": "#B30000",
"highContrast": "#FF1212",
"highContrastLight": "#A80000"
}
}
],
"configuration": {
"title": "vfmt",
"properties": {
@@ -68,7 +140,7 @@
"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."
"markdownDescription": "Colour each nesting level of `begin`/`end` and `fork`/`join` a different colour, and a keyword whose counterpart is missing in an error colour. Every colour is a `vfmt.rainbow*` theme colour you can override in `workbench.colorCustomizations`. Takes effect immediately."
},
"vfmt.lineLength": {
"type": [
+29
View File
@@ -72,6 +72,11 @@ const SOURCE = [
'',
].join('\n');
// The same file with the outer `end` taken away: the half-pair the extension
// paints in its error colour, which is the other half of the rainbow contract.
const BROKEN = SOURCE.replace(' end\n end\n', ' end\n');
const brokenUri = `file://${process.cwd()}/smoke_scratch_broken.sv`;
server.stdin.end(
Buffer.concat([
frame({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { processId: process.pid, rootUri: null, capabilities: {} } }),
@@ -82,6 +87,12 @@ server.stdin.end(
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',
method: 'textDocument/didOpen',
params: { textDocument: { uri: brokenUri, languageId: 'systemverilog', version: 1, text: BROKEN } },
}),
frame({ jsonrpc: '2.0', id: 5, method: 'vfmt/scopePairs', params: { textDocument: { uri: brokenUri } } }),
// The settings push, in exactly the shape `synchronize.configurationSection:
// 'vfmt'` produces — the whole section, defaults included.
frame({
@@ -154,6 +165,24 @@ server.on('close', (code) => {
if (half.end.character <= half.start.character) fail(`empty range in ${JSON.stringify(pair)}`);
}
}
// A balanced buffer still carries the field, empty: that is what clears the
// error decoration once the user finishes typing the missing `end`.
if (!Array.isArray(scopePairs.result.unmatched) || scopePairs.result.unmatched.length !== 0) {
fail(`a balanced buffer must report no unmatched keywords, got ${JSON.stringify(scopePairs.result.unmatched)}`);
}
// ... and the buffer missing its outer `end` reports that `begin`, so the
// extension can paint it rather than leave it undecorated.
const broken = messages.find((m) => m.id === 5);
if (!broken) fail('no vfmt/scopePairs response for the broken buffer');
if (broken.error) fail(`vfmt/scopePairs failed: ${JSON.stringify(broken.error)}`);
const unmatched = broken.result && broken.result.unmatched;
if (!Array.isArray(unmatched) || unmatched.length !== 1) {
fail(`expected one unmatched keyword, got ${JSON.stringify(unmatched)}`);
}
if (unmatched[0].start.line !== 2 || unmatched[0].start.character !== 10) {
fail(`expected the unclosed begin at 2:10, got ${JSON.stringify(unmatched[0])}`);
}
// The settings the extension pushes actually reach the formatter.
const formatting = messages.find((m) => m.id === 4);
+10 -10
View File
@@ -61,9 +61,9 @@ recreated on every run.
```
dist/
vfmt-0.3.0-aarch64-apple-darwin
vfmt-server-0.3.0-aarch64-apple-darwin
vfmt-0.3.0.vsix
vfmt-0.3.1-aarch64-apple-darwin
vfmt-server-0.3.1-aarch64-apple-darwin
vfmt-0.3.1.vsix
SHA256SUMS
```
@@ -111,11 +111,11 @@ npx @vscode/vsce package --out ../../dist/vfmt-<version>.vsix
```bash
# the CLI and the server: anywhere on PATH
install -m 755 dist/vfmt-0.3.0-aarch64-apple-darwin ~/.local/bin/vfmt
install -m 755 dist/vfmt-server-0.3.0-aarch64-apple-darwin ~/.local/bin/vfmt-server
install -m 755 dist/vfmt-0.3.1-aarch64-apple-darwin ~/.local/bin/vfmt
install -m 755 dist/vfmt-server-0.3.1-aarch64-apple-darwin ~/.local/bin/vfmt-server
# the editor extension: sideload, no marketplace involved
code --install-extension dist/vfmt-0.3.0.vsix
code --install-extension dist/vfmt-0.3.1.vsix
```
Publishing the artifacts is a matter of attaching `dist/`'s contents plus
@@ -123,8 +123,8 @@ Publishing the artifacts is a matter of attaching `dist/`'s contents plus
gate is green:
```bash
git tag -a v0.3.0 -m 'vfmt 0.3.0'
git push origin v0.3.0
git tag -a v0.3.1 -m 'vfmt 0.3.1'
git push origin v0.3.1
```
## Appendix — if the owner ever publishes to a marketplace
@@ -151,10 +151,10 @@ The commands themselves, once those exist:
# VS Code Marketplace: needs an Azure DevOps PAT for the publisher
npx @vscode/vsce publish -p "$VSCE_TOKEN"
# ... or publish an already-built package
npx @vscode/vsce publish --packagePath dist/vfmt-0.3.0.vsix -p "$VSCE_TOKEN"
npx @vscode/vsce publish --packagePath dist/vfmt-0.3.1.vsix -p "$VSCE_TOKEN"
# Open VSX (VSCodium, Gitpod, Cursor): needs an Eclipse Foundation account
npx ovsx publish dist/vfmt-0.3.0.vsix -p "$OVSX_TOKEN"
npx ovsx publish dist/vfmt-0.3.1.vsix -p "$OVSX_TOKEN"
```
Both tokens are secrets. Neither belongs in this repo, in a shell history, or