From 948f8a0b3200084962d27be16a496569b6914b55 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 19 Nov 2026 05:06:35 -0800 Subject: [PATCH] Release 0.65.3: comment keywords, and the brackets in comments explained MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §71.8. TODO, FIXME, FIX_ME and TBD inside // and /* */ comments are drawn bold in a new theme colour (lucisv.commentKeyword), as whole words and never in strings or code; lucisv.commentKeywords.custom adds the user's own words, .builtIn switches the four off, .caseSensitive ignores case, all live. Client-side editor decorations: commentScan.js finds comments with the grammar's own comment and string rules (0 mismatched lines against vscode-textmate over OpenTitan hw's 1 185 823 lines), commentKeywords.js matches literally over the visible lines only, with the block-comment state cached per document. The brackets sometimes coloured inside comments are VS Code's bracket-pair colourisation before background tokenization completes, not lucisv (grammar and semantic tokens measured clean); explained in the notes, not changed. Dev, QA (pass with findings, one fix round) and lead review are in docs/features/comment-highlighting/README.md. Not seen in a running editor. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.3) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree (20261119-050504), node 37/0. Co-Authored-By: Claude Mythos 5.2 --- CHANGELOG.md | 36 ++ Cargo.lock | 18 +- Cargo.toml | 2 +- docs/features/comment-highlighting/README.md | 630 +++++++++++++++++++ editors/vscode/.vscodeignore | 5 +- editors/vscode/CHANGELOG.md | 12 + editors/vscode/README.md | 21 +- editors/vscode/commentKeywords.js | 219 +++++++ editors/vscode/commentKeywords_test.js | 297 +++++++++ editors/vscode/commentScan.js | 236 +++++++ editors/vscode/commentScan_test.js | 244 +++++++ editors/vscode/extension.js | 7 + editors/vscode/package-lock.json | 4 +- editors/vscode/package.json | 36 +- tools/RELEASING.md | 3 +- 15 files changed, 1754 insertions(+), 16 deletions(-) create mode 100644 docs/features/comment-highlighting/README.md create mode 100644 editors/vscode/commentKeywords.js create mode 100644 editors/vscode/commentKeywords_test.js create mode 100644 editors/vscode/commentScan.js create mode 100644 editors/vscode/commentScan_test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f08ff8..7863876 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,42 @@ All notable changes to lucisv 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.65.3 — 2026-11-19 + +### Comment keywords, and the brackets in comments explained + +(`docs/features/comment-highlighting`; TODO §71.8.) + +- **`TODO`, `FIXME`, `FIX_ME` and `TBD` stand out inside comments.** In `//` + and `/* */` comments they are drawn bold in a new theme colour, + `lucisv.commentKeyword` — as whole words only (`TODO_reg` and `$TODO` are + left alone), and never in strings or code. +- **Your own words too.** `lucisv.commentKeywords.custom` adds words that are + highlighted the same way and only in comments (matched literally, up to 50 + words of 1–40 characters); `lucisv.commentKeywords.builtIn: false` turns the + four built-ins off, and `lucisv.commentKeywords.caseSensitive: false` + ignores case. Every change applies at once, with no reload. +- **It follows what the editor draws as a comment.** The extension finds + comments with the grammar's own comment and string rules; against VS Code's + real tokenizer that agreed on every one of the 1 185 823 lines of + OpenTitan's `hw` tree. It is client-side, so it paints while the language + server is still starting. +- **Cheap on big files.** Only the lines on screen (and 50 either side) are + searched for words; an edit above the screen re-reads the lines from the + edit down to it (7.9 ms at worst on a 100 000-line file). A file VS Code + itself does not tokenize (over 20 MiB or 300 000 lines) is not painted. +- **Brackets coloured inside comments: explained, not changed.** The `[]` of + a `signal[]` that sometimes lights up in a comment is VS Code's bracket-pair + colourisation, which ignores comments until it has finished tokenizing a + newly opened file in the background and then removes the colour itself. + lucisv's grammar and semantic tokens were measured to colour nothing inside + a comment (309 OpenTitan files, and the large-file path). An extension + cannot change that behaviour short of switching bracket colours off for the + whole language, code included — which stays your choice + (`editor.bracketPairColorization.enabled`, or `colorizedBracketPairs` + under `[systemverilog]`). +- **Not yet seen in a running editor by a human**: the tests are headless. + ## 0.65.2 — 2026-11-19 ### The Hierarchy pane shows where you are diff --git a/Cargo.lock b/Cargo.lock index 34d30f2..7e25253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.2" +version = "0.65.3" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.2" +version = "0.65.3" [[package]] name = "lucisv_mcp" -version = "0.65.2" +version = "0.65.3" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.2" +version = "0.65.3" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.2" +version = "0.65.3" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.2" +version = "0.65.3" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.2" +version = "0.65.3" [[package]] name = "vlog_refactor" -version = "0.65.2" +version = "0.65.3" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.2" +version = "0.65.3" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 21071e5..189d997 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.2" +version = "0.65.3" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/docs/features/comment-highlighting/README.md b/docs/features/comment-highlighting/README.md new file mode 100644 index 0000000..f655fc4 --- /dev/null +++ b/docs/features/comment-highlighting/README.md @@ -0,0 +1,630 @@ +# comment-highlighting + +## Goal + +The owner (TODO §71.8): "Sometimes there is syntax highlighting in the +comment. Like a signal with bracket like signal[]. I saw the [] are getting +highlighted. Not needed. But there is one thing that is needed: please +highlight the TODO, FIXME, FIX_ME, TBD in the comment. Also give the user an +option to highlight a custom word that is specifically in the comment." + +Two parts. **Part 1** finds out why `[]` inside a comment is ever coloured, and +fixes whatever of that is lucisv's. **Part 2** paints `TODO`, `FIXME`, `FIX_ME` +and `TBD` — and any words the user lists in `lucisv.commentKeywords.custom` — in +a bold theme colour wherever they appear as whole words inside `//` or `/* */` +comments, and nowhere else. + +### Part 1 — why `[]` inside a comment gets coloured + +The colour on `[]` is VS Code's **bracket pair colourisation** +(`editor.bracketPairColorization.enabled`, on by default), which colours every +pair from `language-configuration.json`'s `brackets` — unless the token under +the bracket is not `StandardTokenType.Other`. Three candidate causes were +checked; **neither lucisv's server nor its grammar is the cause. The colour +comes from one VS Code state in which the grammar's comment scopes are not +consulted at all**, which an extension cannot change. **Part 1 is an +explanation, not a fix: there is no fix in the extension's power** that does +not also take bracket colours away from code (see the mitigations below). + +**How VS Code decides (verified against `microsoft/vscode` `main`, 2026-11-19).** + +- `bracketPairsTree/tokenizer.ts`, `NonPeekableTextBufferTokenizer.read()`: + a bracket is a bracket only when + `TokenMetadata.getTokenType(tokenMetadata) === StandardTokenType.Other` and + the token's balanced-bracket bit is set; the metadata comes from + `textModel.tokenization.getLineTokens(...)`. A comment token + (`comment.*` scope → `StandardTokenType.Comment`) never yields a bracket. + `FastTokenizer`, in the same file, reads **no token metadata**: it runs one + regex over the whole text and treats every match as a bracket. +- `bracketPairsTree/bracketPairsTree.ts`, constructor: when the model has no + tokens yet it builds `initialAstWithoutTokens` with `FastTokenizer`; when + background tokenization is still in progress it builds it from the buffer's + current tokens (untokenized lines are one `Other` token each). Every + colourising query reads `this.initialAstWithoutTokens || this.astWithTokens`, + token-only changes **never update** `initialAstWithoutTokens` + (`handleEdits(…, tokenChange)` skips it), and it is cleared only in + `handleDidChangeBackgroundTokenizationState` once the state is + `BackgroundTokenizationState.Completed`. +- `TextMateTokenizationSupport.tokenizeEncoded` (read from VS Code 1.145.2's + shipped `workbench.desktop.main.js` and its tokenization worker): + `line.length >= maxTokenizationLineLength ? nullTokenizeEncoded(languageId, + state) : …` — a line at least `editor.maxTokenizationLineLength` (default + 20 000) characters long is one `Other` token and carries the state across + unchanged. **That token has no balanced-bracket bit** (`nullTokenize.ts`; + QA's reading of the 1.145.2 bundle: `(s<<0|0|0|32768|2<<24)>>>0`, no `1024`, + where the store default for a not-yet-tokenized line has it), so once such a + line is tokenized its brackets are not colourised at all — in code or in + comments. +- `semanticTokensProviderStyling.ts`, `getMetadata`: semantic tokens set only + font-style and foreground bits (plus the matching `SEMANTIC_USE_*` flags); + **never the token-type bits**. So no semantic token can make a bracket + in a comment coloured, or one in code uncoloured. + +**So `[]` in a comment is coloured exactly when the file was just opened, +until background tokenization finishes.** The first AST is token-blind, and +stays in charge until the whole file has been tokenized — on a multi-megabyte +file that takes visibly long, which matches "sometimes". Then the colours in +comments disappear by themselves. (A variant of the same mechanism, from QA: +after an edit opens or closes a `/*` above, the lines below keep their old +tokens until the background tokenizer reaches them again, so their brackets may +briefly keep or lose colour.) + +*Corrected after QA F1:* the first version of this README named a second case, +lines of `editor.maxTokenizationLineLength` or more. That was wrong: such a +line's null token lacks the balanced-bracket bit, so after tokenization its +brackets are not coloured at all; it is coloured only during the same +token-blind phase as every other line. + +Bracket colourisation is off entirely above 5 000 000 characters +(`bracketPairsImpl.ts`, `canBuildAST`), and tokenization above 20 MiB or +300 000 lines (`textModel.ts`, `_isTooLargeForTokenization`), so neither of +those is another case. + +**Mitigations considered, none adopted:** + +- `balancedBracketScopes`/`unbalancedBracketScopes` on the grammar + contribution: no help — they only set the balanced-bracket bit on TextMate + tokens, and the token-blind tree reads no tokens. +- `colorizedBracketPairs: []` in `language-configuration.json` (QA's note): + it would remove the colouring in comments, but it also removes every + bracket-pair colour in code, for every user. A net loss, and the owner's + call, not this lane's. A user who wants it can set + `"[systemverilog]": { "editor.language.colorizedBracketPairs": [] }` (and the + same for `[verilog]`) themselves. +- Decorations repainting brackets in comments with the comment colour: there + is no theme colour for the theme's comment token colour, and it would + compete with VS Code's own bracket decorations. +- `editor.bracketPairColorization.enabled` via `configurationDefaults`: the + user's switch, not ours to flip. lucisv cannot shorten VS Code's background + tokenization either. + +**What was ruled out, with evidence (one-off scripts, 2026-11-19).** + +- **The TextMate grammar.** Run through the real `vscode-textmate` 9.3.2 and + `vscode-oniguruma` 1.7.0 that VS Code 1.145.2 ships (extracted from its + `node_modules.asar` into a scratch directory; not a dependency of anything + here), compared per character against the server's own `comment` semantic + tokens, on 309 OpenTitan files (every 13th of `hw/`, 69 249 lines): + **0 characters the lexer calls comment that the grammar does not**, so in the + steady state every bracket the lexer considers commented-out is uncoloured. + The other direction has 39 lines — comments inside a `` `define `` body or + inside a macro call's arguments (`` `DV_SPINWAIT(… // …) ``), which the lexer + keeps as macro text and the grammar (rightly, visually) shows as comment. + Neither direction colours a bracket in something that looks like a comment. + Every comment form the brief named is scoped: `//` after a macro or a + `` `ifdef ``, `/* */` across lines, comments after directives; `(* *)` is + correctly *not* a comment (it is an attribute, and its parentheses are code). +- **Server semantic tokens.** In the same run (`semanticTokens/full`): **0 + non-`comment` semantic tokens start inside a comment**, by the lexer's spans + or by the grammar's. Repeated through the large-file window path + (`semanticTokens/range` on one 12 MB, 357 172-line concatenation of 1 500 + OpenTitan files, so `semantic_tokens_in_window` answers): again 0. The + server only ever emits tokens from lexer tokens, whose comments are trivia, + and from `instantiation::overrides`, keyed by syntax-tree token starts. + Nothing to fix in `crates/lucisv_server/src/tokens*`, so no Rust changed. +- **lucisv's own rainbow.** It paints only `begin`/`end`/`fork`/`join` ranges + from `pairs.rs`, computed over `Document.tokens` (comments excluded) — never + a bracket. + +One divergence between the grammar and the lexer was found and is **not** the +reported problem: an escaped identifier containing `//` (`\a//b `) is an +identifier to the lexer and a line comment to the grammar. It is filed under +Status / TODO as a follow-up. + +### Part 2 — mechanism, and why + +**Editor decorations for every word** (option (b) of the brief), in two new +modules: `commentScan.js` (pure — where the comments are, which words match) +and `commentKeywords.js` (the VS Code wiring). Considered and rejected: + +- *(a) TextMate patterns for the built-ins, decorations for custom words.* Two + mechanisms painting the same thing in two different ways: a TextMate scope is + coloured by the theme's `tokenColors`, which most themes do not define for a + TODO scope, so the built-ins would look different from the custom words, and + a `contributes.colors` default cannot reach a TextMate scope. Turning the + built-ins off would also need a grammar the user cannot edit. +- *(c) A server-side semantic-token modifier.* Splits every comment token, + colours through `semanticTokenColors`/`semanticTokenScopes` rather than a + contributed colour (so no guaranteed visible default), is Rust outside this + lane's mandate, and the server would have to learn the words. + +Decorations give one colour id (`lucisv.commentKeyword`, contributed with +opaque defaults for all four theme kinds), apply to built-in and custom words +identically, and re-read settings in the extension host without a round trip. + +**Comment detection agrees with the grammar, by construction and by +measurement.** The grammar decides "comment" with exactly two rules +(`//.*`; `/\*` … `\*/`, multi-line) and hides them with one (a string, `"` … +`"` or end of line, `\\.` escapes). Every other top-level rule (directives, +macros, system tasks, numbers, keywords) is built only of characters that can +never be `/` or `"`, so it can neither swallow nor reveal a comment start — +`commentScan.js` mirrors those three rules and nothing else, and +`commentScan_test.js` pins them: the comment and string rules must deep-equal +what the scanner mirrors, and no other top-level rule may contain `/`, `"`, +`.`, `[^`, `\S`, `\W`, `\D` or `\N`. Measured against the real tokenizer +(the extracted `vscode-textmate`, as above) over **all 4 029 OpenTitan `hw` +files, 1 185 823 lines, 39.3 M characters, 8.39 M of them comment: 0 lines +where the scan and the grammar disagree on a single character**, plus a table +of 20 hand-written edge lines (strings holding `//` and `/*`, escaped quotes, +an escaped backslash before the closing quote, a backslash at end of line, an +unterminated string, `/*/`, `/**/`, `/***/`, `` `define `` with a trailing +comment, `` `ifdef `` with one, `(* *)`, an escaped identifier). The pictures +in the scanner test's comment table are copied from that tokenizer's output, +not hand-counted. + +Why the grammar's notion and not the lexer's: the keyword is meant to stand out +where the user *sees* a comment, and what they see is the grammar (the server's +`comment` semantic token covers a subset of it — see Part 1). Matching the +lexer instead would leave a `TODO` inside a `` `define `` body's `//` comment +unpainted although it is drawn as a comment. + +**Cheap on big files.** Only the visible ranges plus 50 lines either side are +scanned for words. Whether a line starts inside a block comment is kept per +document (`LineStates`), computed lazily from the top and truncated from the +first edited line down — so typing re-scans nothing above the edit, scrolling +re-scans nothing it has already passed, and the first paint at the bottom of a +file reads each line above it once (`indexOf`-driven, no tokenizer). **An edit +above the viewport does re-walk every line from the edit down to the +viewport** (state only, no word matching): QA measured, on a fake +100 000-line document, first paint at the bottom 12.3 ms / 100 000 reads, +repaint 0.17 ms / 110 reads, edit at the top while viewing the bottom +7.9 ms / 100 000 reads, edit in the middle 3.3 ms / 50 000 reads, edit inside +the viewport 0.10 ms / 110 reads (the fake understates `lineAt`'s real cost). +Edits are debounced 100 ms. A line of `editor.maxTokenizationLineLength` or +more — read with the document as scope, so a `[systemverilog]` override counts +— is skipped and carries the state across, exactly as VS Code does, and a +megabyte-long netlist line is never scanned. A file VS Code does not tokenize +at all (with `editor.largeFileOptimizations` on: more than 20 MiB of text or +more than 300 000 lines) is not painted at all; VS Code makes that decision +once per model and so does this, on a document's first paint. So the +highlight appears only where VS Code draws comment colour. + +## Assumptions + +- The grammar file is the one in `syntaxes/` and no other extension's grammar + replaces it for `verilog`/`systemverilog`. With another grammar active, the + scan may disagree with what is drawn. +- VS Code draws a decoration's `color` over the token colour (both semantic and + TextMate). This is how decoration colours have always rendered; not verified + in a running editor here. +- "Whole word" means `\b`-style boundaries with `$` counted as a word character + (Verilog identifiers contain `$`): a word that starts with `[A-Za-z0-9_$]` + must not have one just before it, and one that ends with one must not have + one just after. So `TODO` skips `TODO_reg`, `myTODO`, `$TODO`, `TODO1`, and + `REVIEW:` matches in `REVIEW:x`. The word characters are **ASCII only** + (`[A-Za-z0-9_$]`, Verilog's identifier set): a custom word that starts or + ends with a non-ASCII letter has no boundary on that side, so `ÄNDERN` lights + inside `fooÄNDERN` (QA F5; as designed, not changed). +- A string continued with backslash-newline ends, to the grammar, at the end + of its line (`"|$`), so the continuation line is code and a `// TODO` on it + is painted — which matches what is drawn (QA F7; by design). +- Words are matched only in a comment's **body** — never across its own `//`, + `/*` or `*/` — so a custom word made of `*` or `/` cannot light up a + delimiter. +- Editor background colours of the built-in themes used for the contrast test: + Dark Modern `#1F1F1F`, Dark+ `#1E1E1E`, Light Modern/Light+ `#FFFFFF`, HC Dark + `#000000`, HC Light `#FFFFFF`. A comment line with the current-line highlight + or a selection behind it is not measured. + +### Decisions the brief asked for + +- **Can the built-in four be removed?** All together, yes: + `lucisv.commentKeywords.builtIn: false`. Individually, no — that is a list + edit with no use case named; anyone who wants two of them turns the built-ins + off and lists those two in `custom`. The custom list is **additive** (default + `[]`), so adding a word never silently loses the built-ins — which is what + would happen if the four were the array's default, because VS Code replaces + an array setting rather than merging it. +- **Regex metacharacters** are matched literally: every word goes through + `escapeRegExp` before it joins the alternation; nothing a user types is ever + interpreted as a pattern. +- **No catastrophic patterns**: the matcher is an alternation of escaped + literals, longest first, each wrapped in at most one one-character lookbehind + and one one-character lookahead — no quantifiers at all. The test runs the + worst the caps allow (50 near-identical 40-character words of `a`) over a + 19 993-character comment of `a` and requires it under 2 s; it takes ~4 ms. +- **Caps**: at most 50 custom words (entries past the 50th are ignored), each + 1–40 characters with no whitespace. An unusable entry — empty, too long, + containing whitespace, not a string — is skipped, and one line + (`lucisv: lucisv.commentKeywords.custom: ignored N entries (…)`) goes to the + lucisv output channel. The `package.json` schema says the same + (`minLength`, `maxLength`, `pattern: ^\S+$`, `maxItems`, `uniqueItems`), so + the settings editor warns before the extension has to. +- **Case**: case-sensitive by default (`todo` in prose stays plain); a boolean, + `lucisv.commentKeywords.caseSensitive`, makes it insensitive — it costs one + regex flag, so it is offered. Duplicates are dropped case-insensitively then. + +## Handshakes + +- **Consumes** `syntaxes/systemverilog.tmLanguage.json`'s `comments` and + `strings` rules and the shape of every other top-level rule. **Promise to + whoever edits the grammar:** `commentScan_test.js` fails on any change to + those two rules, on a reordering that moves them off the top, and on any + other top-level rule that could match `/` or `"`; update `commentScan.js` in + the same change. The Rust keyword test (`crates/lucisv_server/tests/grammar.rs`) + is untouched — the grammar did not change. +- **Consumes** `editor.maxTokenizationLineLength` (per document, language + overrides included) and `editor.largeFileOptimizations` (read, never + written). +- **Provides** the settings `lucisv.commentKeywords.builtIn`, + `lucisv.commentKeywords.custom`, `lucisv.commentKeywords.caseSensitive` and + the colour `lucisv.commentKeyword`. The server receives them in + `workspace/didChangeConfiguration` with the rest of `lucisv` and ignores them + (it only reads named keys; checked in `settings.rs`). +- **extension.js**: one `require` and one construction in `activate`, after the + rainbow's decoration types; the module pushes its decoration type and every + listener (including `onDidOpenTextDocument`, for language-mode changes) into + `context.subscriptions`. It needs nothing from the server. +- **Packaging**: `commentKeywords.js` and `commentScan.js` are runtime modules + (listed in `tools/RELEASING.md`'s runtime-module sentence and the + `.vscodeignore` header); their two `*_test.js` files are excluded. +- No Handshake requests to other lanes: nothing outside this lane's file list + needed changing. + +## Status / TODO + +- [x] Part 1: find the cause of the bracket colouring, with evidence + (VS Code's token-blind first AST and over-long lines; server and grammar + cleared, measured). +- [x] Part 1: fix what is lucisv's — nothing is; no grammar or Rust change. +- [x] `commentScan.js`: grammar-equivalent comment scan, literal whole-word + matcher, settings normalization with caps, incremental line states. +- [x] `commentKeywords.js`: decorations on visible ranges, debounced edits, + immediate setting changes, `maxTokenizationLineLength` honoured. +- [x] `package.json`: three settings, one colour (one dot in its id). +- [x] Tests: `commentScan_test.js` (14), `commentKeywords_test.js` (11 after + the QA round, incl. the contrast check). +- [x] Agreement with the real `vscode-textmate` over all of OpenTitan `hw` + (one-off; recorded above). +- [x] README (extension), `.vscodeignore`, `tools/RELEASING.md`. +- [ ] Follow-up, not in this lane: the grammar has no rule for escaped + identifiers, so `\a//b ` is drawn as a comment from `//` on, and — + worse — `\a/*b ` opens a block comment that runs to the next `*/`, + possibly many lines down (QA F6). A `\\\S+` rule ahead of `#comments` + would fix both — but it changes the scan's mirrored rules too, so it goes + with a `commentScan.js` change. +- [x] QA fix round (F1–F7), see work log. +- [ ] Seen in a running VS Code (cannot be done by the dev agent — see the QA + checklist in the work log). + +## Work log + +### 2026-11-19 — dev (Opus 5.5) + +- Read the grammar, `language-configuration.json`, `tokens.rs`, the rainbow + wiring. The rainbow only paints `begin`/`end`/`fork`/`join`; the server's + semantic tokens never include punctuation except the instantiation `#` + overrides. +- Verified VS Code's bracket colourisation against `microsoft/vscode` `main` + (`bracketPairsTree/tokenizer.ts`, `bracketPairsTree.ts`, + `bracketPairsImpl.ts`, `textModel.ts`, `semanticTokensProviderStyling.ts`) + and the installed 1.145.2 bundle (`maxTokenizationLineLength`, `>=`). +- Built `lucisv-server` (debug) in this worktree and wrote two one-off scripts + in the session scratchpad (not shipped): `compare.js` (grammar via the real + `vscode-textmate` vs the server's semantic tokens, over LSP stdio) and + `agree.js` (`commentScan.js` vs the real tokenizer). Numbers in Goal. Every + run went through `tools/guard.sh`. +- Decision: no grammar change, no Rust change (Part 1 found nothing of + lucisv's to fix). Decorations for all words (Part 2), detection mirroring the + grammar rather than the lexer, explained in Goal. +- Words match in a comment's body only, after a test showed a custom `*/` word + lighting the comment's own delimiter. Word boundaries changed from "neither + neighbour is a word character" to `\b`-style per word edge, so a word ending + in punctuation (`REVIEW:`) still matches before a letter. +- The window scan records each line's successor state while it scans it, so a + paint reads each window line once (the visible-range test counts reads: + 450 above + 121 in the window, then 121 on a repaint). +- **What a human should look at in VS Code** (the dev cannot see a running + editor): + 1. A `.sv` file with `// TODO: x`, `/* FIXME */`, `// FIX_ME TBD`, a + three-line `/* … TODO … */`, `"// TODO"` in a string, `TODO_reg` in code: + the four in comments are bold orange (Dark Modern and Light Modern), the + string and the identifier are not. + 2. Add `"lucisv.commentKeywords.custom": ["XXX", "a.b"]` in settings.json: + `XXX` lights at once, `a.b` lights but `axb` does not — no reload. + `"builtIn": false` removes the four at once; `"caseSensitive": false` + lights `todo`. + 3. Type `/*` at the top of a file: every TODO below lights up after a beat; + delete it: they go back. + 4. Open a multi-MB OpenTitan-sized file and scroll to the end: the keywords + appear as you scroll, typing stays smooth. + 5. Part 1, the cause: open a large `.sv` (a few MB) with `x[3:0]` in + comments and watch the brackets inside comments lose their colour once + tokenization finishes (a few seconds). If they **stay** coloured on a + normal-length line after that, Part 1's conclusion is wrong — check + *Developer: Inspect Editor Tokens and Scopes* on the bracket and report the + scope and which extension provides the grammar. + 6. `workbench.colorCustomizations: { "lucisv.commentKeyword": "#FF0000" }` + recolours them. + +### 2026-11-19 — dev (Opus 5.5), QA fix round + +- **F1**: Part 1 now names one cause only (the token-blind tree until + background tokenization completes); the long-line case is struck with the + reason (null token, no balanced-bracket bit) and a "corrected after QA" + note. Stated plainly that Part 1 is an explanation with no fix in the + extension's power; mitigations listed, including QA's + `colorizedBracketPairs: []` (not adopted: it removes bracket colour in code + too). Changelog paragraph corrected. +- **F2**: `commentKeywords.js` reads `editor.maxTokenizationLineLength` with + the document as scope; each document's record keeps the cutoff its states + were computed with and starts over when it changes (so the configuration + handler no longer clears a global cache). Test: a `[systemverilog]` override + applies to the `.sv` document and not to a `verilog` one, and dropping it + recomputes. +- **F3**: verified in `src/vscode-dts/vscode.d.ts` (`main`, 2026-11-19): + `onDidOpenTextDocument`/`onDidCloseTextDocument` fire "when the language id of + a text document has been changed", `setTextDocumentLanguage` "will trigger the + onDidCloseTextDocument event followed by the onDidOpenTextDocument event", + and the open "is emitted before the document is updated in the active text + editor" — so the open handler repaints on the next tick. A non-Verilog editor + this module painted is cleared; one it never painted is never touched. Test + with the stub: `.sv` → plaintext clears, back → paints without scroll/edit. + The rainbow in `extension.js` has the same pre-existing gap (QA noted it); + not changed here — it is outside this feature. +- **F4**: wording fixed (here and in the extension README). Files VS Code does + not tokenize (`editor.largeFileOptimizations` on and > 20 MiB of text — + `offsetAt` of the end, UTF-16 units, as `getValueLength` counts — or + > 300 000 lines) are not painted; decided once per document. Tests: 300 001 + lines, 20 MiB + 1, exactly 20 MiB (painted), and the option off (painted). +- **F5, F7**: documented as by design under Assumptions. **F6**: the + escaped-identifier follow-up names `\a/*b`. + +### Changelog paragraph (for the lead) + +**Comment keywords.** `TODO`, `FIXME`, `FIX_ME` and `TBD` inside `//` and +`/* */` comments are now bold, in a new `lucisv.commentKeyword` theme colour — +as whole words, never in strings or code. `lucisv.commentKeywords.custom` adds +your own words (matched literally, up to 50), `lucisv.commentKeywords.builtIn` +turns the four off and `lucisv.commentKeywords.caseSensitive` makes matching +case-insensitive; every change applies immediately. Only the lines on screen +are searched for the words (an edit above the screen re-reads the lines down +to it), and a file too large for VS Code to tokenize is not painted. Brackets +that are sometimes coloured inside comments come from VS Code's bracket-pair +colourisation while a newly opened file has not finished tokenizing, not from +lucisv — its grammar and semantic tokens were measured to colour nothing +inside a comment — and the colours go once tokenization completes; there is no +extension-side fix that would not also remove bracket colours in code. + +## QA log + +### 2026-11-19 — QA (Opus 5.5) + +**Verdict: PASS WITH FINDINGS.** Part 2 (the code) holds up under every +attack below. One Part 1 claim (case 2, over-long lines) is wrong against +VS Code's source and the shipped 1.145.2 bundle (F1, documentation only: the +code does the right thing anyway). Three low findings, three informational. + +**Commands and results** + +- `node --test editors/vscode/*_test.js`: 34 files, 34 pass, 0 fail. + `commentScan_test.js` has 14 tests and `commentKeywords_test.js` 8, as + claimed. `node --check` is clean on `commentScan.js`, `commentKeywords.js`, + `extension.js` and both tests. `package.json` parses, `version` is `0.65.2`. +- Scope: `git status --untracked-files=all` lists only `editors/vscode/*`, + `tools/RELEASING.md` and `docs/features/comment-highlighting/`. +- `npx --no-install @vscode/vsce ls --no-dependencies`: ships + `commentKeywords.js` and `commentScan.js`; nothing matching `_test` or + `smoke` ships. +- Reproduced the dev's full-corpus number myself: + `tools/guard.sh -m 4 -t 600 -- node agree.js … all.txt` printed + `{"docs":4029,"lines":1185823,"chars":39294203,"commentChars":8391566,"mismatchedLines":0}`. + On the scripts: `agree.js` is a sound per-character comparison of + `scanLine` chained across lines against the real `vscode-textmate`, so it + does prove agreement with the grammar on OpenTitan. It does not exercise + `LineStates`, edits or `maxLineLength`; my `prop_edit.js` covers those. + `compare.js` (server vs grammar) checks only where non-comment semantic + tokens *start*. That is enough, because semantic tokens can never change + a bracket's token type anyway (confirmed: `getMetadata` sets only + font/foreground bits). Its usage line says `--window` but the code reads + `--range`. That is cosmetic. +- QA scripts (scratchpad `qa71/`, not shipped): `scan_attack.js` (82 crafted + lines vs `vscode-textmate`), `kw_attack.js` (matcher, settings, wiring, + perf), `prop_edit.js` (3 000 random edit/scroll rounds). + +**Part 1: VS Code source, checked independently** (`microsoft/vscode` +`main`, fetched 2026-11-19, plus the installed 1.145.2 +`workbench.desktop.main.js`). + +- Confirmed: `bracketPairsTree/tokenizer.ts:203-208` treats a bracket as a + bracket only if `getTokenType === StandardTokenType.Other` **and** + `containsBalancedBrackets(metadata)`. `FastTokenizer` (`:282`) reads no + tokens. `bracketPairsTree.ts:65-79` builds the token-blind + `initialAstWithoutTokens` when the model has no tokens yet, or from the + current tokens while background tokenization is in progress. + `:84-93` clears it only on `BackgroundTokenizationState.Completed`. Token + changes never update it (`:121`). Lines that are not tokenized yet get + `getDefaultMetadata` (`tokens/contiguousTokensStore.ts:247-256`), which + **does** set `BALANCED_BRACKETS_MASK`, so they produce brackets. Case 1 is + right. +- **F1 (medium, documentation): case 2 is wrong.** A line of + `maxTokenizationLineLength` or more is tokenized by `nullTokenizeEncoded` + (`tokenizationSupportWithLineLimit.ts:40-41`; the worker uses the same + wrapper, `textMateWorkerTokenizer.ts:108`). `nullTokenizeEncoded` + (`languages/nullTokenize.ts:22-31`) sets **no** `BALANCED_BRACKETS_MASK`. + The 1.145.2 bundle agrees: the long-line token is + `(s<<0|0|0|32768|2<<24)>>>0` with no `1024` bit, while the store default is + `…|2<<24|1024`. So once tokenization is complete, brackets on such a line + are **not colourised at all**, in code or in comments. They are coloured + only while case 1 applies, like every other line. Wrong text: + Goal/Part 1 items "2." (lines 63-65), "case 2 has none" (line 72), and the + changelog's "(or on a line too long to tokenize)" (line 323). The code is + unaffected: skipping those lines in `commentKeywords.js` still matches what + VS Code draws (no comment colour there). Suggested fix: drop case 2 and say + over-long lines get no bracket colours once tokenized. +- Missed transient (info): after an edit that opens or closes a `/*` above, + the lines below keep their old tokens until the background tokenizer + re-reaches them, so brackets there may briefly keep or lose colour. + This is the same mechanism as case 1, and transient. +- Mitigations in the extension's power: + - `balancedBracketScopes`/`unbalancedBracketScopes`: no help. They only set + the bit on TextMate tokens, and case 1 reads none. I agree with the dev. + - `colorizedBracketPairs: []` in `language-configuration.json`: it would + remove case 1's colouring in comments, but it also removes bracket-pair + colours in code for every user. That is a net loss and the owner's call, + not this lane's. (I did not read in detail how `FastTokenizer` derives + its pairs from `colorizedBracketPairs`. A user can get the same effect + with a `[systemverilog]` `editor.language.colorizedBracketPairs: []` + override.) + - Painting brackets inside comments with a decoration: not viable. There + is no ThemeColor for the theme's comment token colour, and it would + compete with the bracket decorations' CSS. + - `contributes.configurationDefaults`: not ours to flip + (`bracketPairColorization.enabled`). + +**Part 2: commentScan.js vs the real tokenizer** (`scan_attack.js`): +**82/82 lines agree**. Cases covered: `"//"` and `"/*"` in strings, `\"`, +`"a\\"`, a backslash at end of line (the string ends at `$`, so the next +line's `// TODO` is a comment, as the grammar draws it), a 32-line block, +`/*/`, `/**/`, `/***/`, `/* /* */`, `//` inside a block, `/*` inside `//`, +tabs, an unterminated block to EOF, `\a//b` and `\a/*b`, `` `define `` bodies +with both comment kinds, `(* *)`, `@(*)`, `@ (*)`, `(*)`, `a/ *b`, `a*/b`, +`a/*c*/d`, `a=b//c`, emoji and accents (UTF-16 columns line up), `"` inside +comments, `""`, `"\""`, `"\\""`, a stray `*/`, and the bare `//` `/*` `*/` `/` +`"` `\`. CRLF: VS Code hands `lineAt().text` without the EOL, so it is not a +case for the scanner (`agree.js` splits on `\r?\n` too). + +**Part 2: commentKeywords / matcher** (`kw_attack.js`): + +- Boundaries all as documented: `TODO:` `TODO(` `(TODO)` `TODO.` `//TODO` + `/*TODO*/` `\TODO` and `😀TODO😀` match. `TODOs` `TODO_x` `xTODO` `$TODO` + `TODO$` `TODO1` `FIX_ME_LATER` and `todo` (case-sensitive) do not. + `TODO` in a string or in code is not painted. +- Overlaps: the longest word wins at the same start (`FIX_ME` over `FIX`, + `TBD` over `TB`, `!!!` over `!!`). `FIX` alone never lights inside + `FIX_ME`. Matches never overlap (`a.b`/`b.c` on `a.b.c` gives `a.b`). +- Metacharacters are literal: `a.b` (not `axb`), `(x`, `[`, `\`, `^$`, `.*` + (not `hello`), `|`, `?`, `+`, `{2}`, `$`, `/`, `*`. The words `*/`, `*` and + `/` never light a delimiter. +- Junk: `''`, `'a b'`, `5`, `null`, 41 characters and an object are skipped + (6 counted). 40 characters is kept. Duplicates and a built-in repeated in + `custom` are dropped. 60 words give 50 used and 10 skipped. A non-array + `custom` gives the built-ins only (silently, with no log line: fine). + `caseSensitive:false` matches `todo`/`Todo` and dedupes case-insensitively. +- Wiring with a fake `vscode`: split views of one document each paint their + own ranges from shared states. Plain-text editors are untouched. + `builtIn:false` with an empty `custom` clears the decorations, and custom + words apply live. Disposing every subscription removes all five listeners + and disposes the decoration type (timer cleared). +- **Edit invalidation property** (`prop_edit.js`): 3 000 rounds of 1–3 + changes (replace, insert or delete lines made of `/*` `*/` `//` `"` `\` + `TODO` `(*` `😀` …) anywhere in a 400-line document, then a random + viewport, with `maxTokenizationLineLength` forced to 30 so the long-line + carry is exercised. Every paint was compared with a scan from line 0: + **0 mismatches**. +- **100 000-line document** (fake document, so `lineAt` cost is + understated). First paint at the bottom: 12.3 ms, 100 000 reads. Repaint: + 0.17 ms, 110 reads. Edit at top, viewing the bottom: 7.9 ms, 100 000 reads. + Edit in the middle: 3.3 ms, 50 000 reads. Edit in the viewport: 0.10 ms, + 110 reads. Edit at top, viewing the top: 0.12 ms, 111 reads. So word + matching is bounded by the viewport, but the state walk is bounded by + *(viewport bottom − first edited line)*, not by the viewport. That cost is + fine, but see F4. +- Contrast, computed independently (WCAG relative luminance): dark + `#FF9E3D` scores 8.01 on `#1F1F1F`, 8.11 on `#1E1E1E`, 7.45 on `#252526` + and 7.30 on `#002B36` (Solarized Dark). Light `#A85000` scores 5.51 on + white, 4.96 on `#F3F3F3` and 5.11 on `#FDF6E3`. HC `#FFA500` on black: + 10.63. HC-light `#9C4A00` on white: 6.19. All are ≥ 4.5. `lucisv.commentKeyword` + is spelled identically in `package.json:491`, `commentKeywords.js:15` and + the README. + +**Findings** + +- **F1 (medium, doc)**: see Part 1 above. +- **F2 (low)**: `commentKeywords.js:75` reads + `getConfiguration('editor').get('maxTokenizationLineLength')` with no + language scope. VS Code reads it per language + (`textMateTokenizationFeatureImpl.ts:305-310`, + `observableConfigValue('editor.maxTokenizationLineLength', languageId, …)`). + Repro: `"[systemverilog]": { "editor.maxTokenizationLineLength": 100 }`. + VS Code then stops drawing comments on lines of 100+ characters, but lucisv + still paints keywords there. A long line that opens `/*` also carries + a different block state below, so keywords below can be painted in code or + missed in comments. Fix: read it with the document as scope + (`getConfiguration('editor', document)`) and keep the cutoff per document's + states. +- **F3 (low)**: there is no handling of a language-mode change + (`commentKeywords.js:51-55`, `:110`). VS Code reports it as + close+open of the document, not as a visible-editors change. Switching a + Verilog editor to Plain Text leaves its keyword decorations in place + (`paintEditor` returns before clearing). Switching a `.txt` to + SystemVerilog paints nothing until the next scroll or edit. Reproduced with + the fake in `kw_attack.js`. The rainbow (`extension.js` `repaintVisible`) + has the same pre-existing gap. Fix: `onDidOpenTextDocument` → `paintVisible`, + and clear (`setDecorations([])`) for a non-target editor rather than + returning. +- **F4 (low, doc)**: two claims overstate. (a) "so the highlight never + appears where VS Code shows no comment" (Goal, line 163) does not hold for + files VS Code does not tokenize at all (> 20 MiB or > 300 000 lines, + confirmed in the 1.145.2 bundle, `LARGE_FILE_SIZE_THRESHOLD=20*1024*1024`, + `LARGE_FILE_LINE_COUNT_THRESHOLD=300*1e3`). There, lucisv paints keywords + in text drawn without comment colour, and the first paint walks every line + above the viewport. (b) The extension README's "Only the lines on screen + are scanned" leaves out that an edit above the viewport re-walks every line + from the edit down to the viewport (numbers above). Arguably both are + harmless behaviour, but the text should say it. +- **F5 (info)**: `WORD_CHAR` is ASCII, so a custom word starting or ending in + a non-ASCII letter has no boundary there (`ÄNDERN` lights inside + `fooÄNDERN`). This is consistent with the documented rule. +- **F6 (info)**: the escaped-identifier follow-up should also name `\a/*b`. + The grammar (and the scan) open a block comment there that runs to the next + `*/`, possibly many lines, which is worse than the `\a//b` case filed. +- **F7 (info)**: in a string continued with backslash-newline, the + continuation line is code to the grammar (the string ends at `$`), so a + `// TODO` on it is painted. It matches what is drawn, by design. + +**Fixed by QA**: `editors/vscode/commentScan_test.js`, the "no other +top-level grammar rule can match …" test. The banned escapes now also +include `\H` (Oniguruma non-hex, matches `/`), `\O`, `\X`, `\R`, `\P`, `\p`, +`\x`/`\u`/`\0` (code-point escapes that can spell `/` or `"`) and POSIX +`[[:`. None occurs in the grammar today (14/14 still pass). A mutated +grammar with `` `[a-zA-Z_\x2F]* `` now fails the test (checked in a scratch +copy). + +**Not verifiable without a running VS Code**: the decoration colour drawn +over semantic and TextMate colours, bold rendering, the real ext-host +`lineAt` cost on a multi-MB file, the language-change event sequence behind +F3 (inferred from the API, not observed), and the dev's QA checklist items +1–6 (especially 5: watching comment brackets lose colour once tokenization +completes). + +## Review + +**Lead, 2026-11-19.** Accepted for 0.65.3. + +- Half of the owner's item is an explanation, not a change, and the changelog + says so in those words. QA's F1 mattered: the dev's second cause was wrong + and I had already repeated it to the owner; corrected with them and here. + `colorizedBracketPairs: []` is not adopted — it would take bracket colours + out of code for everyone to fix a transient in comments. +- Decorations for all words (one colour, one switch) is the boring choice and + the right one. The scanner copies three grammar rules and a test pins that + no other rule can match `/` or `"`; QA tightened that pin. The corpus + agreement run (4 029 files, 0 lines) was reproduced by QA, not just quoted. +- Fix round verified by re-running the suite: 37 tests, 37 pass. `extension.js` + wiring read: the client exists before the closure can be called. +- Owed to a human: that the decoration draws over the comment colour, and the + Part 1 observation itself (work log checklist, item 5). +- Follow-ups left open on purpose: the escaped-identifier grammar mismatch + (`\a//b `, `\a/*b`), and the same language-mode gap in the `begin`/`end` + rainbow in `extension.js`. diff --git a/editors/vscode/.vscodeignore b/editors/vscode/.vscodeignore index 896bb14..e8a54c8 100644 --- a/editors/vscode/.vscodeignore +++ b/editors/vscode/.vscodeignore @@ -1,6 +1,7 @@ # The checks are pre-publish/developer checks, not part of the shipped # extension. `restart.js`, `typing.js`, `mcp.js` and the `hierarchy*`/`references*` modules -# themselves ARE shipped — `extension.js` requires them. +# themselves ARE shipped — `extension.js` requires them. So are `commentKeywords.js` +# and `commentScan.js`. smoke.js mcp_smoke.js mcp_test.js @@ -15,5 +16,7 @@ referencesModel_test.js referencesView_test.js typing_test.js semanticTokens_test.js +commentScan_test.js +commentKeywords_test.js .vscode/** .gitignore diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 2199276..bec4058 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,18 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.65.3 — 2026-11-19 + +- **`TODO`, `FIXME`, `FIX_ME` and `TBD` are highlighted inside comments** — + bold, in the new `lucisv.commentKeyword` theme colour, as whole words, never + in strings or code. +- **Add your own comment words** with `lucisv.commentKeywords.custom`; turn the + built-in four off with `lucisv.commentKeywords.builtIn`, ignore case with + `lucisv.commentKeywords.caseSensitive`. Changes apply immediately. +- **About brackets coloured inside comments:** that is VS Code's bracket-pair + colouring while a freshly opened file is still being tokenized; it clears by + itself, and lucisv colours nothing inside a comment. + ## 0.65.2 — 2026-11-19 - **The Hierarchy pane shows where you are.** The rows leading to the file you diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 039e8fd..eba759e 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.65.2**. Its platform packages include +The current release is **0.65.3**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -171,6 +171,7 @@ enabling both paths formats twice. | TextMate highlighting | Covers keywords, comments, strings, literals, system tasks, directives, and macros before the server starts and inside previews/hover cards | | Rainbow scopes | Six theme-aware colors distinguish nested `begin`/`end` and `fork`/`join` pairs; unmatched scopes use a seventh error color | | Matching scopes | Putting the cursor on an opener highlights the exact matching closer | +| Comment keywords | `TODO`, `FIXME`, `FIX_ME` and `TBD` inside `//` and `/* */` comments are painted bold in the `lucisv.commentKeyword` theme colour — whole words only, never in strings or code. Add your own words with `lucisv.commentKeywords.custom` (matched literally, as whole words); `lucisv.commentKeywords.builtIn` turns the four off and `lucisv.commentKeywords.caseSensitive` turns case-insensitive matching on. Only the lines on screen (plus a margin) are searched for the words; an edit above the screen re-reads the lines from the edit down to it, and a file too large for VS Code to tokenize (over 20 MiB or 300 000 lines) is not painted | ### Refactoring @@ -319,6 +320,9 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`, |---|---:|---| | `lucisv.references.fullLineView` | `true` | `Shift+Alt+F12` in a Verilog/SystemVerilog editor opens lucisv's full-line References view instead of VS Code's, whose previews start a few characters before the match. `false` gives the key back to the built-in command; the context-menu entry works either way, and `Shift+F12` peek is never changed | | `lucisv.rainbowBeginEnd` | `true` | Color nested block pairs and unmatched keywords; updates immediately | +| `lucisv.commentKeywords.builtIn` | `true` | Highlight `TODO`, `FIXME`, `FIX_ME` and `TBD` inside comments; updates immediately | +| `lucisv.commentKeywords.custom` | `[]` | More words to highlight inside comments, matched literally as whole words — up to 50, each 1–40 characters with no spaces; updates immediately | +| `lucisv.commentKeywords.caseSensitive` | `true` | `false` highlights `todo`/`Todo` too, for the built-ins and the custom words alike | | `lucisv.inlineTemplates` | `true` | Show context-aware structural ghost text; requires `editor.inlineSuggest.enabled` | | `lucisv.inlineKeywords` | `true` | Ghost the rest of a keyword while its first letters are typed; follows the popup's selected entry; requires `editor.inlineSuggest.enabled` | | `lucisv.autoEnd` | `true` | Write the `end` when `Enter` is pressed after a `begin` that has none | @@ -423,6 +427,21 @@ Every nesting color is a proper VS Code theme color: } ``` +The comment keywords are one more, `lucisv.commentKeyword` (bold, orange by +default): + +```jsonc +"workbench.colorCustomizations": { + "lucisv.commentKeyword": "#FF9E3D" +} +``` + +## Release 0.65.3 highlights + +Version 0.65.3 highlights `TODO`, `FIXME`, `FIX_ME` and `TBD` inside comments, +and any words of your own you list in `lucisv.commentKeywords.custom` — in +comments only, never in code or strings. + ## Release 0.65.2 highlights Version 0.65.2 lights your position in the Hierarchy pane: the instances of diff --git a/editors/vscode/commentKeywords.js b/editors/vscode/commentKeywords.js new file mode 100644 index 0000000..1198f3b --- /dev/null +++ b/editors/vscode/commentKeywords.js @@ -0,0 +1,219 @@ +// Highlight TODO, FIXME, FIX_ME, TBD and the user's own words inside comments +// (docs/features/comment-highlighting). Editor decorations, painted only on +// the lines an editor shows; where the comments are comes from +// `commentScan.js`, which mirrors the TextMate grammar. +// +// `vscode` is passed in rather than required so the wiring is testable with a +// fake (`commentKeywords_test.js`). + +const { chooseWords, wordMatcher, LineStates, keywordRanges } = require('./commentScan'); + +/** The settings section this reads: `lucisv.commentKeywords.*`. */ +const SECTION = 'lucisv.commentKeywords'; + +/** The theme colour the words are painted in. One dot: see the README. */ +const COLOR_ID = 'lucisv.commentKeyword'; + +/** How long typing settles before the edited editor is repainted. */ +const EDIT_DEBOUNCE_MS = 100; + +/** Lines painted beyond each visible range, so a short scroll shows no gap. */ +const MARGIN_LINES = 50; + +/** VS Code's own default for `editor.maxTokenizationLineLength`. */ +const DEFAULT_MAX_LINE_LENGTH = 20000; + +/** + * VS Code never tokenizes a model above either size when + * `editor.largeFileOptimizations` is on (`textModel.ts`, + * `LARGE_FILE_SIZE_THRESHOLD` / `LARGE_FILE_LINE_COUNT_THRESHOLD`; the length + * is in UTF-16 units). Such a file shows no comment colour, so none of it is + * painted either. + */ +const UNTOKENIZED_LENGTH = 20 * 1024 * 1024; +const UNTOKENIZED_LINES = 300 * 1000; + +class CommentKeywords { + /** + * @param vscode the `vscode` module (or a fake of it) + * @param isTarget which documents to paint (the Verilog ones) + * @param log where a line about skipped custom words goes + */ + constructor(vscode, isTarget, log = () => {}) { + this.vscode = vscode; + this.isTarget = isTarget; + this.log = log; + /** + * Per document object: `{ states, maxLineLength, untokenized }` — its + * block-comment line states, the line-length cutoff they were computed + * with, and whether VS Code tokenizes it at all. + */ + this.documents = new Map(); + /** Editors this has painted, so only those are ever cleared. */ + this.painted = new WeakSet(); + this.timer = undefined; + this.decoration = vscode.window.createTextEditorDecorationType({ + color: new vscode.ThemeColor(COLOR_ID), + fontWeight: 'bold', + }); + this.readSettings(); + } + + /** Subscribe to everything that can change what is painted. */ + activate(subscriptions) { + const { window, workspace } = this.vscode; + subscriptions.push( + this.decoration, + window.onDidChangeVisibleTextEditors(() => this.paintVisible()), + window.onDidChangeTextEditorVisibleRanges((event) => this.paintEditor(event.textEditor)), + workspace.onDidChangeTextDocument((event) => this.onEdit(event)), + // A language-mode change is reported as close then open of the same + // document (`languages.setTextDocumentLanguage`'s documentation), and + // the open fires before the editor shows the new mode — hence the tick. + workspace.onDidCloseTextDocument((document) => this.documents.delete(document)), + workspace.onDidOpenTextDocument(() => setTimeout(() => this.paintVisible(), 0)), + workspace.onDidChangeConfiguration((event) => this.onConfiguration(event)), + { dispose: () => clearTimeout(this.timer) }, + ); + this.paintVisible(); + } + + /** Read the words and the case rule afresh. */ + readSettings() { + const settings = this.vscode.workspace.getConfiguration(SECTION); + const caseSensitive = settings.get('caseSensitive', true) !== false; + const { words, skipped } = chooseWords({ + builtIn: settings.get('builtIn', true), + custom: settings.get('custom', []), + caseSensitive, + }); + if (skipped.length) { + this.log(`lucisv: ${SECTION}.custom: ignored ${skipped.length} entr${skipped.length === 1 ? 'y' : 'ies'} ` + + '(each must be 1–40 characters with no spaces, at most 50 words)'); + } + this.matcher = wordMatcher(words, caseSensitive); + } + + /** + * `editor.maxTokenizationLineLength` as VS Code applies it to `document`: + * read with the document as scope, so a `[systemverilog]` override counts. + */ + maxLineLength(document) { + const max = this.vscode.workspace.getConfiguration('editor', document).get('maxTokenizationLineLength'); + return Number.isInteger(max) && max > 0 ? max : DEFAULT_MAX_LINE_LENGTH; + } + + /** + * Whether VS Code tokenizes `document` at all. Decided once per document, + * as VS Code decides it once per model, at creation. + */ + isUntokenized(document) { + const editor = this.vscode.workspace.getConfiguration('editor', document); + if (editor.get('largeFileOptimizations', true) === false) return false; + if (document.lineCount > UNTOKENIZED_LINES) return true; + const last = document.lineAt(document.lineCount - 1); + return document.offsetAt(last.range.end) > UNTOKENIZED_LENGTH; + } + + /** The cached record for `document`, fresh if its cutoff changed. */ + recordOf(document) { + const maxLineLength = this.maxLineLength(document); + let record = this.documents.get(document); + if (!record) { + record = { states: new LineStates(), maxLineLength, untokenized: this.isUntokenized(document) }; + this.documents.set(document, record); + } else if (record.maxLineLength !== maxLineLength) { + // The cutoff decides which lines carry a block comment over, so every + // cached state may be wrong. + record.states = new LineStates(); + record.maxLineLength = maxLineLength; + } + return record; + } + + /** A setting this depends on changed: honour it now, both ways. */ + onConfiguration(event) { + const ours = event.affectsConfiguration(SECTION); + const lineLength = event.affectsConfiguration('editor.maxTokenizationLineLength'); + if (!ours && !lineLength) return; + // A changed cutoff is noticed per document by `recordOf`. + if (ours) this.readSettings(); + this.paintVisible(); + } + + /** Forget the states below the first edited line, then repaint soon. */ + onEdit(event) { + if (!this.isTarget(event.document)) return; + const record = this.documents.get(event.document); + if (record && event.contentChanges.length) { + const first = Math.min(...event.contentChanges.map((change) => change.range.start.line)); + record.states.invalidateFrom(first); + } + clearTimeout(this.timer); + this.timer = setTimeout(() => this.paintVisible(), EDIT_DEBOUNCE_MS); + } + + paintVisible() { + for (const editor of this.vscode.window.visibleTextEditors) this.paintEditor(editor); + } + + /** + * Paint the keywords on (and just around) the lines `editor` shows — or + * clear them, when there is nothing to paint or the document stopped being + * Verilog. + */ + paintEditor(editor) { + const document = editor.document; + if (!this.isTarget(document)) { + if (this.painted.has(editor)) this.setRanges(editor, []); + return; + } + if (!this.matcher) { + this.setRanges(editor, []); + return; + } + const { states, maxLineLength, untokenized } = this.recordOf(document); + if (untokenized) { + this.setRanges(editor, []); + return; + } + const lineText = (line) => document.lineAt(line).text; + const last = document.lineCount - 1; + const ranges = []; + for (const { from, to } of paddedLines(editor.visibleRanges, last)) { + const found = keywordRanges({ + states, lineText, from, to, matcher: this.matcher, maxLineLength, + }); + for (const { line, start, end } of found) ranges.push(new this.vscode.Range(line, start, line, end)); + } + this.setRanges(editor, ranges); + } + + setRanges(editor, ranges) { + editor.setDecorations(this.decoration, ranges); + if (ranges.length) this.painted.add(editor); + else this.painted.delete(editor); + } +} + +/** + * The visible ranges as line spans, widened by `MARGIN_LINES`, clamped to the + * document and merged where they overlap, so no line is scanned twice. + */ +function paddedLines(visibleRanges, lastLine) { + const spans = visibleRanges + .map((range) => ({ + from: Math.max(0, range.start.line - MARGIN_LINES), + to: Math.min(lastLine, range.end.line + MARGIN_LINES), + })) + .sort((a, b) => a.from - b.from); + const merged = []; + for (const span of spans) { + const previous = merged[merged.length - 1]; + if (previous && span.from <= previous.to + 1) previous.to = Math.max(previous.to, span.to); + else merged.push({ ...span }); + } + return merged; +} + +module.exports = { CommentKeywords, paddedLines, COLOR_ID, SECTION }; diff --git a/editors/vscode/commentKeywords_test.js b/editors/vscode/commentKeywords_test.js new file mode 100644 index 0000000..5334350 --- /dev/null +++ b/editors/vscode/commentKeywords_test.js @@ -0,0 +1,297 @@ +// commentKeywords.js against a fake `vscode`: it paints only Verilog editors, +// only around the visible lines, honours every setting change at once, and +// re-reads block-comment state below an edit. Plus the shipped colour's +// contrast against the built-in editor backgrounds +// (docs/features/comment-highlighting). +// +// node --test commentKeywords_test.js + +const assert = require('assert/strict'); +const fs = require('fs'); +const path = require('path'); +const test = require('node:test'); +const { CommentKeywords, paddedLines, COLOR_ID } = require('./commentKeywords'); + +/** A fake of the slice of `vscode` the module uses. */ +function fakeVscode(settings = {}) { + const handlers = {}; + const on = (name) => (handler) => { + handlers[name] = handler; + return { dispose() {} }; + }; + const vscode = { + settings, + handlers, + decorationOptions: undefined, + Range: class { + constructor(l1, c1, l2, c2) { + Object.assign(this, { l1, c1, l2, c2 }); + } + }, + ThemeColor: class { + constructor(id) { + this.id = id; + } + }, + window: { + visibleTextEditors: [], + createTextEditorDecorationType(options) { + vscode.decorationOptions = options; + return { dispose() {} }; + }, + onDidChangeVisibleTextEditors: on('visible'), + onDidChangeTextEditorVisibleRanges: on('ranges'), + }, + workspace: { + // A language-scoped value (`"[systemverilog]": {...}`, keyed here as + // `[systemverilog]editor.x`) wins when a document is the scope. + getConfiguration(section, scope) { + return { + get: (key, fallback) => { + const scoped = scope && settings[`[${scope.languageId}]${section}.${key}`]; + const value = scoped !== undefined ? scoped : settings[`${section}.${key}`]; + return value === undefined ? fallback : value; + }, + }; + }, + onDidChangeTextDocument: on('edit'), + onDidOpenTextDocument: on('open'), + onDidCloseTextDocument: on('close'), + onDidChangeConfiguration: on('config'), + }, + }; + return vscode; +} + +function fakeEditor(lines, { languageId = 'systemverilog', visible = [[0, lines.length - 1]] } = {}) { + const document = { + languageId, + lines, + get lineCount() { + return this.lines.length; + }, + lineAt(line) { + const text = this.lines[line]; + return { text, range: { end: { line, character: text.length } } }; + }, + offsetAt({ line, character }) { + return this.lines.slice(0, line).reduce((sum, text) => sum + text.length + 1, 0) + character; + }, + }; + return { + document, + visibleRanges: visible.map(([from, to]) => ({ start: { line: from }, end: { line: to } })), + painted: undefined, + setDecorations(_type, ranges) { + this.painted = ranges.map((r) => `${r.l1}:${document.lines[r.l1].slice(r.c1, r.c2)}`); + }, + }; +} + +const isVerilog = (document) => ['verilog', 'systemverilog'].includes(document.languageId); + +function start(vscode, editors, log) { + vscode.window.visibleTextEditors = editors; + const subscriptions = []; + const keywords = new CommentKeywords(vscode, isVerilog, log); + keywords.activate(subscriptions); + return { keywords, subscriptions }; +} + +function configChange(vscode, ...sections) { + vscode.handlers.config({ affectsConfiguration: (s) => sections.includes(s) }); +} + +test('paints the built-ins bold in the contributed colour, in Verilog editors only', () => { + const vscode = fakeVscode(); + const sv = fakeEditor(['wire TODO; // TODO and TBD']); + const other = fakeEditor(['// TODO'], { languageId: 'plaintext' }); + const { subscriptions } = start(vscode, [sv, other]); + assert.deepEqual(sv.painted, ['0:TODO', '0:TBD']); + assert.equal(other.painted, undefined); + assert.equal(vscode.decorationOptions.color.id, COLOR_ID); + assert.equal(vscode.decorationOptions.fontWeight, 'bold'); + assert.ok(subscriptions.length >= 7, 'the decoration type and every listener are disposed with the extension'); +}); + +test('only the lines around the visible range are read', () => { + const vscode = fakeVscode(); + const lines = Array.from({ length: 1000 }, (_, i) => `// TODO ${i}`); + const editor = fakeEditor(lines, { visible: [[500, 520]] }); + let reads = 0; + const lineAt = editor.document.lineAt.bind(editor.document); + editor.document.lineAt = (line) => { + reads += 1; + return lineAt(line); + }; + start(vscode, [editor]); + assert.equal(editor.painted.length, 121, 'lines 450..570'); + assert.equal(editor.painted[0], '450:TODO'); + // The last line once (the size check), lines 0..449 once for the + // block-comment state above the window, then each window line once: its + // scan also gives the next line's state. + assert.equal(reads, 1 + 450 + 121); + reads = 0; + vscode.handlers.ranges({ textEditor: editor }); + assert.equal(reads, 121, 'a repaint reuses the states above the window'); +}); + +test('setting changes take effect immediately, both ways', () => { + const vscode = fakeVscode(); + const editor = fakeEditor(['// TODO XXX todo hack']); + start(vscode, [editor]); + assert.deepEqual(editor.painted, ['0:TODO']); + vscode.settings['lucisv.commentKeywords.custom'] = ['XXX', 'hack']; + configChange(vscode, 'lucisv.commentKeywords'); + assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:hack']); + vscode.settings['lucisv.commentKeywords.builtIn'] = false; + configChange(vscode, 'lucisv.commentKeywords'); + assert.deepEqual(editor.painted, ['0:XXX', '0:hack']); + vscode.settings['lucisv.commentKeywords.caseSensitive'] = false; + vscode.settings['lucisv.commentKeywords.builtIn'] = true; + configChange(vscode, 'lucisv.commentKeywords'); + assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:todo', '0:hack']); + vscode.settings['lucisv.commentKeywords.builtIn'] = false; + vscode.settings['lucisv.commentKeywords.custom'] = []; + configChange(vscode, 'lucisv.commentKeywords'); + assert.deepEqual(editor.painted, [], 'nothing left to highlight clears the decorations'); + editor.painted = 'untouched'; + configChange(vscode, 'lucisv.rainbowBeginEnd'); + assert.equal(editor.painted, 'untouched', 'an unrelated setting repaints nothing'); +}); + +test('unusable custom words are skipped with one line in the output channel', () => { + const vscode = fakeVscode({ 'lucisv.commentKeywords.custom': ['ok', 'two words', ''] }); + const logged = []; + const editor = fakeEditor(['// ok']); + start(vscode, [editor], (line) => logged.push(line)); + assert.deepEqual(editor.painted, ['0:ok']); + assert.equal(logged.length, 1); + assert.match(logged[0], /ignored 2 entries/); +}); + +test('an edit above re-reads the block-comment state below it', async () => { + const vscode = fakeVscode(); + const editor = fakeEditor(['wire a;', 'TODO', '*/ // TBD']); + start(vscode, [editor]); + assert.deepEqual(editor.painted, ['2:TBD']); + editor.document.lines[0] = 'wire a; /*'; + vscode.handlers.edit({ document: editor.document, contentChanges: [{ range: { start: { line: 0 } } }] }); + await new Promise((resolve) => setTimeout(resolve, 150)); + assert.deepEqual(editor.painted, ['1:TODO', '2:TBD']); +}); + +test('maxTokenizationLineLength is honoured, and a change to it drops the cached states', () => { + const vscode = fakeVscode({ 'editor.maxTokenizationLineLength': 20 }); + const editor = fakeEditor(['/* open', `${'x'.repeat(30)} */`, 'TODO */']); + start(vscode, [editor]); + assert.deepEqual(editor.painted, ['2:TODO'], 'the long line is not tokenized, so the block stays open'); + vscode.settings['editor.maxTokenizationLineLength'] = 1000; + configChange(vscode, 'editor.maxTokenizationLineLength'); + assert.deepEqual(editor.painted, []); +}); + +test('a [systemverilog] maxTokenizationLineLength override is the one honoured', () => { + const vscode = fakeVscode({ + 'editor.maxTokenizationLineLength': 20000, + '[systemverilog]editor.maxTokenizationLineLength': 20, + }); + const lines = ['/* open', `${'x'.repeat(30)} */ // TODO`, 'TODO */']; + const sv = fakeEditor(lines); + const v = fakeEditor([...lines], { languageId: 'verilog' }); + start(vscode, [sv, v]); + assert.deepEqual(sv.painted, ['2:TODO'], 'the override applies to the systemverilog document'); + assert.deepEqual(v.painted, ['1:TODO'], 'and not to the verilog one'); + delete vscode.settings['[systemverilog]editor.maxTokenizationLineLength']; + configChange(vscode, 'editor.maxTokenizationLineLength'); + assert.deepEqual(sv.painted, ['1:TODO'], 'dropping the override recomputes the states'); +}); + +test('a language-mode change clears or paints at once', async () => { + const vscode = fakeVscode(); + const editor = fakeEditor(['// TODO']); + start(vscode, [editor]); + assert.deepEqual(editor.painted, ['0:TODO']); + // What `setTextDocumentLanguage` reports: close, then open, of the document. + const change = async (languageId) => { + vscode.handlers.close(editor.document); + editor.document.languageId = languageId; + vscode.handlers.open(editor.document); + await new Promise((resolve) => setTimeout(resolve, 5)); + }; + await change('plaintext'); + assert.deepEqual(editor.painted, [], 'no longer Verilog: the decorations go'); + await change('systemverilog'); + assert.deepEqual(editor.painted, ['0:TODO'], 'Verilog again: painted without a scroll or edit'); + const foreign = fakeEditor(['// TODO'], { languageId: 'markdown' }); + vscode.window.visibleTextEditors.push(foreign); + vscode.handlers.visible(); + assert.equal(foreign.painted, undefined, 'an editor this never painted is never touched'); +}); + +test('a file VS Code does not tokenize at all is not painted', () => { + const big = Array.from({ length: 300001 }, () => '// TODO'); + const vscode = fakeVscode(); + const editor = fakeEditor(big, { visible: [[0, 10]] }); + start(vscode, [editor]); + assert.deepEqual(editor.painted, [], 'over 300 000 lines'); + + const long = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024)], { visible: [[0, 1]] }); + start(fakeVscode(), [long]); + assert.deepEqual(long.painted, [], 'over 20 MiB'); + + const atLimit = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024 - 8)], { visible: [[0, 1]] }); + start(fakeVscode({ 'editor.maxTokenizationLineLength': 1e9 }), [atLimit]); + assert.deepEqual(atLimit.painted, ['0:TODO'], 'exactly 20 MiB is still tokenized'); + + const optOut = fakeEditor(big, { visible: [[0, 1]] }); + start(fakeVscode({ 'editor.largeFileOptimizations': false }), [optOut]); + assert.equal(optOut.painted.length, 52, 'largeFileOptimizations off: VS Code tokenizes it, so it is painted'); +}); + +test('paddedLines widens, clamps and merges the visible ranges', () => { + const range = (from, to) => ({ start: { line: from }, end: { line: to } }); + assert.deepEqual(paddedLines([range(0, 10)], 30), [{ from: 0, to: 30 }]); + assert.deepEqual(paddedLines([range(300, 310), range(100, 110)], 1000), + [{ from: 50, to: 160 }, { from: 250, to: 360 }]); + assert.deepEqual(paddedLines([range(100, 110), range(150, 160)], 1000), [{ from: 50, to: 210 }]); +}); + +// ---- The shipped colour is readable on the built-in editor backgrounds. + +/** `editor.background` of the built-in themes, per theme kind. */ +const BACKGROUNDS = [ + { kind: 'dark', name: 'Dark Modern', background: '#1F1F1F' }, + { kind: 'dark', name: 'Dark+', background: '#1E1E1E' }, + { kind: 'light', name: 'Light Modern', background: '#FFFFFF' }, + { kind: 'light', name: 'Light+', background: '#FFFFFF' }, + { kind: 'highContrast', name: 'HC Dark', background: '#000000' }, + { kind: 'highContrastLight', name: 'HC Light', background: '#FFFFFF' }, +]; + +/** WCAG relative luminance of an opaque `#RRGGBB`. */ +function luminance(hex) { + const [r, g, b] = [1, 3, 5].map((at) => { + const c = parseInt(hex.slice(at, at + 2), 16) / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +function contrast(a, b) { + const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (high + 0.05) / (low + 0.05); +} + +test('lucisv.commentKeyword is opaque and at least 4.5:1 on every built-in theme', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8')); + const colour = manifest.contributes.colors.find(({ id }) => id === COLOR_ID); + assert.ok(colour, `${COLOR_ID} is contributed`); + assert.equal(COLOR_ID.split('.').length, 2, 'exactly one dot in the colour id'); + for (const { kind, name, background } of BACKGROUNDS) { + const foreground = colour.defaults[kind]; + assert.match(foreground, /^#[0-9A-Fa-f]{6}$/, `${name}: opaque #RRGGBB`); + const ratio = contrast(foreground, background); + assert.ok(ratio >= 4.5, `${name}: ${foreground} on ${background} is ${ratio.toFixed(2)}:1`); + } +}); diff --git a/editors/vscode/commentScan.js b/editors/vscode/commentScan.js new file mode 100644 index 0000000..c9a0025 --- /dev/null +++ b/editors/vscode/commentScan.js @@ -0,0 +1,236 @@ +// Where the comments are, and which words inside them to highlight — pure, +// no `vscode`, so every rule here is tested with plain node +// (docs/features/comment-highlighting). +// +// The comment rules are the TextMate grammar's, not the lexer's, on purpose: +// a keyword is highlighted where the user *sees* comment colouring, and that +// colouring is the grammar's. `commentScan_test.js` pins the grammar rules +// this file mirrors, so an edit to one without the other fails the build. +// +// The grammar (`syntaxes/systemverilog.tmLanguage.json`) has exactly two rules +// that decide what is comment: `//.*` and `/\*` … `\*/` (which may span +// lines), and one that hides a `//` or `/*` from them — a string, `"` … `"` +// or end of line, with `\\.` escapes. Every other top-level rule matches only +// characters that can never begin those three (backtick names, `$` names, +// numbers, keywords), so it can never swallow or reveal a comment start and +// this scan can ignore it. + +/** The words highlighted unless `lucisv.commentKeywords.builtIn` is off. */ +const BUILT_IN_WORDS = ['TODO', 'FIXME', 'FIX_ME', 'TBD']; + +/** At most this many custom words are honoured; the rest are dropped. */ +const MAX_CUSTOM_WORDS = 50; + +/** A custom word longer than this is dropped. */ +const MAX_WORD_LENGTH = 40; + +/** An identifier character: a match may not have one on either side. */ +const WORD_CHAR = '[A-Za-z0-9_$]'; + +/** The next thing that can start a comment or a string. */ +const OPENER = /\/\/|\/\*|"/g; + +/** + * The comment spans of one line, given whether it starts inside a block + * comment, and whether the next line does. + * + * Each span is `[start, end, bodyStart, bodyEnd]`: the whole comment with + * its delimiters, then the text between them, all as `[start, end)` offsets in + * UTF-16 units — VS Code's columns. + */ +function scanLine(text, inBlock) { + const spans = []; + let at = 0; + if (inBlock) { + const close = text.indexOf('*/'); + if (close < 0) return { spans: [[0, text.length, 0, text.length]], inBlock: true }; + spans.push([0, close + 2, 0, close]); + at = close + 2; + } + for (;;) { + OPENER.lastIndex = at; + const opener = OPENER.exec(text); + if (!opener) return { spans, inBlock: false }; + const start = opener.index; + if (opener[0] === '//') { + spans.push([start, text.length, start + 2, text.length]); + return { spans, inBlock: false }; + } + if (opener[0] === '/*') { + const close = text.indexOf('*/', start + 2); + if (close < 0) { + spans.push([start, text.length, start + 2, text.length]); + return { spans, inBlock: true }; + } + spans.push([start, close + 2, start + 2, close]); + at = close + 2; + } else { + at = stringEnd(text, start + 1); + } + } +} + +/** + * Where a string that opened just before `at` ends: after its closing quote, + * or at the end of the line. A backslash escapes the next character, if the + * line has one — the grammar's `\\.` cannot match the line break. + */ +function stringEnd(text, at) { + while (at < text.length) { + const c = text[at]; + if (c === '\\') at += 2; + else if (c === '"') return at + 1; + else at += 1; + } + return text.length; +} + +/** + * The words to highlight, from the settings: the built-ins (unless turned + * off) and every usable custom word, without duplicates. + * + * A custom word is usable when it is a string of 1 to `MAX_WORD_LENGTH` + * characters with no whitespace; anything else is skipped, as is everything + * past the first `MAX_CUSTOM_WORDS`. Returns the words and the skipped + * entries, so the caller can say what it ignored. + */ +function chooseWords({ builtIn = true, custom = [], caseSensitive = true } = {}) { + const words = builtIn === false ? [] : [...BUILT_IN_WORDS]; + const skipped = []; + const list = Array.isArray(custom) ? custom : []; + for (const [index, entry] of list.entries()) { + const usable = typeof entry === 'string' && entry.length > 0 + && entry.length <= MAX_WORD_LENGTH && !/\s/.test(entry); + if (usable && index < MAX_CUSTOM_WORDS) words.push(entry); + else skipped.push(entry); + } + const seen = new Set(); + const unique = words.filter((word) => { + const key = caseSensitive === false ? word.toLowerCase() : word; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + return { words: unique, skipped }; +} + +/** `text` with every regular-expression metacharacter escaped. */ +function escapeRegExp(text) { + return text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); +} + +/** + * One global regular expression that finds any of `words` as a whole word, + * or `null` when there are none. + * + * Whole word the way `\b` means it, with `$` counted as a word character + * (Verilog's identifiers have it): a word that starts with a word character + * may not have one just before it, and one that ends with a word character + * may not have one just after. So `TODO` skips `TODO_reg` and `myTODO`, and + * `REVIEW:` matches in `REVIEW:x`. + * + * Every word is matched literally — escaped, never interpreted — so a setting + * cannot inject a pattern. The alternation is of plain literals, longest + * first so a word wins over its own prefix, each between at most two + * one-character lookarounds: no quantifier, nothing to backtrack + * catastrophically on. + */ +function wordMatcher(words, caseSensitive = true) { + if (!words.length) return null; + const startsWord = new RegExp(`^${WORD_CHAR}`); + const endsWord = new RegExp(`${WORD_CHAR}$`); + const alternatives = [...words] + .sort((a, b) => b.length - a.length) + .map((word) => (startsWord.test(word) ? `(?= max`) and carries the + * state across it unchanged, so it shows no comment there and neither do we. + */ +class LineStates { + constructor() { + /** `starts[i]`: line `i` begins inside a block comment. Line 0 never does. */ + this.starts = [false]; + } + + /** Lines from `line` on may have changed. */ + invalidateFrom(line) { + this.starts.length = Math.max(1, Math.min(this.starts.length, line + 1)); + } + + /** Whether `line` starts inside a block comment. */ + startOf(line, lineText, maxLineLength) { + while (this.starts.length <= line) { + const previous = this.starts.length - 1; + const text = lineText(previous); + const inBlock = this.starts[previous]; + this.starts.push(text.length >= maxLineLength ? inBlock : scanLine(text, inBlock).inBlock); + } + return this.starts[line]; + } + + /** Record what a scan of `line` found for the next one, if that is new. */ + recordNext(line, inBlock) { + if (this.starts.length === line + 1) this.starts.push(inBlock); + } +} + +/** + * The keyword ranges `{ line, start, end }` on lines `from`..`to` (inclusive) + * of a document read through `lineText`. + */ +function keywordRanges({ states, lineText, from, to, matcher, maxLineLength }) { + const ranges = []; + if (!matcher) return ranges; + for (let line = from; line <= to; line += 1) { + const text = lineText(line); + const inBlock = states.startOf(line, lineText, maxLineLength); + if (text.length >= maxLineLength) { + states.recordNext(line, inBlock); + continue; + } + const { spans, inBlock: next } = scanLine(text, inBlock); + states.recordNext(line, next); + for (const [start, end] of wordsInSpans(text, spans, matcher)) ranges.push({ line, start, end }); + } + return ranges; +} + +module.exports = { + BUILT_IN_WORDS, + MAX_CUSTOM_WORDS, + MAX_WORD_LENGTH, + scanLine, + chooseWords, + escapeRegExp, + wordMatcher, + wordsInSpans, + LineStates, + keywordRanges, +}; diff --git a/editors/vscode/commentScan_test.js b/editors/vscode/commentScan_test.js new file mode 100644 index 0000000..5f26e9b --- /dev/null +++ b/editors/vscode/commentScan_test.js @@ -0,0 +1,244 @@ +// commentScan.js: the comment rules it mirrors are the grammar's, the words +// are matched literally and as whole words, and the incremental line states +// always agree with a scan from the top (docs/features/comment-highlighting). +// +// node --test commentScan_test.js + +const assert = require('assert/strict'); +const fs = require('fs'); +const path = require('path'); +const test = require('node:test'); +const { + BUILT_IN_WORDS, MAX_CUSTOM_WORDS, MAX_WORD_LENGTH, scanLine, chooseWords, escapeRegExp, + wordMatcher, wordsInSpans, LineStates, keywordRanges, +} = require('./commentScan'); + +const grammar = JSON.parse( + fs.readFileSync(path.join(__dirname, 'syntaxes', 'systemverilog.tmLanguage.json'), 'utf8'), +); + +/** The comment columns of each line, as `.`/`#`, scanned top to bottom. */ +function picture(lines) { + let inBlock = false; + return lines.map((line) => { + const result = scanLine(line, inBlock); + inBlock = result.inBlock; + const marks = Array.from(line, () => '.'); + for (const [start, end] of result.spans) marks.fill('#', start, end); + return marks.join(''); + }); +} + +/** The highlighted words of a whole document, as `line:text` strings. */ +function highlighted(lines, words = BUILT_IN_WORDS, options = {}) { + const ranges = keywordRanges({ + states: new LineStates(), + lineText: (line) => lines[line], + from: 0, + to: lines.length - 1, + matcher: wordMatcher(words, options.caseSensitive), + maxLineLength: options.maxLineLength || 20000, + }); + return ranges.map(({ line, start, end }) => `${line}:${lines[line].slice(start, end)}`); +} + +test('the grammar still decides comments with exactly the rules this mirrors', () => { + assert.deepEqual(grammar.repository.comments, { + patterns: [ + { name: 'comment.line.double-slash.systemverilog', match: '//.*' }, + { name: 'comment.block.systemverilog', begin: '/\\*', end: '\\*/' }, + ], + }); + assert.deepEqual(grammar.repository.strings, { + name: 'string.quoted.double.systemverilog', + begin: '"', + end: '"|$', + patterns: [{ name: 'constant.character.escape.systemverilog', match: '\\\\.' }], + }); + assert.deepEqual(grammar.patterns.slice(0, 2), [{ include: '#comments' }, { include: '#strings' }]); +}); + +test('no other top-level grammar rule can match a "/" or a quote', () => { + // If one could, it might swallow a comment opener or reveal one this scan + // hides, and the scan would have to model it. A rule built only of literal + // letters, `\b`, `\s`, digits and classes without `/` or `"` cannot. + const others = grammar.patterns.slice(2).map(({ include }) => grammar.repository[include.slice(1)]); + const regexes = others.flatMap((rule) => (rule.patterns || [rule]).map((r) => r.match)); + assert.ok(regexes.length >= 5); + for (const source of regexes) { + assert.equal(typeof source, 'string', 'every other rule is a single-line match'); + const unescaped = source.replace(/\\./g, ''); + for (const risky of ['/', '"', '.', '[^']) { + assert.ok(!unescaped.includes(risky), `${source} contains ${risky}`); + } + // QA 2026-11-19: also Oniguruma's any-char/negated escapes (`\H` non-hex, + // `\O`, `\X`, `\R`, `\P{…}`/`\p{…}`), code-point escapes that can spell + // `/` or `"` (`\x2F`, `"`, octal `\057`), and POSIX classes. + for (const escape of ['\\S', '\\W', '\\D', '\\N', '\\/', '\\H', '\\O', '\\X', '\\R', + '\\P', '\\p', '\\x', '\\u', '\\0', '[[:']) { + assert.ok(!source.includes(escape), `${source} contains ${escape}`); + } + } +}); + +test('comments: line, block, strings that hide them, and blocks across lines', () => { + const lines = [ + 'assign s = "a // b"; // c', + 'x = "q\\" // still"; /* d */ y;', + 'unterminated "string // to the end', + '/* opens', + ' " is not a string here', + 'closes */ z = "/*";', + '/*/ not closed', + 'still */ q', + '`define M(a) a // macro text', + '(* full_case *) case (x)', + 'a = "back\\\\"; // after', + 'a = "slash at end \\', + '/**/ b /***/ c', + ]; + // Copied from vscode-textmate's own tokenization of these lines with this + // grammar (docs/features/comment-highlighting, "Agreement"), not hand-counted. + assert.deepEqual(picture(lines), [ + '.....................####', + '....................#######...', + '..................................', + '########', + '#########################', + '#########..........', + '##############', + '########..', + '...............#############', + '........................', + '..............########', + '...................', + '####...#####..', + ]); +}); + +test('spans carry their bodies, without the delimiters', () => { + assert.deepEqual(scanLine('a /* b */ // c', false).spans, [[2, 9, 4, 7], [10, 14, 12, 14]]); + assert.deepEqual(scanLine('x */ y', true).spans, [[0, 4, 0, 2]]); + assert.deepEqual(scanLine('x', true), { spans: [[0, 1, 0, 1]], inBlock: true }); +}); + +test('the built-ins are highlighted in comments and nowhere else', () => { + assert.deepEqual( + highlighted([ + '// TODO: fix, FIXME, FIX_ME and TBD', + 'wire TODO_reg; // TODO_reg myTODO $TODO TODO$ TODO1 xTBD', + 'string s = "TODO // TODO"; // TODO', + 'TODO = 1; /* TBD */ FIXME', + '/* block', + ' (TODO) [TBD] {FIX_ME}.', + '*/ TODO', + '//TODO//FIXME', + '/*TODO*/', + 'todo Todo // todo Todo tbd', + ]), + ['0:TODO', '0:FIXME', '0:FIX_ME', '0:TBD', '2:TODO', '3:TBD', '5:TODO', '5:TBD', '5:FIX_ME', + '7:TODO', '7:FIXME', '8:TODO'], + ); +}); + +test('case-insensitive matching is opt-in', () => { + assert.deepEqual(highlighted(['// todo Todo TODO todo_x'], BUILT_IN_WORDS, { caseSensitive: false }), + ['0:todo', '0:Todo', '0:TODO']); + assert.deepEqual(highlighted(['// todo Todo'], BUILT_IN_WORDS, { caseSensitive: true }), []); +}); + +test('custom words are literal: metacharacters mean themselves', () => { + const words = ['a.b', '(.*)+', '[x]', '\\d', 'c|d', '^e$', 'f?', 'g{2}', '$h', 'i/j']; + assert.deepEqual( + highlighted(['// axb a.b (.*)+ aaa [x] x \\d 1 c|d c d ^e$ e f? f g{2} gg $h i/j'], words), + ['0:a.b', '0:(.*)+', '0:[x]', '0:\\d', '0:c|d', '0:^e$', '0:f?', '0:g{2}', '0:$h', '0:i/j'], + ); + assert.equal(escapeRegExp('.*+?^${}()|[]\\/'), '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\\\/'); +}); + +test('whole words follow \\b, with $ as a word character', () => { + const words = ['REVIEW:', '@note', 'HACK']; + assert.deepEqual( + highlighted(['// REVIEW:x xREVIEW: a@note @notes HACK_mode HACK$ (HACK) HACK'], words), + ['0:REVIEW:', '0:@note', '0:HACK', '0:HACK'], + ); +}); + +test('a word wins over its own prefix', () => { + assert.deepEqual(highlighted(['// TODO! TODO'], ['TODO', 'TODO!']), ['0:TODO!', '0:TODO']); +}); + +test('a custom word cannot reach into a comment delimiter', () => { + assert.deepEqual(highlighted(['// x /* y */ z', 'a /** b **/'], ['//', '/*', '*/', '**', '*']), + ['0:/*', '0:*/', '1:*', '1:*'], 'inside a line comment, "/* y */" is only text'); +}); + +test('chooseWords: built-ins, caps, junk and duplicates', () => { + assert.deepEqual(chooseWords().words, BUILT_IN_WORDS); + assert.deepEqual(chooseWords({ builtIn: false }).words, []); + assert.deepEqual(chooseWords({ builtIn: false, custom: ['XXX', 'XXX', 'HACK'] }).words, ['XXX', 'HACK']); + const junk = ['', 'two words', 'tab\there', 'x'.repeat(MAX_WORD_LENGTH + 1), 7, null, { a: 1 }]; + const { words, skipped } = chooseWords({ custom: [...junk, 'OK'] }); + assert.deepEqual(words, [...BUILT_IN_WORDS, 'OK']); + assert.deepEqual(skipped, junk); + assert.deepEqual(chooseWords({ custom: 'TODO' }).words, BUILT_IN_WORDS, 'a non-array is no words'); + const many = Array.from({ length: MAX_CUSTOM_WORDS + 5 }, (_, i) => `W${i}`); + const capped = chooseWords({ builtIn: false, custom: many }); + assert.equal(capped.words.length, MAX_CUSTOM_WORDS); + assert.equal(capped.skipped.length, 5); + assert.deepEqual(chooseWords({ custom: ['todo'], caseSensitive: false }).words, BUILT_IN_WORDS); + assert.deepEqual(chooseWords({ custom: ['todo'] }).words, [...BUILT_IN_WORDS, 'todo']); + assert.equal(wordMatcher([]), null); +}); + +test('the worst words the caps allow stay fast on the longest line VS Code tokenizes', () => { + const words = Array.from({ length: MAX_CUSTOM_WORDS }, (_, i) => 'a'.repeat(MAX_WORD_LENGTH - (i % 3)) + i % 3); + const line = `// ${'a'.repeat(19990)}`; + const started = process.hrtime.bigint(); + wordsInSpans(line, scanLine(line, false).spans, wordMatcher(words)); + const ms = Number(process.hrtime.bigint() - started) / 1e6; + assert.ok(ms < 2000, `took ${ms.toFixed(0)} ms`); +}); + +test('a line VS Code will not tokenize carries the state and highlights nothing', () => { + const lines = ['/* open', `x ${'y'.repeat(50)} */ // TODO`, 'still open TODO */']; + assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 40 }), ['2:TODO']); + assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 1000 }), ['1:TODO']); +}); + +/** A small deterministic PRNG, so a failure reproduces. */ +function prng(seed) { + let state = seed; + return () => { + state = (state * 1103515245 + 12345) % 2147483648; + return state / 2147483648; + }; +} + +test('incremental line states, painted or probed, always equal a scan from the top', () => { + const random = prng(71); + const pieces = ['/*', '*/', '//', '"', 'x', ' ', 'TODO', '\\']; + const line = () => Array.from({ length: 1 + Math.floor(random() * 6) }, + () => pieces[Math.floor(random() * pieces.length)]).join(''); + const lines = Array.from({ length: 40 }, line); + const states = new LineStates(); + const lineText = (at) => lines[at]; + for (let round = 0; round < 300; round += 1) { + const at = Math.floor(random() * lines.length); + const kind = random(); + if (kind < 0.4) lines[at] = line(); + else if (kind < 0.7) lines.splice(at, 0, line()); + else if (lines.length > 1) lines.splice(at, 1); + states.invalidateFrom(at); + if (random() < 0.5) { + // A paint of some window, which records states as a side effect. + const from = Math.floor(random() * lines.length); + const to = Math.min(lines.length - 1, from + Math.floor(random() * 8)); + keywordRanges({ states, lineText, from, to, matcher: wordMatcher(['TODO']), maxLineLength: 20000 }); + } + const probe = Math.floor(random() * lines.length); + const fresh = new LineStates(); + assert.equal(states.startOf(probe, lineText, 20000), fresh.startOf(probe, lineText, 20000), + `round ${round}, line ${probe}`); + } +}); diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js index d8fdcdf..131ca56 100644 --- a/editors/vscode/extension.js +++ b/editors/vscode/extension.js @@ -17,6 +17,7 @@ const { executeCommand } = require('./extract'); const { HierarchyView } = require('./hierarchyView'); const { ReferencesView } = require('./referencesView'); const typing = require('./typing'); +const { CommentKeywords } = require('./commentKeywords'); const mcp = require('./mcp'); /** The single client, kept only so `deactivate` can stop it. */ @@ -265,6 +266,12 @@ function activate(context) { rainbowEnabled = readRainbowSetting(); + // TODO/FIXME/FIX_ME/TBD and `lucisv.commentKeywords.custom` inside comments + // (docs/features/comment-highlighting). Client-side only: it needs nothing + // from the server, so it paints even while the server is starting. + new CommentKeywords(vscode, isVerilog, (line) => client.outputChannel.appendLine(line)) + .activate(context.subscriptions); + context.subscriptions.push( // A new editor has no decorations of its own; paint it as it appears. vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()), diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 12ab8ed..38dbc1e 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.2", + "version": "0.65.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.2", + "version": "0.65.3", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index fdcc795..0526448 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.65.2", + "version": "0.65.3", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT", @@ -486,6 +486,16 @@ "highContrast": "#FFB347", "highContrastLight": "#B35900" } + }, + { + "id": "lucisv.commentKeyword", + "description": "TODO, FIXME, FIX_ME, TBD and the words in lucisv.commentKeywords.custom, inside comments (painted bold in this colour).", + "defaults": { + "dark": "#FF9E3D", + "light": "#A85000", + "highContrast": "#FFA500", + "highContrastLight": "#9C4A00" + } } ], "configuration": { @@ -534,6 +544,30 @@ "default": true, "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 `lucisv.rainbow*` theme colour you can override in `workbench.colorCustomizations`. Takes effect immediately." }, + "lucisv.commentKeywords.builtIn": { + "type": "boolean", + "default": true, + "markdownDescription": "Highlight `TODO`, `FIXME`, `FIX_ME` and `TBD` inside `//` and `/* */` comments — whole words only, so `TODO_reg` is left alone, and never in strings or code. Painted bold in the `lucisv.commentKeyword` theme colour, which `workbench.colorCustomizations` can override. Off leaves only the words in `#lucisv.commentKeywords.custom#`. Takes effect immediately." + }, + "lucisv.commentKeywords.custom": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 40, + "pattern": "^\\S+$", + "patternErrorMessage": "One word: no spaces." + }, + "maxItems": 50, + "uniqueItems": true, + "default": [], + "markdownDescription": "More words to highlight inside comments, the same way as `#lucisv.commentKeywords.builtIn#`'s: `[\"XXX\", \"HACK\", \"REVIEW:\"]`. Each is matched literally — `.` or `*` in a word means that character, not a pattern — as a whole word: a word that starts or ends with a letter, digit, `_` or `$` is not matched where another of those touches it, so `HACK` skips `HACK_mode`. Up to 50 words of up to 40 characters, no spaces; anything else is ignored, with a line in the lucisv output channel. Takes effect immediately." + }, + "lucisv.commentKeywords.caseSensitive": { + "type": "boolean", + "default": true, + "markdownDescription": "Match the comment keywords' capitals exactly, so `todo` in prose is not highlighted. Off highlights `todo`, `Todo` and `TODO` alike, for the built-in words and `#lucisv.commentKeywords.custom#` both. Takes effect immediately." + }, "lucisv.hierarchy.duts": { "type": "array", "items": { diff --git a/tools/RELEASING.md b/tools/RELEASING.md index e009984..b4bd90a 100644 --- a/tools/RELEASING.md +++ b/tools/RELEASING.md @@ -222,7 +222,8 @@ npx @vscode/vsce package --target darwin-arm64 \ where the platform packages' binaries are staged — nor any module `extension.js` requires at runtime (`restart.js`, `mcp.js`, `extract.js`, `hierarchyView.js`, `hierarchyModel.js`, `hierarchySections.js`, - `hierarchyCurrent.js`, `referencesView.js`, `referencesModel.js`): an + `hierarchyCurrent.js`, `referencesView.js`, `referencesModel.js`, + `commentKeywords.js`, `commentScan.js`): an extension that ships without one fails to activate. Check that after any change to it: `unzip -l dist/lucisv-.vsix | grep -E 'smoke|_test'` must print nothing, `unzip -l dist/lucisv-.vsix | grep -E 'restart.js|mcp.js|references(View|Model).js'`