Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d57496978f | ||
|
|
948f8a0b32 | ||
|
|
e9f5090632 | ||
|
|
88546c8b4e | ||
|
|
5c00b701fc | ||
|
|
464929262b | ||
|
|
e4db0ac1fc |
No files matched your search
@@ -14,6 +14,12 @@
|
||||
# The release fails, deliberately, when the tag does not match the
|
||||
# workspace version or CHANGELOG.md has no section for it: every release
|
||||
# ships with real, written notes (see tools/RELEASING.md).
|
||||
#
|
||||
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
|
||||
# tests, the corpus gate, the extension's node tests) runs first, and a red
|
||||
# gate means nothing is built or published. The ci workflow runs on the
|
||||
# branch push, not the tag, so without this step a tag published whatever
|
||||
# it pointed at (0.65.0 went out while its ci run was still stuck).
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
@@ -25,6 +31,15 @@ jobs:
|
||||
runs-on: macos-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# The corpus is pinned-rev clones cached on the runner host, as in
|
||||
# ci.yml; gates.sh skips its corpus step when the cache is absent, so
|
||||
# fetch it here rather than release without that gate.
|
||||
- name: Ensure the cached corpus
|
||||
run: |
|
||||
corpus="$HOME/.cache/lucisv-corpus"
|
||||
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
|
||||
- name: Gate the release
|
||||
run: tools/gates.sh
|
||||
- name: Build release artifacts for every target
|
||||
run: tools/release.sh --cross
|
||||
- name: Audit the cross-built artifacts
|
||||
|
||||
+152
@@ -4,6 +4,158 @@ 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.4 — 2026-11-19
|
||||
|
||||
### `` `ifdef `` blocks fold, and pin in sticky scroll
|
||||
|
||||
(`docs/features/ifdef-folding`; TODO §71.4.)
|
||||
|
||||
- **Every conditional-compilation branch folds on its own.** `` `ifdef ``,
|
||||
`` `ifndef ``, `` `elsif `` and `` `else `` each fold from their own line to
|
||||
the line before the next branch (or before `` `endif ``). Collapse the
|
||||
`` `ifdef `` branch and the `` `else `` line stays visible and separately
|
||||
collapsible; `` `endif `` stays visible too, the way `end` does for a
|
||||
`begin` fold. Nesting works to any depth.
|
||||
- **They pin in sticky scroll.** The floating header lines already follow the
|
||||
server's folds, so while you scroll inside a long branch its `` `ifdef `` or
|
||||
`` `else `` line stays at the top with the module and blocks around it.
|
||||
- **Only real directives count.** The folds are built from the lexer's own
|
||||
directive tokens, so a directive-looking line inside a comment, a string or
|
||||
a `` `define `` body is not folded (35 such lines in OpenTitan). An
|
||||
unterminated `` `ifdef `` folds the branches it finished and never runs to
|
||||
the end of the file; a stray `` `else `` or `` `endif `` is ignored.
|
||||
- **No existing fold is lost or changed.** On OpenTitan's `hw` tree (4 061
|
||||
files) and the 860-file corpus every fold the previous release returned is
|
||||
still returned, byte for byte, with the 1 061 and 511 branch folds added.
|
||||
Where a branch would share its start line with an existing fold — a
|
||||
directive written after code on the same line — the existing fold is sent
|
||||
first and keeps its place; that never occurs in either tree.
|
||||
- **Cost:** one extra pass over the tokens: folding all of OpenTitan goes from
|
||||
29.9 ms to about 34 ms, and a 50 000-branch file answers in 0.2 s.
|
||||
- **Limits.** Files over the large-file threshold (4 MiB) return no folds, as
|
||||
before. Not yet seen in a running editor by a human.
|
||||
|
||||
## 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
|
||||
|
||||
(`docs/features/hierarchy-current-path`; TODO §71.6.)
|
||||
|
||||
- **The rows leading to the file you are editing are lit.** Every instance of
|
||||
the module the open file declares gets a light, bright orange tint with a
|
||||
solid bar at its left edge and a bold label; each row above it is one shade
|
||||
dimmer with a narrower bar, down to a faint floor for distant ancestors. A
|
||||
module instantiated in several places lights every copy, and where two
|
||||
chains meet the nearer one wins. It works on a closed tree and on DUT
|
||||
sections: a section header is tinted when the section holds the file or its
|
||||
parents.
|
||||
- **Switching files repaints, it does not reload.** There is no request to the
|
||||
language server and no rebuild of the tree; only the rows whose shade
|
||||
changed are touched, so nothing collapses (about 5 ms on a 6 000-module
|
||||
design).
|
||||
- **Readable in every built-in theme.** The default tints keep label text at
|
||||
4.5:1 or better on every lit level in the dark, light and high-contrast
|
||||
themes, hovered rows included — a test computes that from the shipped
|
||||
defaults — and the bar's width and style change with the level, so the
|
||||
grading does not rest on colour alone.
|
||||
- **Yours to restyle or switch off.** The shades and the bar are theme colours
|
||||
(`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
|
||||
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) for
|
||||
`workbench.colorCustomizations`; `lucisv.hierarchy.highlightCurrent: false`
|
||||
turns the highlighting off.
|
||||
- **Known limits.** Nothing lights when a folder name's letter case differs
|
||||
between the filelist and the editor, or on Windows network-share paths; in a
|
||||
recursive design a row can be lit with nothing lit beneath it. Not yet seen
|
||||
in a running editor by a human: the tests are headless.
|
||||
|
||||
## 0.65.1 — 2026-11-19
|
||||
|
||||
### Releases are gated
|
||||
|
||||
No change to the formatter, the linter, the language server or the editor
|
||||
extension: the packages are 0.65.0 rebuilt. What changed is how a release is
|
||||
made (`tools/RELEASING.md`).
|
||||
|
||||
- **A tag no longer publishes unless every gate is green.** The release
|
||||
workflow now runs `tools/gates.sh` — `cargo fmt`, `cargo clippy`, each
|
||||
crate's test suites, the doc tests, the corpus gate and the extension's node
|
||||
tests — before it builds anything, and a failing gate stops the release.
|
||||
Until now only the branch push was checked, by a separate workflow the
|
||||
release did not wait for, so 0.65.0 was published while its checks had not
|
||||
finished.
|
||||
- **The build is clean on Rust 1.100.** An unused import in the language
|
||||
server's test module, which that toolchain's clippy rejects under
|
||||
`-D warnings`, is gone. It is what turned 0.65.0's checks red after the
|
||||
fact; the released binaries were never affected.
|
||||
|
||||
## 0.65.0 — 2026-11-19
|
||||
|
||||
### Module instantiation syntax highlighting
|
||||
|
||||
(`docs/features/instantiation-highlighting`; TODO §69.)
|
||||
|
||||
- **Every part of a module instantiation gets its own colour.** Module names,
|
||||
instance names, `.PARAM` overrides, `.port` names and connected signals used
|
||||
to collapse to the same default foreground colour whenever the instantiated
|
||||
module lived in another file or a theme left bare semantic tokens unstyled.
|
||||
The language server now layers AST-guided semantic token overrides (and
|
||||
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
|
||||
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
|
||||
`namespace`, and lone `bind` targets) highlight as `class`.
|
||||
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
|
||||
the `#` introducing a module, class, `extends`, instantiation or
|
||||
parameterized-type parameter list, every `.PARAM` override (`.` and name),
|
||||
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
|
||||
tokens (`#5`, `#(1:2:3)`) are left unemitted.
|
||||
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
|
||||
hierarchical uses like `u_uart.sig`) highlight as `function`.
|
||||
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
|
||||
`.*`), including unfinished entries being typed, highlight as `property`.
|
||||
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
|
||||
consistent colour across the file.
|
||||
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
|
||||
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
|
||||
`[verilog]` and `[systemverilog]` (user settings still win), and
|
||||
`contributes.semanticTokenScopes` maps the language's semantic token types to
|
||||
distinct TextMate scopes so every role renders in colour across Dark+, Dark
|
||||
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
### Completion that keeps up with typing
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.64.0"
|
||||
version = "0.65.4"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -7247,3 +7247,19 @@ Feature README: `docs/features/port-entry-grace/README.md`. Files:
|
||||
- [x] The server withholds the diagnostics that fall inside the entry the
|
||||
last edit touched, and releases them after a quiet period or when the
|
||||
next edit lands elsewhere.
|
||||
|
||||
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
|
||||
|
||||
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
|
||||
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
|
||||
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
|
||||
`docs/features/{lucisv-server,large-file-mode}/README.md`.
|
||||
|
||||
- [x] Distinct semantic highlights across module instantiations (14-type wire
|
||||
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
|
||||
parameter values (`parameter`, distinct from `()`), instance name
|
||||
(`function`), `.port`/`.*` (`property`), and port connections
|
||||
(`variable`), including unfinished entries while typing.
|
||||
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
|
||||
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
|
||||
non-white TextMate scopes across themes.
|
||||
@@ -4,7 +4,17 @@
|
||||
//! `pairs::analyze` already computes for the rainbow and the missing-closer
|
||||
//! warnings, or a block comment, which the lexer already attached as trivia.
|
||||
//! This module is the fourth consumer of the first and the second of the
|
||||
//! second. See `docs/features/references-nav/README.md`.
|
||||
//! second. See `docs/features/references-nav/README.md`. The third source,
|
||||
//! the branches of `` `ifdef `` regions, is [`directives`]
|
||||
//! (`docs/features/ifdef-folding/README.md`).
|
||||
|
||||
mod directives;
|
||||
#[cfg(test)]
|
||||
mod ifdef_tests;
|
||||
#[cfg(test)]
|
||||
mod opentitan_sweep;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{FoldingRange, FoldingRangeKind};
|
||||
use vlog_parser::token::Comment;
|
||||
@@ -13,8 +23,9 @@ use vlog_parser::TextRange;
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::Document;
|
||||
|
||||
/// Every foldable region in a buffer: one per matched scope pair, plus every
|
||||
/// block comment that spans more than one line.
|
||||
/// Every foldable region in a buffer: one per matched scope pair, one per
|
||||
/// branch of a closed `` `ifdef `` region, plus every block comment that spans
|
||||
/// more than one line.
|
||||
///
|
||||
/// A keyword whose counterpart never arrived is **not** foldable — `analyze`
|
||||
/// leaves it out of `pairs`, and folding to the end of the file because an
|
||||
@@ -22,6 +33,15 @@ use crate::state::Document;
|
||||
/// off. Nothing is capped: a fold list is one range per block, and an editor
|
||||
/// that asked for it wants all of them.
|
||||
pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
|
||||
let scopes = scope_and_comment_folds(doc);
|
||||
let branches = branch_folds(doc, &scopes);
|
||||
in_answer_order(scopes, branches)
|
||||
}
|
||||
|
||||
/// The scope-pair and block-comment folds, exactly as they were before
|
||||
/// branch folds existed: sorted by `(start, end)`, one per pair of lines (a
|
||||
/// scope pair wins over a comment on the same two lines).
|
||||
fn scope_and_comment_folds(doc: &Document) -> Vec<FoldingRange> {
|
||||
let mut out: Vec<FoldingRange> = Vec::new();
|
||||
for pair in analyze(&doc.tokens).pairs {
|
||||
// The closing keyword's own line stays visible: LSP hides
|
||||
@@ -43,6 +63,46 @@ pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One fold per branch of every closed `` `ifdef `` region, sorted by start
|
||||
/// line. Conditional-compilation branches follow the scope rule: the next
|
||||
/// directive's line (`else`, `endif`) stays visible. A branch whose two lines
|
||||
/// are exactly an existing fold's is left out, so that fold keeps its kind
|
||||
/// (a `/* */` opened on the directive line stays a `comment`).
|
||||
fn branch_folds(doc: &Document, existing: &[FoldingRange]) -> Vec<FoldingRange> {
|
||||
let taken: HashSet<(u32, u32)> = existing.iter().map(|r| (r.start_line, r.end_line)).collect();
|
||||
let mut out = Vec::new();
|
||||
for (start, through) in directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)) {
|
||||
if !taken.contains(&(start, through)) {
|
||||
push(&mut out, start, through, FoldingRangeKind::Region);
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|range| range.start_line);
|
||||
out
|
||||
}
|
||||
|
||||
/// The one place the answer's order is defined: by start line; on a shared
|
||||
/// start line, every scope or comment fold (in their own `(start, end)`
|
||||
/// order) before any branch fold.
|
||||
///
|
||||
/// The order is load-bearing. VS Code keeps only the *first* range it
|
||||
/// receives for a start line (`sanitizeRanges`), so whatever comes first is
|
||||
/// the fold the user gets and the line sticky scroll pins. Putting existing
|
||||
/// folds first means a branch fold never costs the user a fold they had
|
||||
/// before — on `module m; `ifdef A` the `module` fold survives and the branch
|
||||
/// yields. See `docs/features/ifdef-folding/README.md`.
|
||||
fn in_answer_order(existing: Vec<FoldingRange>, branches: Vec<FoldingRange>) -> Vec<FoldingRange> {
|
||||
let mut out = Vec::with_capacity(existing.len() + branches.len());
|
||||
let mut branches = branches.into_iter().peekable();
|
||||
for range in existing {
|
||||
while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) {
|
||||
out.push(branch);
|
||||
}
|
||||
out.push(range);
|
||||
}
|
||||
out.extend(branches);
|
||||
out
|
||||
}
|
||||
|
||||
/// Add one range, unless there is nothing between its two lines to hide.
|
||||
fn push(out: &mut Vec<FoldingRange>, start_line: u32, end_line: u32, kind: FoldingRangeKind) {
|
||||
if end_line <= start_line {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Folding for conditional compilation: one range per branch of every
|
||||
//! `` `ifdef `` / `` `ifndef `` … `` `endif `` region.
|
||||
//!
|
||||
//! No new scan. The lexer already turns each of the five directives into one
|
||||
//! [`TokenKind::Directive`] token that runs to the end of its line, and only
|
||||
//! where they really are directives: never in a comment or a string (those are
|
||||
//! trivia and literals), never inside a `` `define `` body (the whole body,
|
||||
//! continuation lines included, is the `` `define `` token's own text). A
|
||||
//! token's first word is all this module reads.
|
||||
//! See `docs/features/ifdef-folding/README.md`.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
|
||||
/// What one conditional-compilation directive does to the branch structure.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Conditional {
|
||||
/// `` `ifdef `` / `` `ifndef ``: a region, and its first branch, begin.
|
||||
Open,
|
||||
/// `` `elsif `` / `` `else ``: the current branch ends, the next begins.
|
||||
Next,
|
||||
/// `` `endif ``: the last branch, and the region, end.
|
||||
Close,
|
||||
}
|
||||
|
||||
/// `(directive line, last line)` of every branch whose region is closed, in
|
||||
/// 0-based lines, given the line each token starts on.
|
||||
///
|
||||
/// A branch runs from its own directive's line through the line *before*
|
||||
/// the next directive of the same region, so the `` `else `` and the
|
||||
/// `` `endif `` stay visible when the branch above them is collapsed — the
|
||||
/// same rule as `end` under `begin`. Branches with nothing between their two
|
||||
/// lines come back too (`last <= first`); the caller drops them.
|
||||
///
|
||||
/// A region that never closes contributes the branches it *did* finish
|
||||
/// (an `` `ifdef `` … `` `else `` … end-of-file still folds its first
|
||||
/// branch) and nothing for the one still open, rather than folding to the end
|
||||
/// of the file. A stray `` `else `` or `` `endif `` with no region open is
|
||||
/// ignored.
|
||||
pub(super) fn branch_spans(tokens: &[Token], line_of: impl Fn(&Token) -> u32) -> Vec<(u32, u32)> {
|
||||
// The directive line of the branch that is open at each nesting depth.
|
||||
let mut open: Vec<u32> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in tokens {
|
||||
let Some(directive) = conditional(token) else { continue };
|
||||
let at = line_of(token);
|
||||
match directive {
|
||||
Conditional::Open => open.push(at),
|
||||
Conditional::Next => {
|
||||
if let Some(first) = open.last_mut() {
|
||||
out.push((*first, at.saturating_sub(1)));
|
||||
*first = at;
|
||||
}
|
||||
}
|
||||
Conditional::Close => {
|
||||
if let Some(first) = open.pop() {
|
||||
out.push((first, at.saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The conditional-compilation directive a token is, if it is one.
|
||||
fn conditional(token: &Token) -> Option<Conditional> {
|
||||
if token.kind != TokenKind::Directive {
|
||||
return None;
|
||||
}
|
||||
match directive_word(&token.text) {
|
||||
"ifdef" | "ifndef" => Some(Conditional::Open),
|
||||
"elsif" | "else" => Some(Conditional::Next),
|
||||
"endif" => Some(Conditional::Close),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word a directive's text spells, without its backtick or argument:
|
||||
/// `` `ifndef FOO `` is `"ifndef"`. The parser keeps the same rule private
|
||||
/// (`vlog_parser/src/parser/directive.rs`); it is four lines, so it is
|
||||
/// repeated here rather than widened into the parser's public surface.
|
||||
fn directive_word(text: &str) -> &str {
|
||||
let rest = text.strip_prefix('`').unwrap_or("");
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
|
||||
rest.get(..end).unwrap_or("")
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
//! `` `ifdef `` branch folds, through the whole [`folding_ranges`] answer so
|
||||
//! every test also sees how they sit beside the scope and comment folds.
|
||||
|
||||
use lsp_types::FoldingRangeKind;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::folding_ranges;
|
||||
use crate::state::Document;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// Every fold as `(start line, end line, kind)`, kinds spelled short, after
|
||||
/// checking the one ordering promise every answer keeps: by start line.
|
||||
fn folds(text: &str) -> Vec<(u32, u32, &'static str)> {
|
||||
let ranges = folding_ranges(&doc_of(text));
|
||||
assert!(ranges.windows(2).all(|w| w[0].start_line <= w[1].start_line), "{ranges:?}");
|
||||
ranges
|
||||
.into_iter()
|
||||
.map(|range| {
|
||||
let kind = match range.kind {
|
||||
Some(FoldingRangeKind::Comment) => "comment",
|
||||
Some(FoldingRangeKind::Region) => "region",
|
||||
other => panic!("unexpected kind {other:?}"),
|
||||
};
|
||||
(range.start_line, range.end_line, kind)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folds as `(start, end)` alone, for tests about lines rather than kinds.
|
||||
fn lines(text: &str) -> Vec<(u32, u32)> {
|
||||
folds(text).into_iter().map(|(start, end, _)| (start, end)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_branch_folds_from_its_directive_to_the_line_before_the_next() {
|
||||
// Collapsing the `ifdef` branch leaves `else` on screen and separately
|
||||
// collapsible; collapsing the `else` branch leaves `endif` on screen.
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
"`ifdef A\n", // 1
|
||||
" wire a;\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`else\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`endif\n", // 6
|
||||
"endmodule\n", // 7
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 6, "region"), (1, 3, "region"), (4, 5, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_elsif_chain_gives_every_arm_its_own_fold() {
|
||||
let text = concat!(
|
||||
"`ifndef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`elsif B\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`elsif C\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`else\n", // 6
|
||||
" wire d;\n", // 7
|
||||
"`endif\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1), (2, 3), (4, 5), (6, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_regions_fold_at_every_depth() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" `ifdef B\n", // 1
|
||||
" `ifndef C\n", // 2
|
||||
" wire c;\n", // 3
|
||||
" `endif\n", // 4
|
||||
" `else\n", // 5
|
||||
" wire nb;\n", // 6
|
||||
" `endif\n", // 7
|
||||
"`else\n", // 8
|
||||
" `ifdef D\n", // 9
|
||||
" wire d;\n", // 10
|
||||
" `endif\n", // 11
|
||||
"`endif\n", // 12
|
||||
);
|
||||
assert_eq!(
|
||||
lines(text),
|
||||
vec![(0, 7), (1, 4), (2, 3), (5, 6), (8, 11), (9, 10)],
|
||||
"A, B, C, B's else, A's else, D"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_branch_with_nothing_in_it_folds_nothing() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
"`else\n", // 1
|
||||
" wire b;\n", // 2
|
||||
"`endif\n", // 3
|
||||
"`ifdef C\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(lines(text), vec![(1, 2)], "only the else branch holds a line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_line_region_is_one_token_and_folds_nothing() {
|
||||
// A directive runs to the end of its line, so the `endif` here is the
|
||||
// `ifdef` token's text, not a directive of its own.
|
||||
let text = "module m;\n`ifdef A wire a; `else wire b; `endif\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let directives = doc.tokens.iter().filter(|t| t.text.starts_with("`ifdef")).count();
|
||||
assert_eq!(directives, 1);
|
||||
assert_eq!(lines(text), vec![(0, 1)], "the module only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unterminated_region_folds_only_the_branches_it_finished() {
|
||||
// Same policy as an unclosed `begin`: never fold to the end of the file.
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`else\n", // 2
|
||||
" wire b;\n", // 3
|
||||
" wire c;\n", // 4
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1)]);
|
||||
assert!(lines("`ifdef A\n wire a;\n wire b;\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_else_and_endif_are_ignored_without_disturbing_what_follows() {
|
||||
let text = concat!(
|
||||
"`else\n", // 0
|
||||
" wire x;\n", // 1
|
||||
"`endif\n", // 2
|
||||
"`endif\n", // 3
|
||||
"`ifdef A\n", // 4
|
||||
" wire a;\n", // 5
|
||||
"`endif\n", // 6
|
||||
"`elsif B\n", // 7
|
||||
" wire b;\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(4, 5)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_between_ports_fold() {
|
||||
let text = concat!(
|
||||
"module m (\n", // 0
|
||||
" input a,\n", // 1
|
||||
"`ifdef B\n", // 2
|
||||
" input b,\n", // 3
|
||||
" input c,\n", // 4
|
||||
"`endif\n", // 5
|
||||
" input d\n", // 6
|
||||
");\n", // 7
|
||||
"endmodule\n", // 8
|
||||
);
|
||||
assert!(lines(text).contains(&(2, 4)), "got {:?}", lines(text));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_inside_case_and_generate_fold() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" generate\n", // 1
|
||||
"`ifdef G\n", // 2
|
||||
" if (A) begin : g\n", // 3
|
||||
" wire a;\n", // 4
|
||||
" end\n", // 5
|
||||
"`endif\n", // 6
|
||||
" endgenerate\n", // 7
|
||||
" always_comb begin\n", // 8
|
||||
" case (s)\n", // 9
|
||||
" 0: x = 0;\n", // 10
|
||||
"`ifdef C\n", // 11
|
||||
" 1: x = 1;\n", // 12
|
||||
"`else\n", // 13
|
||||
" 1: x = 2;\n", // 14
|
||||
"`endif\n", // 15
|
||||
" endcase\n", // 16
|
||||
" end\n", // 17
|
||||
"endmodule\n", // 18
|
||||
);
|
||||
assert_eq!(
|
||||
lines(text),
|
||||
vec![(0, 17), (1, 6), (2, 5), (3, 4), (8, 16), (9, 15), (11, 12), (13, 14)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_inside_a_define_body_is_text_not_a_fold() {
|
||||
let text = concat!(
|
||||
"`define M \\\n", // 0
|
||||
" `ifdef X \\\n", // 1
|
||||
" a = 1; \\\n", // 2
|
||||
" `else \\\n", // 3
|
||||
" a = 2; \\\n", // 4
|
||||
" `endif\n", // 5
|
||||
"module m;\n", // 6
|
||||
" wire a;\n", // 7
|
||||
"endmodule\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(6, 7)], "the module only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_in_a_comment_or_a_string_is_not_one() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" // `ifdef A\n", // 1
|
||||
" /* `ifdef B\n", // 2
|
||||
" `endif */\n", // 3
|
||||
" initial $display(\"`ifdef\");\n", // 4
|
||||
" // `endif\n", // 5
|
||||
"endmodule\n", // 6
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 5, "region"), (2, 3, "comment")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_whitespace_trailing_comments_and_crlf_change_nothing() {
|
||||
let plain = concat!(
|
||||
"module m;\n", // 0
|
||||
" `ifdef A // why\n", // 1
|
||||
" wire a;\n", // 2
|
||||
"\t`else /* other */\n", // 3
|
||||
" wire b;\n", // 4
|
||||
" `endif // A\n", // 5
|
||||
"endmodule\n", // 6
|
||||
);
|
||||
assert_eq!(lines(plain), vec![(0, 5), (1, 2), (3, 4)]);
|
||||
assert_eq!(lines(&plain.replace('\n', "\r\n")), lines(plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_crossing_a_begin_keeps_both_sets_of_folds() {
|
||||
// Real RTL opens one `begin` in each arm and closes it once below the
|
||||
// `endif`. The branch folds cross the `begin` folds; VS Code keeps
|
||||
// crossing ranges (`sanitizeRanges` adds them at the level of the range
|
||||
// they cross; see the feature README), so nothing is dropped here and
|
||||
// nothing is invented either.
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" always_comb begin\n", // 1
|
||||
"`ifdef A\n", // 2
|
||||
" if (a) begin\n", // 3
|
||||
"`else\n", // 4
|
||||
" if (b) begin\n", // 5
|
||||
"`endif\n", // 6
|
||||
" x = 1;\n", // 7
|
||||
" end\n", // 8
|
||||
" end\n", // 9
|
||||
"endmodule\n", // 10
|
||||
);
|
||||
// The scope pairing sees three `begin`s and two `end`s, matches the inner
|
||||
// two (`(5, 7)`, `(3, 8)`) and leaves the `always_comb` one out — that is
|
||||
// `pairs::analyze`, unchanged by this feature. The branches are added
|
||||
// beside it: `(2, 3)` crosses `(3, 8)`, `(4, 5)` crosses `(5, 7)`.
|
||||
assert_eq!(lines(text), vec![(0, 9), (2, 3), (3, 8), (4, 5), (5, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_folds_are_regions() {
|
||||
let text = "`ifdef A\n wire a;\n`endif\n";
|
||||
assert_eq!(folds(text), vec![(0, 1, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn back_to_back_regions_each_fold() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`endif\n", // 2
|
||||
"`ifdef B\n", // 3
|
||||
" wire b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1), (3, 4)]);
|
||||
}
|
||||
|
||||
// A shared start line. VS Code keeps only the first range it receives for a
|
||||
// start line, so a fold that existed before branch folds must come first and
|
||||
// the branch fold is the one that yields (QA findings 1 and 2, 2026-11-19).
|
||||
|
||||
#[test]
|
||||
fn a_module_header_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
|
||||
let text = "module m; `ifdef A\n a;\n`endif\nendmodule\n";
|
||||
assert_eq!(lines(text), vec![(0, 2), (0, 1)], "the module first, the branch after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
"initial begin `ifdef X\n", // 1
|
||||
" a;\n", // 2
|
||||
" b;\n", // 3
|
||||
" `endif\n", // 4
|
||||
" c;\n", // 5
|
||||
"end\n", // 6
|
||||
"endmodule\n", // 7
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 6), (1, 5), (1, 3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_opened_on_a_directive_line_keeps_its_fold_first() {
|
||||
// The comment is the shorter range but the older fold, so it is first,
|
||||
// and in VS Code the branch from line 0 is the one that yields.
|
||||
let text = concat!(
|
||||
"`ifdef A /* c1\n", // 0
|
||||
" c2 */\n", // 1
|
||||
" x;\n", // 2
|
||||
"`else\n", // 3
|
||||
" b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 1, "comment"), (0, 2, "region"), (3, 4, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_spanning_exactly_a_branch_stays_a_comment() {
|
||||
// Same two lines as the branch: one range, and it keeps the kind it had
|
||||
// before branch folds existed, so *Fold All Block Comments* still folds it.
|
||||
let text = concat!(
|
||||
"`ifdef A /* c1\n", // 0
|
||||
" c2\n", // 1
|
||||
" c3 */\n", // 2
|
||||
"`else\n", // 3
|
||||
" b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 2, "comment"), (3, 4, "region")]);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The real-world proof for `` `ifdef `` folding: every `.sv`/`.svh`/`.v`
|
||||
//! file under an OpenTitan `hw` tree, through [`folding_ranges`], with the
|
||||
//! ranges checked against the file and the directives counted independently.
|
||||
//!
|
||||
//! `#[ignore]`: it parses four thousand files. Run with
|
||||
//! `LUCISV_OPENTITAN_HW=/path/to/opentitan/hw tools/guard.sh -- cargo test
|
||||
//! --release -p lucisv_server opentitan_sweep -- --ignored --nocapture`;
|
||||
//! without the variable it reads `~/.cache/lucisv-opentitan-full/hw`, and it
|
||||
//! skips (passing, with a line on stderr) when that is not there.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use lsp_types::FoldingRange;
|
||||
|
||||
use super::{branch_folds, directives, folding_ranges, line, scope_and_comment_folds};
|
||||
use crate::state::Document;
|
||||
|
||||
/// The tree: `LUCISV_OPENTITAN_HW`, else the full-tree cache.
|
||||
fn tree() -> Option<PathBuf> {
|
||||
let root = std::env::var_os("LUCISV_OPENTITAN_HW").map(PathBuf::from).or_else(|| {
|
||||
std::env::var_os("HOME")
|
||||
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
|
||||
})?;
|
||||
root.is_dir().then_some(root)
|
||||
}
|
||||
|
||||
/// Every Verilog source under `dir`, sorted so a run is reproducible.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
sources(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The five words, counted on the token stream by a rule written apart from
|
||||
/// the one under test.
|
||||
fn word(token: &Token) -> Option<&'static str> {
|
||||
if token.kind != TokenKind::Directive {
|
||||
return None;
|
||||
}
|
||||
let mut first = token.text.split(|c: char| !c.is_ascii_alphanumeric() && c != '`' && c != '_');
|
||||
match first.next()? {
|
||||
"`ifdef" => Some("ifdef"),
|
||||
"`ifndef" => Some("ifndef"),
|
||||
"`elsif" => Some("elsif"),
|
||||
"`else" => Some("else"),
|
||||
"`endif" => Some("endif"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same five, counted on the raw text: a line whose first non-blank
|
||||
/// characters spell one. Differs from the token count wherever the lexer knows
|
||||
/// better — a comment, a `` `define `` body.
|
||||
fn text_count(text: &str) -> usize {
|
||||
text.lines()
|
||||
.filter(|l| {
|
||||
let l = l.trim_start();
|
||||
["`ifdef", "`ifndef", "`elsif", "`else", "`endif"].iter().any(|d| {
|
||||
l.strip_prefix(d).is_some_and(|rest| {
|
||||
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
|
||||
})
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct Tally {
|
||||
files: usize,
|
||||
unlexed: usize,
|
||||
tokens: usize,
|
||||
text_lines: usize,
|
||||
opens: usize,
|
||||
nexts: usize,
|
||||
closes: usize,
|
||||
/// `else`/`elsif` and `endif` that found a region open — what
|
||||
/// [`directives::branch_spans`] should emit one span for each of.
|
||||
nexts_matched: usize,
|
||||
closes_matched: usize,
|
||||
/// Regions still open at end of file.
|
||||
unclosed: usize,
|
||||
spans: usize,
|
||||
ranges: usize,
|
||||
not_first_on_line: usize,
|
||||
/// Branch folds left out because an existing fold has the same two lines.
|
||||
same_lines_as_existing: usize,
|
||||
/// Branch folds that share their start line with an existing fold.
|
||||
shared_start: usize,
|
||||
folding: Duration,
|
||||
branches: Duration,
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "reads an OpenTitan checkout; see the module comment"]
|
||||
fn every_opentitan_file_folds_its_ifdef_branches_validly() {
|
||||
let Some(root) = tree() else {
|
||||
eprintln!("opentitan_sweep: no OpenTitan hw tree; skipped");
|
||||
return;
|
||||
};
|
||||
let mut files = Vec::new();
|
||||
sources(&root, &mut files);
|
||||
files.sort();
|
||||
let mut tally = Tally::default();
|
||||
let mut slowest: Vec<(Duration, Duration, PathBuf)> = Vec::new();
|
||||
for path in &files {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
let (folding, branches) = sweep_one(path, text, &mut tally);
|
||||
slowest.push((folding, branches, path.clone()));
|
||||
}
|
||||
slowest.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
eprintln!("opentitan_sweep: {tally:#?}");
|
||||
for (folding, branches, path) in slowest.iter().take(5) {
|
||||
eprintln!(" {folding:?} (branches {branches:?}) {}", path.display());
|
||||
}
|
||||
assert!(tally.files > 0);
|
||||
assert_eq!(tally.spans, tally.nexts_matched + tally.closes_matched, "{tally:#?}");
|
||||
}
|
||||
|
||||
/// Fold one file, check its ranges, and add it to `tally`. Returns the time
|
||||
/// the whole answer took and the time the branch pass alone took.
|
||||
fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration) {
|
||||
tally.files += 1;
|
||||
let by_text = text_count(&text);
|
||||
tally.text_lines += by_text;
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
if doc.tokens.is_empty() {
|
||||
tally.unlexed += 1;
|
||||
eprintln!(" does not lex: {}", path.display());
|
||||
}
|
||||
let lines = doc.line_index.line_col(doc.text.len() as u32).0;
|
||||
|
||||
let started = Instant::now();
|
||||
let ranges = folding_ranges(&doc);
|
||||
let folding = started.elapsed();
|
||||
let started = Instant::now();
|
||||
let spans = directives::branch_spans(&doc.tokens, |t| line(&doc, t.span.start));
|
||||
let branches = started.elapsed();
|
||||
tally.folding += folding;
|
||||
tally.branches += branches;
|
||||
|
||||
for range in &ranges {
|
||||
assert!(range.start_line < range.end_line, "{}: {range:?}", path.display());
|
||||
assert!(range.end_line < lines, "{}: {range:?} past line {lines}", path.display());
|
||||
}
|
||||
check_existing_unchanged(&doc, &ranges, path, tally);
|
||||
let before = tally.tokens;
|
||||
let directive_lines = check_directives(&doc, path, tally);
|
||||
if tally.tokens - before != by_text {
|
||||
let tokens = tally.tokens - before;
|
||||
eprintln!(" {by_text} by text, {tokens} by token: {}", path.display());
|
||||
}
|
||||
tally.spans += spans.len();
|
||||
for &(start, end) in spans.iter().filter(|(s, e)| e > s) {
|
||||
tally.ranges += 1;
|
||||
assert!(directive_lines.contains(&start), "{}: fold at {start}", path.display());
|
||||
assert!(
|
||||
ranges.iter().any(|r| r.start_line == start && r.end_line == end),
|
||||
"{}: branch {start}..{end} missing from the answer",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
(folding, branches)
|
||||
}
|
||||
|
||||
/// Count the directive tokens into `tally` and return the lines they start on.
|
||||
fn check_directives(doc: &Document, path: &Path, tally: &mut Tally) -> Vec<u32> {
|
||||
let mut at = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
for (i, token) in doc.tokens.iter().enumerate() {
|
||||
let Some(word) = word(token) else { continue };
|
||||
tally.tokens += 1;
|
||||
match word {
|
||||
"ifdef" | "ifndef" => {
|
||||
tally.opens += 1;
|
||||
depth += 1;
|
||||
}
|
||||
"elsif" | "else" => {
|
||||
tally.nexts += 1;
|
||||
tally.nexts_matched += usize::from(depth > 0);
|
||||
}
|
||||
_ => {
|
||||
tally.closes += 1;
|
||||
tally.closes_matched += usize::from(depth > 0);
|
||||
depth = depth.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
let start = line(doc, token.span.start);
|
||||
let previous = i.checked_sub(1).map(|p| &doc.tokens[p]);
|
||||
if previous.is_some_and(|p| line(doc, p.span.end.saturating_sub(1)) == start) {
|
||||
tally.not_first_on_line += 1;
|
||||
eprintln!(" not first on line {}: {}:{}", start + 1, path.display(), token.text);
|
||||
}
|
||||
at.push(start);
|
||||
}
|
||||
tally.unclosed += depth;
|
||||
at
|
||||
}
|
||||
|
||||
/// The answer with its branch folds taken out is exactly the scope and
|
||||
/// comment folds alone — same ranges, kinds and order — so no fold that
|
||||
/// existed before this feature is lost, changed or moved.
|
||||
fn check_existing_unchanged(
|
||||
doc: &Document,
|
||||
ranges: &[FoldingRange],
|
||||
path: &Path,
|
||||
tally: &mut Tally,
|
||||
) {
|
||||
let existing = scope_and_comment_folds(doc);
|
||||
let branches = branch_folds(doc, &existing);
|
||||
let rest: Vec<&FoldingRange> = ranges.iter().filter(|r| !branches.contains(r)).collect();
|
||||
assert_eq!(rest, existing.iter().collect::<Vec<_>>(), "{}", path.display());
|
||||
assert_eq!(ranges.len(), existing.len() + branches.len(), "{}", path.display());
|
||||
let spans = directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start));
|
||||
let kept = spans.iter().filter(|(s, e)| e > s).count();
|
||||
tally.same_lines_as_existing += kept - branches.len();
|
||||
for branch in &branches {
|
||||
if existing.iter().any(|r| r.start_line == branch.start_line) {
|
||||
tally.shared_start += 1;
|
||||
eprintln!(" shared start line {}: {}", branch.start_line + 1, path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,7 @@ use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
|
||||
PublishDiagnostics, ShowMessage,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Progress, PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
//! identifiers by `vlog_semantic` + `ExternalResolutions` and for module
|
||||
//! instantiations / `#(...)` parameter lists by `Document.tree`
|
||||
//! (`docs/features/instantiation-highlighting/README.md`). The full mapping
|
||||
//! table is in `docs/features/lucisv-server/README.md`; the range and delta
|
||||
//! rules are in `docs/features/semantic-tokens-delta/README.md`.
|
||||
//!
|
||||
//! One tokenizer and one encoder serve all three requests: classification
|
||||
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
|
||||
//! protocol thinks in), a range answer drops the ones it does not want, and
|
||||
//! `encode` delta-encodes whatever is left from the start of the document.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
mod instantiation;
|
||||
|
||||
/// The legend the server advertises. The index into this array is what the
|
||||
/// wire format carries, so the order is part of the protocol contract and
|
||||
/// must match [`Highlight`].
|
||||
@@ -133,6 +139,7 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
|
||||
/// See `docs/features/large-file-mode/README.md`.
|
||||
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
let window = crate::large::window(doc, range);
|
||||
let overrides = HashMap::new();
|
||||
let mut pieces = Vec::new();
|
||||
// The comment spans the lexer never saw go in first; `flatten` sorts, so
|
||||
// the order they are collected in cannot reach the wire.
|
||||
@@ -140,16 +147,17 @@ pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticTo
|
||||
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
for token in &window.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
encode(&within(flatten(pieces, doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let overrides = instantiation::overrides(doc);
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
@@ -177,12 +185,17 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
/// after it on the same line — because [`flatten`] converts the offsets with a
|
||||
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
|
||||
/// and no two pieces here can start at the same byte.
|
||||
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
fn collect(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
out: &mut Vec<Piece>,
|
||||
) {
|
||||
for comment in &token.leading {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
if let Some(ty) = classify(token, semantics) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
|
||||
if let Some(ty) = classify(token, doc, overrides) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, &doc.semantics) });
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
@@ -190,7 +203,14 @@ fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
}
|
||||
|
||||
/// What a token is, or `None` for the ones this server does not colour.
|
||||
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
fn classify(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
) -> Option<Highlight> {
|
||||
if let Some(&ty) = overrides.get(&token.span.start) {
|
||||
return Some(ty);
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Keyword => Some(Highlight::Keyword),
|
||||
TokenKind::Number => Some(Highlight::Number),
|
||||
@@ -201,8 +221,8 @@ fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
// A macro *usage* lexes as an identifier whose text starts with a
|
||||
// backtick; `is_macro` is the lexer's own public test for it.
|
||||
TokenKind::Ident if token.is_macro() => Some(Highlight::Macro),
|
||||
TokenKind::Ident => Some(identifier_type(token.span.start, semantics)),
|
||||
// Punctuation: deliberately not emitted, see the feature README.
|
||||
TokenKind::Ident => Some(identifier_type(token.span.start, &doc.semantics, &doc.external)),
|
||||
// Punctuation outside `overrides`: deliberately not emitted, see the feature README.
|
||||
TokenKind::Symbol | TokenKind::Eof => None,
|
||||
}
|
||||
}
|
||||
@@ -219,16 +239,28 @@ fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table: its own
|
||||
/// declaration, the declaration it resolves to, or `variable` when nothing in
|
||||
/// this file knows (an external candidate, or a name a macro would produce).
|
||||
fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
|
||||
let symbol = semantics
|
||||
.symbol_at(offset)
|
||||
.or_else(|| semantics.reference_at(offset).and_then(|r| r.resolved()))
|
||||
.and_then(|id| semantics.symbol(id));
|
||||
match symbol {
|
||||
Some(symbol) => symbol_type(symbol.kind),
|
||||
/// What symbol kind `offset` resolves to across the file and workspace overlay.
|
||||
fn resolved_kind(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Option<SymbolKind> {
|
||||
match external.definition_of(semantics, offset)? {
|
||||
Definition::Local(symbol) => Some(symbol.kind),
|
||||
Definition::External(defs) => defs.first().map(|def| def.kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table and workspace
|
||||
/// overlay: its own declaration, the declaration it resolves to, or `variable`
|
||||
/// when nothing resolves it.
|
||||
fn identifier_type(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Highlight {
|
||||
match resolved_kind(offset, semantics, external) {
|
||||
Some(kind) => symbol_type(kind),
|
||||
None => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
@@ -248,7 +280,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
|
||||
SymbolKind::Function | SymbolKind::Task | SymbolKind::Instance => Highlight::Function,
|
||||
SymbolKind::StructMember
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Coverpoint
|
||||
@@ -260,7 +292,6 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
// A property and a sequence are named, instantiated by name and take
|
||||
@@ -728,9 +759,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded tokens with the identifier refinement folded away.
|
||||
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
|
||||
/// Decoded tokens with identifier refinement and AST-only punctuation
|
||||
/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared
|
||||
/// against the full pipeline.
|
||||
fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
let positions = full.positions();
|
||||
decode(data)
|
||||
.into_iter()
|
||||
.filter(|&(line, character, ..)| {
|
||||
let at = positions.offset(Position { line, character });
|
||||
!full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol)
|
||||
})
|
||||
.map(|(l, c, len, ty, _)| (l, c, len, coarse(ty)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether any construct in `doc` crosses `offset` — a block comment, a
|
||||
@@ -792,8 +833,8 @@ mod tests {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
coarsely(&semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&semantic_tokens_in_range(&full, window)),
|
||||
coarsely(&full, &semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&full, &semantic_tokens_in_range(&full, window)),
|
||||
"{}: lines {from}..{to}",
|
||||
path.display()
|
||||
);
|
||||
@@ -889,7 +930,8 @@ mod tests {
|
||||
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
|
||||
// never reaches `pieces` — only the tokens `classify` keeps are
|
||||
// expected on the wire.
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
|
||||
let empty = HashMap::new();
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) {
|
||||
let expected = positions.position(token.span.start);
|
||||
let found = decoded
|
||||
.iter()
|
||||
@@ -1291,4 +1333,129 @@ mod tests {
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// module instantiation and `#(...)` parameter-list highlighting
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn named_tokens(text: &str) -> Vec<(String, u32, u32)> {
|
||||
with_document(text, |doc| {
|
||||
let pos = doc.positions();
|
||||
decode(&semantic_tokens(doc))
|
||||
.into_iter()
|
||||
.map(|(line, character, len, ty, mods)| {
|
||||
let start = pos.offset(Position { line, character }) as usize;
|
||||
let end = pos.offset(Position { line, character: character + len }) as usize;
|
||||
(doc.text[start..end].to_string(), ty, mods)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() {
|
||||
let src = "\
|
||||
module top #(
|
||||
parameter int DATA_W = 32
|
||||
) (
|
||||
input logic clk,
|
||||
input logic rst_ni
|
||||
);
|
||||
logic [DATA_W-1:0] data_q;
|
||||
pkg::uart_core #(
|
||||
.BAUD_DIV (EXT_DIV),
|
||||
.WIDTH (DATA_W),
|
||||
.DEPTH (16)
|
||||
) u_uart (
|
||||
.clk_i (clk),
|
||||
.rst_ni,
|
||||
.data_o (data_q),
|
||||
.*
|
||||
);
|
||||
assign data_q = u_uart.tx_data;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
let find_nth = |word: &str, n: usize| {
|
||||
out.iter()
|
||||
.filter(|(w, ..)| w == word)
|
||||
.nth(n)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}"))
|
||||
};
|
||||
|
||||
// Both `#` tokens (header parameter port list and instantiation overrides)
|
||||
// share `Parameter`, while `(` and `)` are never emitted.
|
||||
assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")"));
|
||||
|
||||
// Scoped module name: `pkg` is Namespace, `uart_core` is Class.
|
||||
assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0));
|
||||
assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0));
|
||||
|
||||
// Parameter overrides: `.` and parameter names share `Parameter` with `#`,
|
||||
// as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number.
|
||||
assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0));
|
||||
|
||||
// Instance declaration and hierarchical use both highlight as `Function`.
|
||||
let fn_ty = Highlight::Function as u32;
|
||||
assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION));
|
||||
assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0));
|
||||
|
||||
// Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`,
|
||||
// while connected signals (`clk`, `data_q`) stay `Variable`.
|
||||
assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_hashes_are_never_classified_as_parameters() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire #5 a;
|
||||
assign #(1:2:3) a = 1'b0;
|
||||
and #(2, 3) g0 (y, a, a);
|
||||
initial #10 $finish;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}");
|
||||
assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub #(
|
||||
.WIDTH(
|
||||
) u0 (
|
||||
.clk_i(
|
||||
.rst_ni(rst_n)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0)));
|
||||
assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0)));
|
||||
reconstructs(MODULE, src);
|
||||
reconstructs(src, MODULE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! AST-guided semantic token overrides for module instantiations and `#(...)`
|
||||
//! parameter lists.
|
||||
//!
|
||||
//! Plain lexical + symbol-table classification leaves an external module's
|
||||
//! name, its `#` parameter sigil, its `.PARAM` overrides and its `.port`
|
||||
//! connections as uncoloured punctuation or generic `variable`s. Walking
|
||||
//! [`Document::tree`] supplies the syntactic role of each token directly from
|
||||
//! the parsed AST, even before workspace indexing finishes or when the
|
||||
//! instantiated unit lives outside the indexed tree.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
BindDirective, ClassDecl, ClassExtends, Connection, Connections, DataType, Expr,
|
||||
GateInstantiation, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, RawText,
|
||||
Typedef, TypedefKind,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use super::{resolved_kind, Highlight};
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// Token-start byte offset -> highlight overrides derived from `doc.tree`.
|
||||
pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
|
||||
let mut out = HashMap::new();
|
||||
if doc.tokens.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let mut ctx = Ctx {
|
||||
tokens: &doc.tokens,
|
||||
semantics: &doc.semantics,
|
||||
external: &doc.external,
|
||||
out: &mut out,
|
||||
};
|
||||
ctx.items(&doc.tree.items);
|
||||
out
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
tokens: &'a [Token],
|
||||
semantics: &'a Semantics,
|
||||
external: &'a ExternalResolutions,
|
||||
out: &'a mut HashMap<u32, Highlight>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn items(&mut self, items: &[Item]) {
|
||||
for item in items {
|
||||
self.item(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn item(&mut self, item: &Item) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => self.module(m, item.span.end),
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
self.items(items)
|
||||
}
|
||||
ItemKind::Class(c) => self.class(c, item.span.end),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst, item.span.end),
|
||||
ItemKind::Bind(bind) => self.bind(bind, item.span.end),
|
||||
ItemKind::GateInstantiation(gate) => self.gate(gate),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items),
|
||||
ItemKind::GenIf(g) => {
|
||||
self.items(&g.then.items);
|
||||
self.gen_else(g.els.as_deref());
|
||||
}
|
||||
ItemKind::GenFor(g) => self.items(&g.body.items),
|
||||
ItemKind::GenCase(g) => {
|
||||
for arm in &g.items {
|
||||
self.items(&arm.body.items);
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.data_type(&d.ty),
|
||||
ItemKind::PortDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::ParamDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::Typedef(t) => self.typedef(t),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_else(&mut self, els: Option<&GenElse>) {
|
||||
match els {
|
||||
Some(GenElse::If(_, inner)) => {
|
||||
self.items(&inner.then.items);
|
||||
self.gen_else(inner.els.as_deref());
|
||||
}
|
||||
Some(GenElse::Block(block)) => self.items(&block.items),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn module(&mut self, m: &Module, end: u32) {
|
||||
if m.param_ports.is_some() {
|
||||
let last = m.imports.last().and_then(|imp| imp.paths.last());
|
||||
let from = last.map_or(m.name_span.end, |p| p.item.span.end);
|
||||
self.param_hash(from, end);
|
||||
}
|
||||
for elem in m.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
if let PortList::Ansi(ports) = &m.ports {
|
||||
for elem in ports {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.items(&m.items);
|
||||
}
|
||||
|
||||
fn class(&mut self, c: &ClassDecl, end: u32) {
|
||||
if c.param_ports.is_some() {
|
||||
self.param_hash(c.name_span.end, end);
|
||||
for elem in c.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ext) = &c.extends {
|
||||
self.class_extends(ext);
|
||||
}
|
||||
self.items(&c.items);
|
||||
}
|
||||
|
||||
fn class_extends(&mut self, ext: &ClassExtends) {
|
||||
self.scoped_unit(ext.name_span);
|
||||
if let Some(params) = &ext.params {
|
||||
self.param_hash(ext.name_span.end, ext.span.end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
}
|
||||
|
||||
fn typedef(&mut self, t: &Typedef) {
|
||||
if let TypedefKind::Alias(ty) = &t.kind {
|
||||
self.data_type(ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn data_type(&mut self, ty: &DataType) {
|
||||
if let Some(params) = ty.params() {
|
||||
self.param_hash(params.span.start, params.span.end);
|
||||
}
|
||||
}
|
||||
|
||||
fn instantiation(&mut self, inst: &Instantiation, end: u32) {
|
||||
self.scoped_unit(inst.module_span);
|
||||
if let Some(params) = &inst.params {
|
||||
self.param_hash(inst.module_span.end, end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
for instance in &inst.instances {
|
||||
self.ident_at(instance.name_span, Highlight::Function);
|
||||
self.port_connections(&instance.conns);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self, b: &BindDirective, end: u32) {
|
||||
if let [only] = &b.target[..] {
|
||||
let kind = resolved_kind(only.span.start, self.semantics, self.external);
|
||||
if only.index.is_none() && kind != Some(SymbolKind::Instance) {
|
||||
self.ident_at(only.span, Highlight::Class);
|
||||
}
|
||||
}
|
||||
for inst in &b.instances {
|
||||
self.ident_at(inst.span, Highlight::Function);
|
||||
}
|
||||
self.instantiation(&b.inst, end);
|
||||
}
|
||||
|
||||
fn gate(&mut self, g: &GateInstantiation) {
|
||||
for inst in &g.instances {
|
||||
if let Some(span) = inst.name_span {
|
||||
self.ident_at(span, Highlight::Function);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_overrides(&mut self, params: &[ListElem<Connection>]) {
|
||||
for elem in params {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => {
|
||||
self.named_entry(conn, Highlight::Parameter);
|
||||
if let Some(expr) = &conn.expr {
|
||||
self.param_expr(expr);
|
||||
}
|
||||
}
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Parameter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn port_connections(&mut self, conns: &Connections) {
|
||||
let Connections::Named(list) = conns else { return };
|
||||
for elem in list {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => self.named_entry(conn, Highlight::Property),
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Property),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn named_entry(&mut self, conn: &Connection, ty: Highlight) {
|
||||
if conn.name_span.is_empty() {
|
||||
return;
|
||||
}
|
||||
for tok in self.tokens_in(TextRange::new(conn.span.start, conn.name_span.start)) {
|
||||
if tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
for tok in self.tokens_in(conn.name_span) {
|
||||
if (tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recovered_entry(&mut self, raw: &RawText, ty: Highlight) {
|
||||
let mut saw_dot = false;
|
||||
for tok in self.tokens_in(raw.span) {
|
||||
if tok.kind == TokenKind::Attribute {
|
||||
continue;
|
||||
}
|
||||
if !saw_dot && tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
saw_dot = true;
|
||||
continue;
|
||||
}
|
||||
if saw_dot && ((tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*")) {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fn param_expr(&mut self, expr: &Expr) {
|
||||
if expr.span.is_empty() {
|
||||
return;
|
||||
}
|
||||
let start = first_token_from(self.tokens, expr.span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= expr.span.end);
|
||||
for (idx, tok) in slice[..len].iter().enumerate() {
|
||||
if tok.kind != TokenKind::Ident || tok.is_macro() {
|
||||
continue;
|
||||
}
|
||||
if resolved_kind(tok.span.start, self.semantics, self.external).is_some() {
|
||||
continue;
|
||||
}
|
||||
let abs = start + idx;
|
||||
let next = self.tokens.get(abs + 1);
|
||||
let prev = abs.checked_sub(1).and_then(|i| self.tokens.get(i));
|
||||
let ty = if next.is_some_and(|t| t.is_sym("::")) {
|
||||
Highlight::Namespace
|
||||
} else if next.is_some_and(|t| t.is_sym("(")) && !prev.is_some_and(|t| t.is_sym(".")) {
|
||||
Highlight::Function
|
||||
} else {
|
||||
Highlight::Parameter
|
||||
};
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn scoped_unit(&mut self, span: TextRange) {
|
||||
let idents: Vec<&Token> = self
|
||||
.tokens_in(span)
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Ident && !t.is_macro())
|
||||
.collect();
|
||||
let Some((&last, prefix)) = idents.split_last() else { return };
|
||||
for &seg in prefix {
|
||||
self.out.insert(seg.span.start, Highlight::Namespace);
|
||||
}
|
||||
self.out.insert(last.span.start, Highlight::Class);
|
||||
}
|
||||
|
||||
fn ident_at(&mut self, span: TextRange, ty: Highlight) {
|
||||
for tok in self.tokens_in(span) {
|
||||
if tok.kind == TokenKind::Ident && !tok.is_macro() {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_hash(&mut self, from: u32, until: u32) {
|
||||
let start = first_token_from(self.tokens, from);
|
||||
for tok in self.tokens.get(start..).unwrap_or(&[]) {
|
||||
if tok.span.start >= until || tok.is_sym("(") || tok.is_sym(";") {
|
||||
break;
|
||||
}
|
||||
if tok.is_sym("#") {
|
||||
self.out.insert(tok.span.start, Highlight::Parameter);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens_in(&self, span: TextRange) -> &'a [Token] {
|
||||
if span.is_empty() {
|
||||
return &[];
|
||||
}
|
||||
let start = first_token_from(self.tokens, span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= span.end);
|
||||
&slice[..len]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! `` `ifdef `` branch folds over the wire: spawn the real binary, open a
|
||||
//! buffer, ask `textDocument/foldingRange`, and read back the exact ranges an
|
||||
//! editor (and VS Code's sticky scroll, which pins every fold's first line)
|
||||
//! receives. The shape itself is pinned by the unit tests beside
|
||||
//! `src/folding.rs`; this checks it survives serialisation and dispatch.
|
||||
//! See `docs/features/ifdef-folding/README.md`.
|
||||
//!
|
||||
//! The framing is repeated from `e2e.rs` rather than shared: an integration
|
||||
//! test file is its own crate, and the helpers are twenty lines.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn frame(payload: &str) -> String {
|
||||
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
|
||||
}
|
||||
|
||||
fn read_message(input: &mut impl BufRead) -> Option<Value> {
|
||||
let mut length = None;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if input.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return None;
|
||||
}
|
||||
let trimmed = line.trim_end_matches(['\r', '\n']);
|
||||
if trimmed.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
|
||||
length = value.parse::<usize>().ok();
|
||||
}
|
||||
}
|
||||
let mut body = vec![0u8; length?];
|
||||
input.read_exact(&mut body).ok()?;
|
||||
serde_json::from_slice(&body).ok()
|
||||
}
|
||||
|
||||
/// Run one session and return every message the server wrote. The OS cache
|
||||
/// directory is pointed into the temp dir, as `e2e.rs` does, so the index
|
||||
/// cache never lands in the developer's home.
|
||||
fn talk(dir: &std::path::Path, session: &str) -> Vec<Value> {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
|
||||
.env("HOME", dir)
|
||||
.env("XDG_CACHE_HOME", dir.join("cache"))
|
||||
.env("LOCALAPPDATA", dir.join("cache"))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("the server binary starts");
|
||||
child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session");
|
||||
let mut stdout = BufReader::new(child.stdout.take().expect("stdout"));
|
||||
let mut out = Vec::new();
|
||||
while let Some(message) = read_message(&mut stdout) {
|
||||
out.push(message);
|
||||
}
|
||||
assert!(child.wait().expect("the server exits").success());
|
||||
out
|
||||
}
|
||||
|
||||
const SOURCE: &str = concat!(
|
||||
"module top;\n", // 0
|
||||
"`ifdef FAST\n", // 1
|
||||
" wire a;\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`elsif SLOW\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`else\n", // 6
|
||||
" `ifndef TINY\n", // 7
|
||||
" wire d;\n", // 8
|
||||
" `endif\n", // 9
|
||||
"`endif\n", // 10
|
||||
"endmodule\n", // 11
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn ifdef_branches_come_back_as_region_folds_over_the_wire() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_ifdef_folding_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", dir.join("top.sv").display());
|
||||
let open = json!({
|
||||
"jsonrpc": "2.0", "method": "textDocument/didOpen",
|
||||
"params": { "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": SOURCE
|
||||
} }
|
||||
});
|
||||
let ask = json!({
|
||||
"jsonrpc": "2.0", "id": 2, "method": "textDocument/foldingRange",
|
||||
"params": { "textDocument": { "uri": uri } }
|
||||
});
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&open.to_string()),
|
||||
frame(&ask.to_string()),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&dir, &session);
|
||||
let response = messages.iter().find(|m| m["id"] == 2).expect("a foldingRange response");
|
||||
let folds: Vec<(u64, u64, String)> = response["result"]
|
||||
.as_array()
|
||||
.expect("a folding list")
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let line = |key: &str| f[key].as_u64().expect("a line");
|
||||
(line("startLine"), line("endLine"), f["kind"].as_str().unwrap_or("").to_string())
|
||||
})
|
||||
.collect();
|
||||
let region = |start, end| (start, end, "region".to_string());
|
||||
assert_eq!(
|
||||
folds,
|
||||
vec![region(0, 10), region(1, 3), region(4, 5), region(6, 9), region(7, 8)],
|
||||
"the module, then `ifdef`, `elsif`, `else` and the nested `ifndef`"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -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`.
|
||||
@@ -0,0 +1,567 @@
|
||||
# hierarchy-current-path
|
||||
|
||||
## Goal
|
||||
|
||||
The owner (TODO §71.6): "In the module view, always highlight the current open
|
||||
file and its parents, in different shade. Light bright orange for the instance,
|
||||
and getting dimmer the further it goes … I just want easy understanding of the
|
||||
hierarchical view." The Hierarchy pane now lights every row whose module is
|
||||
declared in the active editor's file (level 0, a light bright orange) and every
|
||||
row whose module is above it in the design, one shade dimmer per
|
||||
instantiation level, down to a floor that stays distinguishable from an unlit
|
||||
row. A module instantiated in several places lights every instance and each
|
||||
instance's chain; where chains meet, the nearer distance wins. It works on a
|
||||
closed tree (the root, or a section header, says the file is in there), costs
|
||||
no snapshot request, and repaints only the rows whose level changed. A boolean
|
||||
setting, `lucisv.hierarchy.highlightCurrent` (default on), turns it off.
|
||||
|
||||
### Mechanism, and why
|
||||
|
||||
The brief assumed a `TreeView`, where a row's background cannot be painted and
|
||||
the candidates are a `FileDecorationProvider` (label colour + badge), a
|
||||
`ThemeIcon` colour or label highlights. **The Hierarchy pane is not a
|
||||
`TreeView`: it is a `WebviewView`** (`registerWebviewViewProvider` in
|
||||
`hierarchyView.js`, rows drawn by `media/hierarchy.js`). A webview can paint a
|
||||
row's whole background with CSS, which is the most legible of all the options,
|
||||
so that is what this does. The colours are still real theme colours:
|
||||
|
||||
- They are contributed through `contributes.colors` (five ids, with `dark`,
|
||||
`light`, `highContrast` and `highContrastLight` defaults), so a user or a
|
||||
theme overrides them with `workbench.colorCustomizations`.
|
||||
- **Verified, 2026-11-19:** the contribution handler
|
||||
(`src/vs/workbench/services/themes/common/colorExtensionPoint.ts`, VS Code
|
||||
`main`) calls `colorRegistry.registerColor` for every contributed id (id
|
||||
pattern `^\w+[.\w+]*$`; `highContrastLight` falls back to `light`,
|
||||
`highContrast` to `dark`); the webview theming
|
||||
(`src/vs/workbench/contrib/webview/browser/themeing.ts`) iterates
|
||||
`getColorRegistry().getColors()` and exports each resolved colour as
|
||||
`'vscode-' + entry.id.replace('.', '-')`. So a contributed colour reaches the
|
||||
webview as a CSS variable — **with only the first dot replaced** (a plain
|
||||
string `replace`). Every id here therefore has exactly one dot
|
||||
(`lucisv.hierarchyCurrent` → `--vscode-lucisv-hierarchyCurrent`), and a test
|
||||
pins that. The public guides (code.visualstudio.com/api/extension-guides/webview,
|
||||
…/references/contribution-points) document the `--vscode-` naming and the
|
||||
`contributes.colors` shape but say nothing about contributed colours inside
|
||||
webviews; the source is the authority used.
|
||||
- The same source lists the body classes `vscode-light`, `vscode-dark`,
|
||||
`vscode-high-contrast`, `vscode-high-contrast-light`; the high-contrast rule
|
||||
adds the theme's `contrastActiveBorder` around the current row (not on a
|
||||
bookmarked one, whose border is the bookmark's).
|
||||
|
||||
**Two layers per lit row, both `background-image`s**, so they sit over whatever
|
||||
the row already has — hover, the opaque sticky section header — instead of
|
||||
replacing it:
|
||||
|
||||
1. **A translucent tint**, kept light enough that the label stays at or above
|
||||
WCAG AA (4.5:1) on every level, hovered or not, in Dark Modern, Dark+, Light
|
||||
Modern, Light+, HC dark and HC light. `hierarchyPalette_test.js` blends the
|
||||
`package.json` defaults over those themes' sidebar and hover colours and
|
||||
fails under 4.5:1, or when neighbouring levels are closer than ΔE76 3.
|
||||
2. **A bar at the left edge** (`lucisv.hierarchyCurrentBar`, opaque) that
|
||||
carries the "brightest" the tint gave up for legibility. On the current row
|
||||
it is a solid 4px light bright orange, fully opaque. Each level up it gets
|
||||
narrower and fainter: 3px at 80 %, 2px at 65 %, then 2px dashed at 55 %,
|
||||
then 1px dashed at 45 %. Width and dash are the cue that does not depend on
|
||||
colour, which is what high-contrast themes need for levels 1–4 (QA F3). The
|
||||
current row's label is also bold. The test asserts the opaque bar is at
|
||||
least 3:1 against the sidebar (WCAG 1.4.11, non-text contrast).
|
||||
|
||||
*Why this and not a darker tint per theme kind:* a tint dark enough to keep
|
||||
light text readable on a dark sidebar stops reading as "light bright orange".
|
||||
The bar can be that orange at full strength, because no text sits on it. So the
|
||||
tint does legibility and the bar does brightness.
|
||||
|
||||
**A bookmark wins:** a bookmarked row keeps its yellow fill and border and drops
|
||||
the tint. The bar stays, so a bookmarked current row still says it is current.
|
||||
|
||||
**Forced colours** (Windows High Contrast / `forced-colors: active`) drop every
|
||||
background image, so the tint and the bar are gone and **levels 1–4 have no
|
||||
cue there**. The current row keeps a dashed `CanvasText` *border* and its bold
|
||||
label. It is a border rather than an outline, so the focus ring and the
|
||||
bookmark's 2px outline stay as they were (QA F4).
|
||||
|
||||
| level | colour id | meaning | dark | light | HC dark | HC light |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 0 | `lucisv.hierarchyCurrent` | module declared in the active file | `#FFB34745` | `#FFC26661` | `#FFB34780` | `#FF8C0099` |
|
||||
| 1 | `lucisv.hierarchyParent1` | one level above | `#FFB34730` | `#FFC2664F` | `#FFB34761` | `#FF8C0073` |
|
||||
| 2 | `lucisv.hierarchyParent2` | two levels above | `#FFB34721` | `#FFC2663B` | `#FFB34745` | `#FF8C0052` |
|
||||
| 3 | `lucisv.hierarchyParent3` | three levels above | `#FFB34716` | `#FFC26629` | `#FFB3472B` | `#FF8C0033` |
|
||||
| 4 | `lucisv.hierarchyAncestor` | four or more (the floor) | `#FFB3470D` | `#FFC26615` | `#FFB34717` | `#FF8C001A` |
|
||||
| bar | `lucisv.hierarchyCurrentBar` | left-edge bar, every level | `#FFB347` | `#C86400` | `#FFB347` | `#B35900` |
|
||||
|
||||
Light themes use a paler orange (`#FFC266`) than dark ones. Light+ is the
|
||||
tightest theme: its list foreground `#616161` is only about 5.0:1 on its hover
|
||||
colour to begin with. Searching the hue showed `#FFC266` gives the widest steps
|
||||
under that limit among the oranges (ΔE ≥ 3.9). `#FFBF00` does better, but it is
|
||||
amber and too close to the yellow bookmark.
|
||||
|
||||
### What "distance" means
|
||||
|
||||
A row's distance is a property of its **module**: how many instantiation levels
|
||||
it sits above the nearest module declared in the active file (0 for that
|
||||
module). The level below a row is its module's own instance list wherever the
|
||||
row sits, so every row of a module has the same answer, and one breadth-first
|
||||
walk *up* the module graph from all current modules at once (the reverse index
|
||||
`hierarchySections.parentIndex` already builds) answers it for every module.
|
||||
|
||||
- **Plain tree and a DUT's forward section:** the lit rows are exactly the
|
||||
paths from the root down to every current instance, brightest at the bottom.
|
||||
A forward row that cannot open (leaf, `recursive` repeat, unresolved or
|
||||
ambiguous type) is lit only when it is itself current — what it would lead
|
||||
to is not under it on screen.
|
||||
- **"Parents of <DUT>" (upward tree):** the same rule — the rows lit are the
|
||||
active file's own parents among the DUT's parents, dimmer the further up the
|
||||
design, which on that tree is further *down* the page. With `leaf.sv` active
|
||||
under `tb → dut → leaf`, it shows `dut` at 1 and `tb` at 2. An upward row is
|
||||
always its own module, so a `recursive` repeat there is still lit.
|
||||
- **Section headers** light one step dimmer than the nearest module the section
|
||||
holds, shown or not: a forward section that holds the current module lights
|
||||
its header at 1; an upward section lights at 1 + the nearest distance in the
|
||||
DUT's ancestor closure. That is what tells the user a *closed* section holds
|
||||
the file (or its parents).
|
||||
- **Search results are not lit**: a flat hit has no path to light.
|
||||
|
||||
### Cost
|
||||
|
||||
Per active-file change, with M modules, E resolved instances, R rows on screen:
|
||||
|
||||
- one URI comparison per distinct definition file (≤ M), then the upward BFS —
|
||||
O(M + E), and in practice only the current module's ancestor closure is
|
||||
visited;
|
||||
- per upward section header, one walk of the DUT's ancestor closure, memoized
|
||||
on the path for the life of that (snapshot, file) pair;
|
||||
- one map lookup per row on screen — O(R);
|
||||
- a `lit` message carrying only the `[id, level | null]` pairs that changed;
|
||||
the webview sets `data-lit` on those buttons, looked up in an id → button map
|
||||
it builds at render. **No snapshot request, no row rebuild, no re-render.**
|
||||
|
||||
A render (opening a row, a refresh) reuses the cached path for the same
|
||||
(snapshot, file) pair, so it adds only the O(R) lookups. Ids are untouched, so
|
||||
expansion state survives every relight.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **"Declared in the active file" is `module.definition.uri` equal to the
|
||||
editor's URI** after both go through `vscode.Uri.parse(...).toString()`
|
||||
(the server and VS Code may percent-encode a path differently). The
|
||||
comparison is asked once per distinct file. A module declared in a file the
|
||||
snapshot reaches only through `` `include`` is attributed to whichever URI the
|
||||
server put in its definition.
|
||||
- **What that comparison does and does not fold.** `Uri.parse` + `toString`
|
||||
lowercases a Windows drive letter and encodes `:` as `%3A`, so the server's
|
||||
`file:///C:/x/top.sv` matches VS Code's `file:///c%3A/x/top.sv`. It does
|
||||
**not** fold the case of directory or file names: on a case-insensitive file
|
||||
system (win32, default darwin), a filelist that spells `C:\Proj\rtl` where
|
||||
the editor opened `c:\proj\rtl` lights nothing. **UNC paths do not light
|
||||
either**: the server writes `\\srv\share\a.sv` as `file:////srv/share/a.sv`
|
||||
and VS Code as `file://srv/share/a.sv` (see Handshakes, note for the lead).
|
||||
Both read from source by QA, not executed.
|
||||
- **An ambiguous or unresolved instance names no one module**, so it is never
|
||||
current and never leads anywhere: the declaration rows themselves (roots) are
|
||||
still lit.
|
||||
- **In a recursive component a forward row may be lit with nothing lit below
|
||||
it**: the shortest path in the module graph can run through a module the tree
|
||||
cuts as `recursive` on that particular path. Documented rather than fixed —
|
||||
it needs a per-path walk, which is what this design avoids. It is not rare in
|
||||
dense cycles: QA's property run over 1 500 random cyclic graphs of 3–6
|
||||
modules found 1 165 lit open rows with no child one level brighter (e.g.
|
||||
`m0:[m1,m2] m1:[m3,m5] m2:[m1] m3:[m2,m4] m4:[m1,m3] m5:[m0,m4]`, `m3`
|
||||
current: `m0 › m1 › m3 › u (m2)` is lit at 2 and its only child is a cut
|
||||
`m1`). Acyclic designs, and a self-instantiating module, never show it.
|
||||
- **Focus moving to a panel or a webview is not a new file.**
|
||||
`onDidChangeActiveTextEditor(undefined)` with editors still visible keeps the
|
||||
current lighting; with none visible it clears. An `output`-scheme editor (the
|
||||
Output panel) is ignored. Any other non-HDL file (a README, a diff side) lights
|
||||
nothing.
|
||||
- **A bookmark beats the tint** on the same row; the bar and the current row's
|
||||
bold label still show.
|
||||
- **The theme table in `hierarchyPalette_test.js` is representative, not
|
||||
exhaustive**: the built-in Dark Modern, Dark+, Light Modern, Light+, HC dark
|
||||
and HC light sidebar, foreground and hover colours. A third-party theme with
|
||||
a very different sidebar is not measured; its author or the user can override
|
||||
the six colours.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `hierarchySections.parentIndex(model)` — the module → instantiating edges
|
||||
index, memoized on the model. Unchanged.
|
||||
- `hierarchySections.headerId(section)` — **now exported** (additive; it was
|
||||
module-private). Used to find a header row's section.
|
||||
- Tree nodes from `hierarchyModel.rootNode`/`instanceNode` and
|
||||
`hierarchySections.upNode`/`upRootNode`: reads `definition`, `moduleId`,
|
||||
`hasChildren`, `up`. Unchanged.
|
||||
|
||||
### `hierarchyCurrent.js` → `hierarchyView.js`
|
||||
|
||||
- `matchingFiles(model, sameFile)` → the model's spellings of the active file.
|
||||
- `currentPath(model, files)` → the distance state, or `undefined`.
|
||||
- `rowLevels(rows, nodes, list, path)` → `Map<rowId, level>` for lit rows only.
|
||||
- `levelChanges(before, after)` → `[id, level | null][]`.
|
||||
- `LIT_COLORS`, `litLevel`, `cssVariableFor` — the level ↔ colour contract.
|
||||
|
||||
### `hierarchyView.js` → `media/hierarchy.js` (the wire inside the extension)
|
||||
|
||||
- A `render` row carries `lit: <0..4>` **only when lit**; an unlit pane's rows
|
||||
are byte-identical to before this feature (the existing "unstar restores the
|
||||
pane exactly" assertion still holds).
|
||||
- New message `{ type: 'lit', changes: [[id, level | null], …] }`, tree rows
|
||||
only. The renderer sets or removes `data-lit` on the matching buttons.
|
||||
- `treeOrSections` now returns `{ rows, nodes, bookmarkId, list }` (`list` is
|
||||
the section list, `[]` for the plain tree). Internal to the view.
|
||||
|
||||
### Scope deviation, flagged for the lead
|
||||
|
||||
The brief's file list did not name `editors/vscode/media/hierarchy.js` and
|
||||
`media/hierarchy.css`, because it assumed a `TreeView`. The pane is a webview
|
||||
and those two files *are* its rows; nothing is visible without them. The edits
|
||||
are small and additive (a `lit` message handler, `data-lit` per row, the CSS
|
||||
block for five levels). The dut-hierarchy lane edited the same renderer under
|
||||
the same reasoning. Please confirm the other lane does not own them.
|
||||
|
||||
`extension.js` needed **no** change: the view subscribes to
|
||||
`onDidChangeActiveTextEditor` and the setting itself.
|
||||
|
||||
### Note for the lead — UNC URIs (not a request; nothing acted on)
|
||||
|
||||
`crates/lucisv_server/src/uri.rs:20-28` turns `\\srv\share\a.sv` into
|
||||
`file:////srv/share/a.sv` (four slashes, empty authority), where VS Code uses
|
||||
`file://srv/share/a.sv` (authority `srv`). This predates this feature and is
|
||||
outside its scope. Here it means a module declared on a UNC path never lights,
|
||||
and it probably affects any other client-side comparison against server URIs.
|
||||
QA F6, from reading the source, not executed.
|
||||
|
||||
### The server — nothing
|
||||
|
||||
The snapshot already carries each module's declaring file
|
||||
(`definition.file` in the schema-2 file table). No request or schema change.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Pure module `hierarchyCurrent.js`: distance per module (BFS up),
|
||||
per-row levels, header levels, changes diff, colour contract.
|
||||
- [x] Headless tests `hierarchyCurrent_test.js` (18 checks: 15 by the dev,
|
||||
3 added by QA).
|
||||
- [x] Palette regression test `hierarchyPalette_test.js` (4 checks over 6
|
||||
themes): label ≥ 4.5:1 on every level, hovered too; neighbours ΔE ≥ 3;
|
||||
brightest first; bar ≥ 3:1.
|
||||
- [x] QA fix round: F1 contrast, F2 distinct levels, F3 HC bookmark + non-colour
|
||||
cue, F4 forced colours, F7 renderer guard, F8 count, F5/F6 documented.
|
||||
- [x] View wiring: active-editor tracking, cached path per (snapshot, file),
|
||||
`lit` on render rows, in-place `lit` message, setting.
|
||||
- [x] View test: relight posts only changed rows, no request, no render;
|
||||
ignores unchanged file / focus loss / Output; setting off and on;
|
||||
closing all editors clears.
|
||||
- [x] Renderer and CSS (`media/`): `data-lit`, gradient tint, bookmark wins,
|
||||
high-contrast border, forced-colors outline.
|
||||
- [x] `package.json`: five tints and the bar colour, `lucisv.hierarchy.highlightCurrent`.
|
||||
- [x] `.vscodeignore` excludes `hierarchyCurrent_test.js` and
|
||||
`hierarchyPalette_test.js`; `RELEASING.md`
|
||||
lists `hierarchyCurrent.js` as a runtime module (`release.sh` has no
|
||||
such list).
|
||||
- [x] Extension README: feature row and setting row.
|
||||
- [ ] Visual check in a running VS Code (cannot be done by the dev agent; see
|
||||
the work log).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev (Opus 5.5)
|
||||
|
||||
- Read the sidebar, dut-hierarchy and hierarchy feature docs and the view code.
|
||||
Found the pane is a `WebviewView`, not a `TreeView`, which removes the
|
||||
premise of the mechanism question: row backgrounds are paintable. Chose CSS
|
||||
backgrounds driven by contributed theme colours; verified in VS Code's source
|
||||
that contributed colours reach webviews and that only the first dot of the id
|
||||
becomes a dash (see Goal → Mechanism).
|
||||
- First design lit the upward "Parents of" tree by *tree* direction (a row lit
|
||||
when the current file is below it on the page). Its own test showed the flaw:
|
||||
with `leaf.sv` open, that section shows `dut` and `tb` — leaf's parents — and
|
||||
lit neither. Switched to one meaning everywhere: distance = instantiation
|
||||
levels above the current module. Dropped the second (downward) BFS that the
|
||||
first design needed.
|
||||
- Headers: first cut was "root distance + 1"; replaced by "one dimmer than the
|
||||
nearest module the section holds", which is the only version that means the
|
||||
same thing for forward and upward sections.
|
||||
- Tests before: 10 files under `node --test editors/vscode/*_test.js`, all
|
||||
passing. After: 11 files, all passing (`hierarchyCurrent_test.js` is new, 15
|
||||
checks; `hierarchyView_test.js` gained one scenario).
|
||||
- **Not verified:** the rendered colours in a real VS Code (no editor access);
|
||||
the `.vsix` contents (`vsce` is not installed in this tree). Human check:
|
||||
1. Open a design, open the Hierarchy pane, open a leaf module's file: the
|
||||
root row is tinted even while closed; open it — each level brighter to the
|
||||
leaf, which is bold and brightest orange.
|
||||
2. Open a module instantiated twice: both instance rows and both chains lit.
|
||||
3. Switch files: the tint moves without the "Loading hierarchy…" status and
|
||||
without collapsing anything.
|
||||
4. Star a DUT: the DUT section and the "Parents of" section light; close
|
||||
them — the headers stay tinted when they hold the file.
|
||||
5. Bookmark a lit row: yellow wins. Hover a lit row: tint over hover.
|
||||
6. Light, dark, high-contrast dark and light themes: the floor (level 4,
|
||||
use a design ≥ 5 levels deep) is still visible against the sidebar.
|
||||
7. `"lucisv.hierarchy.highlightCurrent": false` clears it live; `true`
|
||||
restores it.
|
||||
8. `workbench.colorCustomizations` with `"lucisv.hierarchyCurrent": "#00ff0080"`
|
||||
recolours the current row.
|
||||
9. After packaging: `unzip -l dist/lucisv-<v>.vsix | grep hierarchyCurrent`
|
||||
prints `extension/hierarchyCurrent.js` and no `_test`.
|
||||
|
||||
### 2026-11-19 — dev (QA fix round, Opus 5.5)
|
||||
|
||||
- **F1 contrast.** The tints are now lighter, and the brightness moved to a new
|
||||
opaque left-edge bar (`lucisv.hierarchyCurrentBar`). Reasons are under Goal →
|
||||
Mechanism. The tint alphas were placed from measurements: for each theme
|
||||
kind, the most tint that keeps label text ≥ 4.55:1 on both the sidebar and
|
||||
the hover colour, then five levels spread evenly in ΔE between that and an
|
||||
unlit row. Light themes moved to `#FFC266` after a hue search (Light+ is
|
||||
the binding constraint). Ratios of label text on the level-0 row:
|
||||
|
||||
| theme | before (QA) | after | after, hovered | after, levels 1–4 |
|
||||
|---|---|---|---|---|
|
||||
| Dark Modern | 3.68 | **5.91** | 4.72 | 7.39 8.51 9.42 10.09 |
|
||||
| Dark+ | 3.32 | **5.14** | 4.72 | 6.25 7.25 7.98 8.62 |
|
||||
| Light Modern | 7.61 | **8.99** | 8.72 | 9.26 9.62 9.85 10.23 |
|
||||
| Light+ | 4.09 | **4.83** | 4.56 | 4.98 5.13 5.25 5.41 |
|
||||
| HC dark | 4.67 | **6.17** | — | 8.93 12.46 16.23 18.86 |
|
||||
| HC light | 8.14 | **8.64** | — | 9.82 11.00 12.24 13.30 |
|
||||
|
||||
Every level, hovered or not, is now ≥ 4.56:1 (hovered levels 1–4 are in
|
||||
the `LUCISV_PALETTE_TABLE=1` output). The bar against the sidebar: Dark
|
||||
Modern 9.97, Dark+ 8.60, Light Modern 3.75, Light+ 3.59, HC dark 11.79,
|
||||
HC light 4.83 (all ≥ 3:1).
|
||||
- **F2 distinct levels.** ΔE76 between neighbours, as 0/1, 1/2, 2/3, 3/4 and
|
||||
floor/unlit:
|
||||
|
||||
| theme | before (QA) | after |
|
||||
|---|---|---|
|
||||
| Dark Modern | 14.5 10.7 5.8 **3.0** 14.2 | 9.0 6.2 5.1 3.7 6.4 |
|
||||
| Dark+ | 13.9 10.4 5.3 **2.7** 13.2 | 8.0 6.4 4.6 4.0 5.3 |
|
||||
| Light Modern | 14.5 7.6 4.4 **1.8** 9.0 | 4.4 4.0 4.5 3.9 4.6 |
|
||||
| Light+ | 14.4 7.6 4.3 **1.8** 9.0 | 3.9 4.3 4.0 4.2 4.6 |
|
||||
| HC dark | 19.8 10.7 12.0 7.2 16.0 | 12.6 12.1 12.7 11.3 7.4 |
|
||||
| HC light | 15.7 8.4 6.2 3.7 10.4 | 15.2 12.8 11.6 9.1 9.1 |
|
||||
|
||||
So five levels stay: every neighbour pair is ≥ 3.7, where the old palette
|
||||
had pairs at 1.8. The steps are smaller than before because the whole range
|
||||
is smaller (the price of legible text), but they are now even. On top of the
|
||||
tint, the bar's width and dash differ at every level.
|
||||
- **Regression test** `editors/vscode/hierarchyPalette_test.js` (new, listed
|
||||
in `.vscodeignore`). It computes all of the above from `package.json`'s
|
||||
defaults and fails under 4.5:1 text, under ΔE 3 between neighbours, if the
|
||||
levels are not brightest-first, or under 3:1 for the bar. Proven to bite:
|
||||
pointed at a copy of the manifest with the old level-0 defaults, it fails
|
||||
with "Dark Modern: label on level 0 is 3.68:1, under 4.5".
|
||||
`LUCISV_PALETTE_TABLE=1` prints the table.
|
||||
- **F3.** The HC border rule is now `:not(.bookmarked)`, so a bookmarked
|
||||
current row keeps the bookmark's border. Levels 1–4 get a cue that is not
|
||||
colour in every theme: bar width and style (4 solid, 3 solid, 2 solid,
|
||||
2 dashed, 1 dashed). A bookmarked lit row keeps its bar too
|
||||
(`.row.bookmarked[data-lit]`), so "bookmark wins" now means fill and border.
|
||||
- **F4.** Forced colours: the current row's cue is a dashed `CanvasText`
|
||||
border instead of an outline, so focus and bookmark outlines are no longer
|
||||
overridden. The dropped tint and bar are written down under Goal.
|
||||
- **F7.** `media/hierarchy.js` `relight` skips a non-array entry.
|
||||
- **F8.** Status corrected (18 + 4 checks).
|
||||
- **F5, F6.** Stated under Assumptions, with QA's numbers and examples. The
|
||||
UNC note is under Handshakes, for the lead, with nothing acted on.
|
||||
- `hierarchyCurrent.js` exports `BAR_COLOR`. The manifest test now expects the
|
||||
five tints plus the bar, and checks the bar is opaque in all four kinds and
|
||||
that the CSS uses its variable.
|
||||
- Tests: `node --test editors/vscode/*_test.js` gives 12 files, 12 pass, 0 fail
|
||||
(11 before this round; `hierarchyPalette_test.js` is new). `node --check`
|
||||
is clean on `hierarchyCurrent.js`, `hierarchyCurrent_test.js`,
|
||||
`hierarchyPalette_test.js` and `media/hierarchy.js`. `package.json` parses.
|
||||
- **Still unverified:**
|
||||
- Any of it in a running VS Code.
|
||||
- Whether `color-mix()` with a `var()` percentage and the dashed
|
||||
`repeating-linear-gradient` bar render as intended. The webview's Chromium
|
||||
supports both, and `color-mix` was already used for the bookmark.
|
||||
- Forced-colors behaviour (it follows the spec, but nobody has run it).
|
||||
- The theme table is the built-in themes' published colours, not a capture
|
||||
from a live window.
|
||||
|
||||
### Changelog paragraph (for the lead)
|
||||
|
||||
**The Hierarchy pane shows where you are.** The rows leading to the file you
|
||||
are editing are lit: every instance of the module it declares in a bright
|
||||
orange with a solid bar at its edge, each row above one shade dimmer with a
|
||||
narrower bar, down to a faint floor; labels stay readable at every level. It works on a
|
||||
closed tree and on DUT sections — a header is tinted when its section holds
|
||||
the file or its parents — and switching files repaints only the rows that
|
||||
changed, with no reload of the hierarchy. The shades and the bar are theme
|
||||
colours (`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
|
||||
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) you can override; set
|
||||
`lucisv.hierarchy.highlightCurrent` to `false` to turn it off.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS.** The distance logic, the wiring, the renderer and
|
||||
packaging all check out. One medium finding: text contrast on the current row
|
||||
in dark themes. The rest are low or informational.
|
||||
|
||||
**Commands and results** (worktree `lucisv-wt/71.6`, Node v26.13.0):
|
||||
|
||||
- `node --test editors/vscode/*_test.js`: 11 files, 11 pass, 0 fail (before and
|
||||
after the QA additions).
|
||||
- `node --check` on `hierarchyCurrent.js`, `hierarchyCurrent_test.js`,
|
||||
`hierarchyView.js`, `hierarchyView_test.js`, `hierarchySections.js` and
|
||||
`media/hierarchy.js`: all clean.
|
||||
- `package.json` parses, and `version` is still `0.65.1`.
|
||||
`git diff --name-only 88546c8` plus the untracked files touch only
|
||||
`editors/vscode/**`, `tools/RELEASING.md` and this folder. The `media/` edits
|
||||
only add the `lit` handler, `setLit` and `treeButtons`, and the CSS block for
|
||||
the five levels plus the high-contrast and forced-colors rules. All of it
|
||||
belongs to this feature.
|
||||
- `npx --no-install @vscode/vsce ls --no-dependencies` ran offline (vsce 4.1.1
|
||||
from the npx cache). It lists `hierarchyCurrent.js`, `media/hierarchy.css`
|
||||
and `media/hierarchy.js`, and no `*_test.js` or `smoke` file. `package.json`
|
||||
has no `files` field, so `.vscodeignore` decides what ships.
|
||||
- I checked the VS Code source on `main` myself. In `themeing.ts` the variable
|
||||
name is `'vscode-' + entry.id.replace('.', '-')`, so only the first dot
|
||||
becomes a dash. `colorExtensionPoint.ts` uses the pattern `^\w+[.\w+]*$`, and
|
||||
`highContrast ?? dark` / `highContrastLight ?? light` as fallbacks. The
|
||||
README's account is accurate. All five ids have exactly one dot, the CSS uses
|
||||
`--vscode-lucisv-hierarchy{Current,Parent1,Parent2,Parent3,Ancestor}`, and
|
||||
every id has all four defaults.
|
||||
|
||||
**Attacks on `hierarchyCurrent.js`** (scratch scripts outside the repo; the
|
||||
plain missing assertions were added to `hierarchyCurrent_test.js`):
|
||||
|
||||
- Passed:
|
||||
- an empty snapshot, including in DUT sections
|
||||
- a file that declares no module
|
||||
- one file declaring several modules, two of them on one chain (both are
|
||||
level 0)
|
||||
- an unequal diamond (`top→a→b→c→leaf` plus `top→leaf`): top is lit at 1
|
||||
and the long chain at 3, 2, 1
|
||||
- 50 instances of one module: all lit at 0
|
||||
- a self-instantiating module
|
||||
- a pure cycle with no root
|
||||
- DUT sections over a cycle
|
||||
- a 300-deep chain: 296 rows at the floor, no level outside 0..4
|
||||
- `litLevel(NaN)` and `litLevel(Infinity)` both return `undefined`
|
||||
- Timing, 6 000 modules (a fan-out-3 DAG with cross links):
|
||||
- `matchingFiles` + `currentPath`: 4.9 ms including the first `parentIndex`
|
||||
build, 1.8 ms on a fresh model
|
||||
- `rowLevels` over 176 open rows: 1.6 ms
|
||||
- Property test over 1 500 random DAGs: every lit forward row that is open and
|
||||
not current has a child exactly one level brighter, with 0 violations. See F5
|
||||
for the cyclic case.
|
||||
|
||||
**`media/hierarchy.js`, executed** with a hand-rolled fake `document` and
|
||||
`acquireVsCodeApi` loaded through `vm` (scratch `dom.js`):
|
||||
|
||||
- A render paints `data-lit`.
|
||||
- A `lit` message changes only the rows it names, and the button objects stay
|
||||
the same, so nothing is rebuilt.
|
||||
- Unknown ids and invalid levels (`-1`, `1.5`, missing) are ignored or cleared.
|
||||
- `changes` set to a non-array, or missing, is ignored.
|
||||
- A later full render shows whatever the host sends.
|
||||
- While search is active, the hidden tree still relights and a search row
|
||||
named in a `lit` message is not touched.
|
||||
- Setting off (all-null changes, then a render without `lit`) leaves no lit
|
||||
row.
|
||||
- A `lit` message after an error status does not throw.
|
||||
|
||||
**Findings**
|
||||
|
||||
- **F1 (medium): body text on the level-0 row is below WCAG AA in dark and
|
||||
Light+ themes.** Source: `editors/vscode/package.json`, the
|
||||
`lucisv.hierarchyCurrent` defaults (`dark` `#FFB34773`, `light`
|
||||
`#FF8C0066`). Blended onto typical sidebar backgrounds, the foreground
|
||||
contrast is:
|
||||
|
||||
| theme | foreground | level-0 background | contrast | unlit |
|
||||
|---|---|---|---|---|
|
||||
| Dark Modern | `#CCCCCC` | `#805E2D` | 3.68:1 | 11.06 |
|
||||
| Dark+ | `#CCCCCC` | `#876535` | 3.32:1 | 9.54 |
|
||||
| Light+ | `#616161` | `#F8CA92` | 4.09:1 | 5.58 |
|
||||
| HC dark | `#FFFFFF` | — | 4.67:1 | — |
|
||||
|
||||
The row the user most needs to read is the hardest one to read.
|
||||
Reproduction: `node contrast.js` (scratch). This is a palette decision for
|
||||
the lead and owner. I did not change it.
|
||||
- **F2 (low): level 3 and the floor are close to indistinguishable.** In light
|
||||
themes they differ by ΔE76 1.8 (`#FF8C001F` against `#FF8C001A`), which is
|
||||
under the ≈2.3 just-noticeable difference. Dark+ is at 2.7 and Dark Modern at
|
||||
3.0. The steps between the other levels are 4.3 to 15.7. The floor against an
|
||||
unlit row is ΔE 9.0 to 16.0, which is fine. In practice the user sees about
|
||||
four shades, not five.
|
||||
- **F3 (low): in high-contrast themes a bookmarked current row loses its yellow
|
||||
border.** Source: `media/hierarchy.css:77-80`. The selector
|
||||
`body.vscode-high-contrast .row[data-lit="0"]` (specificity 0,3,1) sets
|
||||
`border-color` and beats the `.row.bookmarked` border (0,2,0). That
|
||||
contradicts "a bookmark wins". The yellow background is kept. In HC only
|
||||
level 0 gets a cue other than colour (the border, plus the bold label every
|
||||
theme gets). Levels 1 to 4 are colour only.
|
||||
- **F4 (low): in `forced-colors`, the focus ring and the bookmark outline are
|
||||
lost on the current row.** Source: `media/hierarchy.css:115`. The rule
|
||||
`.row[data-lit="0"] { outline: 1px dashed Highlight }` comes later and has the
|
||||
same specificity, so it replaces the `.row:focus` outline (line 48) and the
|
||||
bookmark's 2px outline (line 114). That leaves a focused current row without
|
||||
its focus ring. Under forced colors the gradient tint is also dropped (CSS
|
||||
Color Adjust forces `background-image` to `none`), so levels 1 to 4 are
|
||||
invisible there. That is expected, but it is not written down.
|
||||
- **F5 (low, documented): the recursive-design limitation is real and common
|
||||
in dense cycles.** Over 1 500 random cyclic graphs of 3 to 6 modules, 1 165
|
||||
lit open rows had no child one level brighter. Example: with
|
||||
`m0:[m1,m2] m1:[m3,m5] m2:[m1] m3:[m2,m4] m4:[m1,m3] m5:[m0,m4]` and `m3`
|
||||
current, the row `m0 › m1 › m3 › u (m2)` is lit at 2 and its only child,
|
||||
`m1`, is cut as `recursive`. A self-instantiating module does not show this.
|
||||
Assumptions describes it accurately.
|
||||
- **F6 (low, not executed): files are compared exactly after `vscode.Uri`
|
||||
normalization.** From `uri.ts` on `main`, `parse` followed by `toString`
|
||||
lowercases the drive letter and encodes `:` as `%3A`. So
|
||||
`file:///C:/x/top.sv` from the server matches VS Code's
|
||||
`file:///c%3A/x/top.sv`. Two cases do not match:
|
||||
- Directory case is not folded. If a filelist spells the path differently
|
||||
from how the editor opens it (`C:\Proj` against `c:\proj`, on
|
||||
case-insensitive win32 or darwin), nothing lights.
|
||||
- UNC paths: `crates/lucisv_server/src/uri.rs:20-28` turns `\\srv\share\a.sv`
|
||||
into `file:////srv/share/a.sv`, while VS Code uses `file://srv/share/a.sv`.
|
||||
This is a pre-existing server encoding and outside this scope, but here it
|
||||
means nothing lights.
|
||||
|
||||
`vscode-uri` is not available offline, so this comes from reading the source.
|
||||
- **F7 (info): `media/hierarchy.js:157` throws a TypeError on an entry that is
|
||||
not an array** (`changes: [null]`). Only a malformed host message triggers
|
||||
it, and the host never sends one.
|
||||
- **F8 (doc):** Status said "15 checks". It is 18 now, with the QA additions.
|
||||
|
||||
**QA changes:** I added three tests to `hierarchyCurrent_test.js`:
|
||||
`anEmptySnapshotLightsNothing`, `theShorterOfTwoUnequalChainsWins` and
|
||||
`aSelfInstantiatingModuleTerminates`.
|
||||
|
||||
**Still to check in a running VS Code (by a human):**
|
||||
|
||||
- The dev's nine checks in the Work log.
|
||||
- The `onDidChangeActiveTextEditor(undefined)` ordering against
|
||||
`visibleTextEditors` when the last editor closes, and when focus moves to a
|
||||
webview editor such as a Markdown preview.
|
||||
- That contributed colours with alpha really reach the webview (`toString` of
|
||||
a translucent `Color`).
|
||||
- F1 and F2 judged by eye in real themes.
|
||||
- Windows: a drive-letter workspace, and a filelist with path case that
|
||||
differs from the editor's.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.2.
|
||||
|
||||
- The brief assumed a TreeView; the pane is a webview, and the dev was right
|
||||
to paint rows with CSS and to take `media/hierarchy.{js,css}` into scope —
|
||||
no other lane owns them. Ruled in.
|
||||
- QA's F1–F4, F7, F8 are fixed in the fix round and I re-ran the suite on the
|
||||
result: 12 test files, 12 pass. The palette test is the part I value most:
|
||||
the contrast claim is computed from the shipped defaults, not asserted.
|
||||
- Read the stylesheet: `--bar-alpha`/`--lit` are set by the per-level rules on
|
||||
the same element the `[data-lit]` rule reads them on, so they resolve; a
|
||||
bookmarked row keeps its fill and border and only adds the bar.
|
||||
- Not verified by anyone: the look in a running VS Code (tint, bar, dashes,
|
||||
forced-colours). I tried to render the stylesheet in a browser from this
|
||||
session and could not. The owner's eye is still owed; the changelog says so.
|
||||
- Left open, recorded under Assumptions: case-differing folder names and UNC
|
||||
paths do not light (the UNC spelling is the server's, `uri.rs:20-28` — a
|
||||
candidate for a later round), and the recursive-design gap.
|
||||
@@ -0,0 +1,408 @@
|
||||
# ifdef-folding
|
||||
|
||||
## Goal
|
||||
|
||||
Owner: "ifdef and else block should support collapsing. It should also be part
|
||||
of the floating bars." Every branch of a `` `ifdef `` / `` `ifndef `` …
|
||||
`` `endif `` region becomes a `textDocument/foldingRange`, so each branch
|
||||
collapses on its own and — because the extension sets
|
||||
`editor.stickyScroll.defaultModel: foldingProviderModel` for both languages
|
||||
(TODO §67) — the branch's directive line is pinned by VS Code's sticky scroll
|
||||
("floating bars") while the reader is inside it. Server-side only: no new
|
||||
setting, no extension code.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Directives are what the lexer says they are.** `vlog_parser::lexer`
|
||||
makes each of the five directives one `TokenKind::Directive` token running
|
||||
to the end of its line (`is_line_directive`, `lexer.rs:899`; capture at
|
||||
`lexer.rs:187-260`). Consequences, all tested:
|
||||
- in a `//` or `/* */` comment → trivia, never a fold;
|
||||
- in a string → part of the string literal;
|
||||
- inside a `` `define `` body (backslash continuations) → text of the
|
||||
`` `define `` token, never a fold;
|
||||
- `` `ifdef A … `else … `endif `` on **one line** is a single token (the rest
|
||||
of the line is its text), so there is nothing to fold — correct;
|
||||
- leading whitespace, trailing `//`/`/* */` comments (the lexer stops before
|
||||
them) and CRLF change nothing.
|
||||
- A directive written after code on its line (`module m; `ifdef A`,
|
||||
`initial begin `ifdef X`) is still a directive, and its branch fold starts
|
||||
on that code line — but that line already starts the `module`/`begin`
|
||||
fold, which is sent first, so **in VS Code such a branch gets no fold of
|
||||
its own** (the existing fold and its sticky-scroll header win; see the
|
||||
ordering rule below). Zero such lines in OpenTitan (4 061 files) or the
|
||||
corpus (860 files): `not_first_on_line: 0`, `shared_start: 0`.
|
||||
- **No existing fold is lost or changed by this feature** (lead's ruling,
|
||||
2026-11-19). Two rules, both in `folding.rs`:
|
||||
- a branch fold with exactly the same two lines as an existing scope or
|
||||
comment fold is not added — the existing fold keeps its kind, so a
|
||||
`/* */` opened on the directive line and ending on the line before the
|
||||
next directive stays a `comment` fold;
|
||||
- the answer's order is defined in one place, `in_answer_order`: by start
|
||||
line; on a shared start line every scope/comment fold (in its own
|
||||
`(start, end)` order, byte-identical to before) comes before any branch
|
||||
fold. Because VS Code keeps only the first range it receives for a start
|
||||
line, the branch fold is the one that yields.
|
||||
- **Fold shape — a branch runs from its directive's line to the line before
|
||||
the next directive of the same region.** `` `ifdef `` line L0, `` `else ``
|
||||
L5, `` `endif `` L9 → `(0, 4)` and `(5, 8)`. Collapsing the first branch
|
||||
leaves `` `else `` visible and separately collapsible; collapsing the last
|
||||
leaves `` `endif `` visible. Chosen to match the existing `begin`/`end` rule
|
||||
in `folding.rs` (the closer stays on screen). For C, VS Code itself ships
|
||||
no `#ifdef` folding — `extensions/cpp/language-configuration.json` folding
|
||||
markers are `#pragma region`/`#pragma endregion` only (checked in the VS
|
||||
Code repo, main branch, 2026-11-19); `#if` folding comes from the C/C++
|
||||
extension's provider, whose exact shape I did **not** verify. The shape
|
||||
here is the one where every directive line stays visible, which is the
|
||||
only one that lets each branch collapse independently.
|
||||
- **Kind: `region`.** Same as every scope-pair fold. LSP 3.17 defines only
|
||||
`comment`, `imports`, `region`; VS Code's *Fold All Regions*
|
||||
(`editor.foldAllMarkerRegions`) folds kind `region`
|
||||
(`folding.ts` `FoldAllRegionsAction` → `setCollapseStateForType(Region)`),
|
||||
which already includes every `begin` fold, so branches joining it is
|
||||
consistent. `imports` would be wrong (and would auto-collapse under
|
||||
`editor.foldingImportsByDefault`).
|
||||
- **Degraded input** (all tested, none panic):
|
||||
- a region still open at end of file folds the branches it *finished*
|
||||
(`` `ifdef `` … `` `else `` … EOF folds the `ifdef` branch) and nothing for
|
||||
the open one — the same "never fold to EOF" policy as an unclosed `begin`;
|
||||
- a stray `` `else ``/`` `elsif ``/`` `endif `` with no region open is
|
||||
ignored and does not disturb later regions;
|
||||
- a branch with no line between its directive and the next yields no range
|
||||
(`push` drops `end <= start`).
|
||||
- **A file that does not lex** has no tokens and folds nothing, as before.
|
||||
|
||||
### VS Code facts this relies on (verified in source, `microsoft/vscode` main, 2026-11-19)
|
||||
|
||||
- `syntaxRangeProvider.ts` `collectSyntaxRanges` keeps a provider range only
|
||||
if `start > 0 && end > start && end <= lineCount` (1-based there) — every
|
||||
range we send satisfies it (pinned by the OpenTitan sweep).
|
||||
- `sanitizeRanges` sorts by start line (then provider rank, a stable sort)
|
||||
and **keeps crossing ranges**: an entry that starts inside the current top
|
||||
and ends after it is added at the top's nesting level without becoming the
|
||||
top. **Ranges sharing a start line: the first in our order survives**
|
||||
(`entry.start > top.start` guard) — with one nuance QA found: the guard
|
||||
compares against `top`, and a crossing entry never becomes `top`, so if
|
||||
the first range on a line was itself added as a crossing entry, a second
|
||||
same-start range that also crosses is kept as well (harmless). A branch
|
||||
fold shares a start line with an existing fold in two ways: a directive
|
||||
after code on its line (`module m; `ifdef A`), or a multi-line `/* */`
|
||||
opened after the directive (`` `ifdef A /* … ``). Existing folds are sent
|
||||
first, so in both cases the existing fold survives and the branch yields.
|
||||
- Parent/child (what sticky scroll nests by) is recomputed by **containment**
|
||||
in `foldingRanges.ts` `ensureParentIndices`, and the sticky model is built
|
||||
from those `FoldingRegions` (`stickyScrollModelProvider.ts`
|
||||
`_fromFoldingRegions`, range end + 1). So a crossing branch is a child of
|
||||
the nearest fold that contains it, and sticky scroll still shows a sane
|
||||
stack.
|
||||
- When the count exceeds `editor.foldingMaximumRegions` (default 5000) the
|
||||
collector keeps shallow levels first. Not new; branches add ~0.26 ranges
|
||||
per OpenTitan file on average.
|
||||
- LSP 3.17 (`foldingRange.md`): validity is per range (lines within the
|
||||
document); the spec says nothing against overlap, and "clients are free to
|
||||
ignore invalid ranges".
|
||||
|
||||
### Crossing structure
|
||||
|
||||
Real RTL opens a `begin` in each arm and closes it once below the `endif`
|
||||
(test `a_region_crossing_a_begin_keeps_both_sets_of_folds`). The result is
|
||||
`[(0,9) module, (2,3) ifdef, (3,8) begin, (4,5) else, (5,7) begin]`: the scope
|
||||
folds are whatever `pairs::analyze` already made of the unbalanced
|
||||
`begin`s (unchanged by this feature), and the branch folds are added beside
|
||||
them, crossing. Per the facts above VS Code keeps all five; sticky scroll at
|
||||
line 7 shows module → `if (a) begin` → `if (b) begin`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `vlog_parser::token::{Token, TokenKind::Directive}` and the
|
||||
lexer's directive capture, read-only. No parser change: the representation
|
||||
is sufficient. The directive-word rule (backtick, then the identifier
|
||||
prefix) is private in `vlog_parser/src/parser/directive.rs:15-28`; it is four
|
||||
lines and is repeated in `folding/directives.rs` rather than widened into
|
||||
the parser's public surface. (A third copy, by first whitespace word, lives
|
||||
in `on_type/auto_end.rs:258`.) If a public `Token::directive_word` is ever
|
||||
added, all three should use it — a request, not a blocker.
|
||||
- **Promises** `folding::folding_ranges` (the only caller is
|
||||
`server/dispatch.rs`, unchanged): sorted by start line (tie-break in
|
||||
`in_answer_order`: existing folds, in their old `(start, end)` order,
|
||||
before branch folds), de-duplicated by `(start, end)` with the existing
|
||||
fold winning, every range `start < end`, branch folds kind `region`. With
|
||||
the branch folds removed the answer is exactly the old answer — asserted
|
||||
per file by the sweep (`check_existing_unchanged`).
|
||||
- **Large-file path: unchanged.** A buffer over the threshold is
|
||||
`Document::large` (`state/document.rs:103`), whose `tokens` are empty, so
|
||||
`folding_ranges` answers `[]` for it exactly as before — pinned already by
|
||||
`server/tests/large_file.rs` (`FoldingRangeRequest` → empty). Supporting
|
||||
branch folds there would need a line scan of the raw text in or beside
|
||||
`large.rs`, which this lane does not own; not requested.
|
||||
- **Scope note for the lead**: the end-to-end test is a new file,
|
||||
`crates/lucisv_server/tests/ifdef_folding.rs` (a new integration test, not
|
||||
an edit to `e2e.rs`), repeating `e2e.rs`'s twenty lines of framing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Find how directives are represented (one `Directive` token per line).
|
||||
- [x] `folding/directives.rs`: one linear pass → branch spans.
|
||||
- [x] Wire into `folding_ranges` (kind `region`).
|
||||
- [x] Unit tests for every edge case in `folding/ifdef_tests.rs` (15).
|
||||
- [x] Wire test `tests/ifdef_folding.rs`.
|
||||
- [x] OpenTitan sweep `folding/opentitan_sweep.rs` (`#[ignore]`, skips when absent).
|
||||
- [x] Timing before/after.
|
||||
- [x] VS Code README feature rows (Folding, Sticky scroll).
|
||||
- [x] Fix round: existing folds win identical lines and shared start lines
|
||||
(QA findings 1–2); `in_answer_order` defines the order; sweep asserts the
|
||||
non-branch answer is unchanged.
|
||||
- [ ] Human check in a running VS Code (cannot be done by the agent):
|
||||
collapse an `ifdef` branch (the `else` stays visible), collapse the `else`
|
||||
branch (the `endif` stays visible), nested regions, sticky scroll pinning
|
||||
the `` `ifdef ``/`` `else `` line while scrolling inside a long branch, and a
|
||||
crossing `begin` (e.g. one `if … begin` per arm, one `end`).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev
|
||||
|
||||
- Directives: the lexer's `Directive` tokens are exactly the right
|
||||
representation (comments/strings/define bodies already excluded), so the
|
||||
new pass reads only `token.kind` and the first word. Built
|
||||
`crates/lucisv_server/src/folding/directives.rs` (`branch_spans`, ~90
|
||||
lines): a stack of open-branch start lines; `Open` pushes, `Next` emits the
|
||||
current branch and restarts it, `Close` pops and emits. Line numbers come
|
||||
from the caller (`folding::line`, the same `LineIndex` conversion as the
|
||||
other folds). `folding.rs` gained one loop and the module declarations.
|
||||
- Tests: `folding/ifdef_tests.rs` — shape, `elsif` chain, three-deep nesting,
|
||||
empty branch, one-line region, unterminated, stray directives, port list,
|
||||
`case` + `generate`, `define` body, comment/string, whitespace/trailing
|
||||
comments/CRLF, crossing `begin` (exact list pinned), kind, back-to-back.
|
||||
All passed on the first run. `tests/ifdef_folding.rs` checks the same over
|
||||
the wire (elsif/else/nested ifndef).
|
||||
- **OpenTitan sweep** (`LUCISV_OPENTITAN_HW` or
|
||||
`~/.cache/lucisv-opentitan-full/hw`, 4 061 `.sv`/`.svh`/`.v` files, release
|
||||
build, through `tools/guard.sh`): no panic; every range `start < end` and
|
||||
`end < line count`; every branch fold starts on a line holding a
|
||||
conditional directive token, and that token is the first on its line in
|
||||
every case (`not_first_on_line: 0`); every non-empty branch is present in
|
||||
the answer. Counts: 1 839 directive tokens (772 `ifdef`/`ifndef`, 295
|
||||
`elsif`/`else`, 772 `endif`), all matched, 0 unclosed → 1 067 branch spans
|
||||
= 295 + 772, of which 1 061 are ranges (6 empty branches). A naive text
|
||||
count of lines starting with a directive finds 1 874: the 35 extra are in
|
||||
block comments (`prim_macros.svh:35-46`) and `` `define `` bodies
|
||||
(`prim_assert*.sv*`, `prim_flop_macros.sv`, `dv_defines.svh`, ibex
|
||||
`check/top.sv:181`) — correctly not folded. One file does not lex
|
||||
(`riscv_core_setting.tpl.sv`, a template) and folds nothing, as before.
|
||||
- **Timing** (`folding_ranges` per file, release, same machine, warm):
|
||||
before — whole tree 29.9 ms, slowest `top_darjeeling/.../pinmux_reg_top.sv`
|
||||
(1.3 MB) 0.84 ms; after — whole tree 34.4–35.0 ms, slowest the same file
|
||||
1.09 ms, of which the branch pass is ~0.25 ms (it touches every token
|
||||
once: ~1.5 ns/token). Two after-runs agreed within 2%.
|
||||
- Not touched: `vlog_parser`, `vlog_formatter`, `large.rs`, dispatch,
|
||||
`package.json`.
|
||||
|
||||
### 2026-11-19 — dev, fix round (QA findings 1 and 2, lead's ruling)
|
||||
|
||||
- `folding.rs` split into `scope_and_comment_folds` (the old body, verbatim:
|
||||
pairs + comments, sort `(start, end)`, dedup), `branch_folds` (drops a
|
||||
branch whose `(start, end)` an existing fold already has, so that fold
|
||||
keeps its kind) and `in_answer_order` (the one place the order is defined:
|
||||
a merge by start line, existing folds first on a tie).
|
||||
- **Deviation from the brief's wording, flagged for the lead:** the ruling
|
||||
said "send the LONGER one first" and also "an existing fold is never lost
|
||||
or changed". These disagree in QA's third repro (`` `ifdef A /* c1\n c2 */ ``):
|
||||
the comment `(0,1)` is the existing fold and the *shorter* one. Longer-first
|
||||
would put the branch `(0,2)` first and VS Code would drop the comment fold.
|
||||
Longer-first applied to *all* folds would also reorder existing
|
||||
same-start pairs (e.g. a `begin /* … */` line), so non-directive folds
|
||||
would no longer be byte-identical to base. I implemented "existing first"
|
||||
instead. It gives the same answer as longer-first for both QA repros where
|
||||
the existing fold is longer (`module m; `ifdef A`, `initial begin `ifdef X`),
|
||||
keeps the comment in the third, and leaves every non-branch fold in its old
|
||||
order. If longer-first really is wanted for the comment case, it is a
|
||||
one-line change in `in_answer_order`.
|
||||
- Tests added to `folding/ifdef_tests.rs`: the three QA repros and the
|
||||
comment-kind case (19 tests now); the `folds` helper asserts every answer
|
||||
is sorted by start line.
|
||||
- Sweep: new per-file assertion `check_existing_unchanged` (answer minus
|
||||
branch folds == the scope/comment folds exactly, same order and kinds;
|
||||
answer length == both added together) and two counts. OpenTitan: as
|
||||
before (1 839 tokens, 1 067 spans, 1 061 ranges), `same_lines_as_existing:
|
||||
0`, `shared_start: 0`, tree 33.8 ms, slowest file 1.09 ms. Corpus
|
||||
(`~/.cache/lucisv-corpus`, 860 files, via `LUCISV_OPENTITAN_HW`): 923
|
||||
tokens, 511 spans, 511 ranges, `shared_start: 0`, `same_lines_as_existing:
|
||||
0`, `not_first_on_line: 0`, passed.
|
||||
|
||||
## Changelog paragraph (for the lead)
|
||||
|
||||
**`` `ifdef `` branches fold, and stick.** Every branch of a
|
||||
`` `ifdef ``/`` `ifndef `` region now folds on its own, from its directive to
|
||||
the line before the next `` `elsif ``/`` `else ``/`` `endif `` — which stays
|
||||
visible, so the `else` branch can be collapsed separately — and, because
|
||||
sticky scroll follows the folds, the directive of the branch you are in is
|
||||
pinned at the top of the editor with the module and blocks around it. Nested
|
||||
regions fold at every depth; directives inside comments, strings and
|
||||
`` `define `` bodies are left alone; an unterminated region never folds to the
|
||||
end of the file. Buffers over the large-file threshold still fold nothing.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS** (two low-severity findings, two info notes;
|
||||
nothing fixed by QA, no source file touched). The machine was heavily loaded
|
||||
throughout (another QA lane's cargo jobs, load average 19–21), so the
|
||||
timings below are upper bounds.
|
||||
|
||||
**Gates** (worktree, uncommitted diff on 948f8a0):
|
||||
- `cargo fmt --all -- --check` clean; `cargo clippy --all-targets -- -D
|
||||
warnings` clean (the one cargo-level `workspace.package.authors` manifest
|
||||
warning is pre-existing and not a lint).
|
||||
- `tools/guard.sh -- cargo test -p lucisv_server`: 1 973 passed, 0 failed
|
||||
(lib 1 863 + 37 ignored; e2e 106; grammar 3; `ifdef_folding` 1;
|
||||
opentitan_references 0 + 2 ignored). `tools/guard.sh -- cargo test -p
|
||||
vlog_formatter`: all green. `node --test editors/vscode/*_test.js`: 37/37.
|
||||
- Ignored sweep, `tools/guard.sh -t 1500 -- cargo test --release -p
|
||||
lucisv_server opentitan_sweep -- --ignored --nocapture`: ok; 4 061 files,
|
||||
1 unlexed, 1 839 tokens (772/295/772), 1 067 spans, 1 061 ranges, 0
|
||||
unclosed, `not_first_on_line: 0`; whole-tree `folding_ranges` 33.4 ms
|
||||
(branch pass 4.7 ms), slowest `top_darjeeling/.../pinmux_reg_top.sv`
|
||||
1.07 ms (branches 0.24 ms) — consistent with the work log.
|
||||
- Scope: `git status` shows only `folding.rs` (modified, purely additive:
|
||||
module decls, doc, one loop), `folding/{directives,ifdef_tests,
|
||||
opentitan_sweep}.rs`, `tests/ifdef_folding.rs`, `editors/vscode/README.md`,
|
||||
this README. Sizes: `folding.rs` 296 lines incl. tests (~85 production),
|
||||
`directives.rs` 85 — well under CLAUDE.md thresholds.
|
||||
|
||||
**Attack inputs over LSP** (release and debug `lucisv-server`, one
|
||||
`didOpen` + `textDocument/foldingRange` per buffer; script kept in the QA
|
||||
scratchpad, `qa714/cases.py`). Hand-computed expectation matched every one:
|
||||
10-deep nesting `(i, 19-i)` for i=0..9; `elsif` chains; empty first branch
|
||||
(`ifdef`/`else` adjacent → only the `else` fold); `else` directly before
|
||||
`endif`; two `else` in one region and `elsif` after `else` (each treated as
|
||||
"next branch", three folds, no panic); `endif // c`; `endif /* multi-line */`
|
||||
(comment folds separately, branch unaffected); spaces/tabs before
|
||||
directives; CRLF; no trailing newline ending in `` `endif ``; directives in
|
||||
`/* */`, `//`, a string inside a live region (`$display("`endif `else")`),
|
||||
a `` `define `` body with `\` continuations (LF and CRLF), a `` `define `` with
|
||||
a trailing `\` at EOF (both after a region and alone); mid-line
|
||||
`assign a = b; `ifdef X` and `end `ifdef A` (lexed as a directive, fold
|
||||
starts on that code line — sensible); region crossing `begin…end`,
|
||||
crossing a module boundary, wrapping a whole module, inside a port list,
|
||||
inside a `case`; `` `ifdef_helper ``/`` `elseif ``/`` `endif_x ``/`` `IFDEF ``/
|
||||
`` `ENDIF `` (no folds); `` `include ``/`` `timescale `` between branches;
|
||||
one-line region; stray `else`/`endif`; unterminated region.
|
||||
|
||||
**Fuzz** (`qa714/fuzz.py`, 2 × 5 000 random buffers through one server
|
||||
session each, through `tools/guard.sh`): half well-nested generated regions
|
||||
up to 7 deep, half random directive/code/comment/`define`/string/look-alike
|
||||
line soup, 30 % CRLF, 20 % no trailing newline. Checked against an
|
||||
independent line-model (my own scan: directive first on a line, outside block
|
||||
comments and `define` bodies): every answer present, sorted, `start < end <
|
||||
line count`, region folds == model's non-empty branch spans exactly, every
|
||||
fold on a directive line, no crossing branch folds in well-nested input.
|
||||
**0 failures** in 10 000. Sanity: the same checker against the base binary
|
||||
fails 1 673/2 000, so it is not vacuous.
|
||||
|
||||
**Scale** (`qa714/big.py`): 50 000-branch `elsif` chain (1.4 MB), 25 000
|
||||
back-to-back `ifdef/else` regions, and 50 000-deep nesting (1.7 MB): 0.20 s,
|
||||
0.22 s, 0.24 s round-trip vs base 0.17/0.18/0.20 s; 12.5k → 25k → 50k
|
||||
doubles cleanly (linear, no quadratic term, no stack overflow at 50 000
|
||||
deep). VS Code's 5 000 cap (`RangesCollector.toIndentRanges`) keeps shallow
|
||||
levels first and, within the cut level, the first in order — for a flat chain
|
||||
the module plus the first 4 999 branches; nothing harmful. Note only that a
|
||||
branch fold adds one nesting level to what it contains, so in a file already
|
||||
over 5 000 folds a few deep `begin` folds may now fall past the cut instead of
|
||||
a branch. Not new behaviour, no real file near it.
|
||||
|
||||
**Regression of existing folds** — done by **building the base**, not by
|
||||
reading the diff: `git archive 948f8a0` into the QA scratchpad, own
|
||||
`CARGO_TARGET_DIR`, release build; both binaries over the full OpenTitan
|
||||
`hw` tree (4 061 files) and `~/.cache/lucisv-corpus` (860 files) via LSP.
|
||||
Result: every base fold (start, end, kind) is still present in the new
|
||||
answer (0 lost in 4 921 files), and new − base equals the independent model's
|
||||
non-empty branch spans exactly in every file (0 mismatches). So on real code
|
||||
the non-directive fold set is identical to 948f8a0. Independent recount
|
||||
(own scan, not the lexer): OpenTitan 1 839 directives (772 open / 295 next /
|
||||
772 close), 1 067 spans, 1 061 non-empty, 0 unclosed — matches the dev
|
||||
exactly; corpus 923 directives, 511 spans, 511 non-empty.
|
||||
|
||||
**VS Code source** (`microsoft/vscode` main, fetched 2026-11-19:
|
||||
`folding/browser/syntaxRangeProvider.ts`, `foldingRanges.ts`, `folding.ts`,
|
||||
`stickyScroll/browser/stickyScrollModelProvider.ts`,
|
||||
`stickyScrollProvider.ts`, `stickyScrollController.ts`). Confirmed: the
|
||||
`start > 0 && end > start && end <= nLines` filter; `sanitizeRanges` sorts by
|
||||
start then provider rank (stable, so our order), drops any entry whose start
|
||||
equals the current `top`'s start, and adds crossing entries at `top`'s level
|
||||
without making them `top`; `ensureParentIndices` assigns parents by
|
||||
containment (popping a non-containing parent); sticky scroll builds its tree
|
||||
from those parents (`_fromFoldingRegions`, end + 1) and walks it;
|
||||
`FoldAllRegionsAction` → `setCollapseStateForType(Region)`. Nuance to the
|
||||
README's "only the first survives": that holds when the first becomes `top`;
|
||||
if the first was itself a crossing entry (not `top`), a second range with the
|
||||
same start that also crosses is kept as well — harmless. With a crossing
|
||||
fold, sticky scroll gets sibling roots at the same depth (e.g. `module a` and
|
||||
an `ifdef` that runs into `module b` are both depth-0 candidates), so both
|
||||
lines are pinned; exact pixel layout needs a running VS Code.
|
||||
|
||||
**Findings**
|
||||
|
||||
1. **Low — a block-comment fold can lose its `comment` kind.**
|
||||
`crates/lucisv_server/src/folding.rs:55-56`: branch spans are pushed
|
||||
before comments and the dedup keeps the first of an equal `(start, end)`,
|
||||
so when a multi-line `/* */` starts on a directive line and ends on the
|
||||
line before the next directive, the base `comment` fold becomes a
|
||||
`region`. Repro: `` "`ifdef A /* c1\n c2\n c3 */\n`else\n b;\n`endif\n" ``
|
||||
— base `[(0,2,comment)]`, new `[(0,2,region),(3,4,region)]`. Effect: *Fold
|
||||
All Block Comments* no longer folds it (*Fold All Regions* now does); the
|
||||
hidden lines are the same. 0 occurrences in OpenTitan + corpus.
|
||||
2. **Low — same-start-line collisions keep the shorter fold, which can drop
|
||||
an existing one in VS Code.** Sorting `(start, end)` ascending puts the
|
||||
shorter range first, and VS Code keeps only that one. Repros (LSP):
|
||||
`"module m; `ifdef A\n a;\n`endif\nendmodule\n"` → `[(0,1) ifdef,
|
||||
(0,2) module]`: VS Code drops the **module** fold that base showed (and
|
||||
sticky scroll no longer pins `module m;` past line 1);
|
||||
`"module m;\ninitial begin `ifdef X\n a;\n b;\n `endif\n c;\nend\nendmodule\n"`
|
||||
→ `(1,3)` ifdef before `(1,5)` begin: the `initial begin` fold is
|
||||
dropped. Conversely `"`ifdef A /* c1\n c2 */\n x;\n`else\n b;\n`endif\n"`
|
||||
→ `(0,1) comment` before `(0,2) region`: the **branch** is the one
|
||||
dropped. The README (Assumptions → VS Code facts) says a shared start line
|
||||
happens "only when a directive follows code on its line"; the comment case
|
||||
shows it is also a multi-line block comment *after* the directive. 0
|
||||
occurrences in 4 921 real files (only directive-after-text lines found are
|
||||
inside `//` comments, `prim_flop_2sync.sv:33,37`). Whether equal-start
|
||||
ranges should be ordered longer-first (keeps base folds, loses the branch)
|
||||
is a design choice for the lead, not a QA fix.
|
||||
3. **Info — lone-CR files fold nothing**, base and new alike (the lexer and
|
||||
line index only break on `\n`). Pre-existing, unchanged.
|
||||
4. **Info — README accuracy**: line references checked and correct
|
||||
(`lexer.rs:187-260`, `:899`; `parser/directive.rs:15-28`;
|
||||
`on_type/auto_end.rs:258`; `state/document.rs:103`). Corrections: see
|
||||
finding 2 (the same-start condition) and the `sanitizeRanges` nuance
|
||||
above. The "not verified" list (C/C++ extension's `#if` shape, the human
|
||||
VS Code check) is honest and remains unverified.
|
||||
|
||||
**Unverifiable without a running VS Code**: the visual result of collapsing
|
||||
each branch, the sticky-scroll stack and its layout for crossing folds
|
||||
(two depth-0 siblings), and which fold the user actually sees for the
|
||||
same-start cases above (derived from source, not observed).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.4.
|
||||
|
||||
- Built on the lexer's directive tokens with no parser change: the right
|
||||
foundation, and it is why the 35 look-alike lines in OpenTitan are skipped
|
||||
without a special case. The three copies of the directive-word rule are a
|
||||
fair follow-up (`Token::directive_word`), not this round's business.
|
||||
- My fix-round instruction said "longer first"; the dev was right to depart
|
||||
from it. The principle I gave — an existing fold is never lost or changed —
|
||||
and "longer first" disagree when a short comment fold shares a start line
|
||||
with a longer branch, and the principle is the one that matters.
|
||||
"Existing first" is what ships, defined in one place (`in_answer_order`).
|
||||
- QA's regression check is the proof I wanted: base built from `git archive`,
|
||||
both binaries over 4 921 real files, non-directive folds byte-identical; a
|
||||
10 000-case fuzz against an independent model whose checker demonstrably
|
||||
fails on the base binary.
|
||||
- Owed to a human: the collapse and sticky-scroll behaviour in a running
|
||||
editor, in particular crossing regions (an `ifdef` that spans two modules
|
||||
pins both headers as siblings, by QA's reading of VS Code's source).
|
||||
- Open, recorded: no folds on the large-file path; lone-CR files fold nothing
|
||||
(as before).
|
||||
@@ -0,0 +1,126 @@
|
||||
# instantiation-highlighting
|
||||
|
||||
## Goal
|
||||
|
||||
Give module and interface instantiations distinct, recognizable syntax colours
|
||||
instead of painting every part of an instantiation with the default variable
|
||||
foreground. Borrowing the roles other languages assign to constructor and
|
||||
component calls (C++, Rust, TypeScript/JSX), each syntactic piece of an
|
||||
instantiation takes its own semantic token class and theme-safe TextMate scope:
|
||||
|
||||
1. **Module / interface name** (`uart_core` in `uart_core #(...) u_uart (...)`,
|
||||
`pkg::uart_core` with `pkg` as `namespace`, and lone `bind` targets) →
|
||||
`class` (`entity.name.type.class`).
|
||||
2. **`#` sign and parameters** (`#` before parameter port or override lists,
|
||||
`.BAUD_DIV` dot + parameter-port name, `parameter`/`localparam` symbols, and
|
||||
unresolved constant identifiers inside `#(...)`) → `parameter`
|
||||
(`keyword.control` / `constant.language` / `variable.parameter`), sharing
|
||||
one colour that stays distinct from bracket-pair-coloured `()`.
|
||||
3. **Instance name** (`u_uart`, gate instances, `bind` target instances, and
|
||||
uses of `SymbolKind::Instance` such as `u_uart.sig`) → `function`
|
||||
(`entity.name.function`).
|
||||
4. **Port name** (`.clk_i` dot + port name, implicit `.clk_i`, and wildcard
|
||||
`.*` in an instance's connection list) → `property`
|
||||
(`entity.name.tag.css` / `entity.other.attribute-name` /
|
||||
`variable.other.property`).
|
||||
5. **Port connection** (`clk` inside `.clk_i(clk)` or positional `(clk)`) →
|
||||
`variable` (`support.variable` / `entity.other.attribute-name` /
|
||||
`variable.other.readwrite`), keeping signal colouring consistent across the
|
||||
file and non-white in themes that leave bare `variable` uncoloured.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The 14-type wire legend is unchanged.** Every role above maps onto the
|
||||
existing `SemanticTokenType` indices (`namespace`, `class`, `parameter`,
|
||||
`variable`, `property`, `function`), so `token_types().len() == 14` and
|
||||
`token_modifiers().len() == 1` stay untouched on the wire.
|
||||
- **AST spans decide instantiation structure; single-file + overlay semantics
|
||||
decide expressions.** A buffer opened before workspace indexing finishes, a
|
||||
standalone file, or an instantiation of an unindexed vendor macro still
|
||||
highlights its module name, `#`, `.PARAM`, instance name, and `.port` from
|
||||
`Document.tree` alone. Identifiers that resolve through `Document.external`
|
||||
also take their cross-file `SymbolKind` instead of degrading to `variable`.
|
||||
- **Parameter `#` only, never delay `#`.** Only the `#` introducing a parameter
|
||||
port list, parameter override list, or parameterized `DataType` receives
|
||||
`Highlight::Parameter`; `#5` and `#(1:2:3)` net, assignment, gate, and
|
||||
procedural delays remain unemitted punctuation.
|
||||
- **Large-file fast path (`Document::large`) stays lexer-only.** Because the
|
||||
fast path builds no AST or symbol table, AST-driven `#`, `.`, and `.*` tokens
|
||||
are emitted only by the full pipeline, alongside identifier refinement.
|
||||
- **Editor defaults remain user-overridable.** Setting
|
||||
`editor.semanticHighlighting.enabled = true` in `configurationDefaults` for
|
||||
`[verilog]` and `[systemverilog]` activates semantic tokens in themes whose
|
||||
own `semanticHighlighting` flag is unset or `false`, while any explicit user
|
||||
or workspace setting still wins.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumed from `vlog_parser`:** `SourceFile`, `Item`/`ItemKind`, `Module`,
|
||||
`Instantiation`, `Instance`, `Connections`, `Connection`, `BindDirective`,
|
||||
`GateInstantiation`, `ClassDecl`, `ClassExtends`, `DataType::params`,
|
||||
`ListElem`, `RawText`, `Token`, `TokenKind`, `TextRange`. No parser changes.
|
||||
- **Consumed from `vlog_semantic`:** `Semantics`, `SymbolKind`,
|
||||
`ExternalResolutions::definition_of`, `Definition`. No semantic changes.
|
||||
- **Promised to LSP clients (`crates/lucisv_server/src/tokens.rs`):** identical
|
||||
14-entry `token_types` legend and 1-entry `token_modifiers` legend; sorted,
|
||||
non-overlapping single-line UTF-16 tokens; exact `full/delta` round-trip.
|
||||
- **Shared with `editors/vscode/package.json`:** `contributes.semanticTokenScopes`
|
||||
keys for `verilog` and `systemverilog` are a subset of `tokens::token_types()`,
|
||||
checked by `editors/vscode/semanticTokens_test.js`.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Add `crates/lucisv_server/src/tokens/instantiation.rs` for AST-guided
|
||||
instantiation and parameter-header highlight overrides.
|
||||
- [x] Update `crates/lucisv_server/src/tokens.rs` to apply overrides, consult
|
||||
`Document.external` via `definition_of`, map `SymbolKind::Instance` to
|
||||
`Highlight::Function`, and add unit tests covering instantiation shapes,
|
||||
delay `#` exclusion, recovered entries, and `large-file-mode` window
|
||||
agreement.
|
||||
- [x] Configure `editor.semanticHighlighting.enabled` and
|
||||
`contributes.semanticTokenScopes` for `verilog` and `systemverilog` in
|
||||
`editors/vscode/package.json`, with headless verification in
|
||||
`editors/vscode/semanticTokens_test.js` (and `.vscodeignore` exclusion).
|
||||
- [x] Update `docs/features/lucisv-server/README.md` and
|
||||
`docs/features/large-file-mode/README.md` for the refined mapping.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-17 — dev
|
||||
|
||||
- Audited `tokens.rs`, `editors/vscode/package.json`, and VS Code theme scope
|
||||
tables across Dark Modern/Dark+, Light Modern/Light+, GitHub Dark, One Dark
|
||||
Pro, Monokai, and Visual Studio Dark. Found two root causes for flat white
|
||||
instantiations: (1) `tokens.rs` consulted only single-file `Semantics`
|
||||
(leaving external module names, `.PARAM` overrides, `.port` names, and
|
||||
`SymbolKind::Instance` all on `Highlight::Variable`, and leaving `#`
|
||||
unemitted); (2) `package.json` neither defaulted
|
||||
`editor.semanticHighlighting.enabled` on nor mapped semantic token types to
|
||||
distinct TextMate scopes for themes where `variable`/`parameter`/`property`
|
||||
collapse to white or one shared colour.
|
||||
- Added `crates/lucisv_server/src/tokens/instantiation.rs` (~280 total lines)
|
||||
and wired `crates/lucisv_server/src/tokens.rs` without changing the 14-type
|
||||
wire legend:
|
||||
- Module/interface/`extends` names → `Highlight::Class` (`pkg::` prefixes →
|
||||
`Highlight::Namespace`);
|
||||
- Parameter-list `#` (headers, instantiations, parameterized `DataType`s,
|
||||
never delays), `.PARAM` overrides (`.` + name), and unresolved constant
|
||||
identifiers inside `#(...)` → `Highlight::Parameter`;
|
||||
- `SymbolKind::Instance`, `Instance.name_span`, gate instances, and `bind`
|
||||
instance lists → `Highlight::Function`;
|
||||
- Named port connections (`.` + name, implicit `.name`, wildcard `.*`),
|
||||
including recovered unfinished entries while typing → `Highlight::Property`;
|
||||
- Port connection expressions stay on `identifier_type` (`Highlight::Variable`
|
||||
for signals), now backed by `ExternalResolutions::definition_of`.
|
||||
- Added `editor.semanticHighlighting.enabled: true` under
|
||||
`configurationDefaults` and `semanticTokenScopes` for `verilog` and
|
||||
`systemverilog` in `editors/vscode/package.json`; added
|
||||
`editors/vscode/semanticTokens_test.js` (75 checks, all green under `node`)
|
||||
and listed it in `editors/vscode/.vscodeignore`.
|
||||
- Cargo/Rust toolchain is not installed on this Windows host; Rust formatting
|
||||
(`use_small_heuristics = "Max"`, ≤100 cols), clippy rules, and test
|
||||
invariants were audited manually for Gitea CI execution.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
@@ -184,11 +184,12 @@ documented difference below.
|
||||
|
||||
### What it gets wrong, honestly
|
||||
|
||||
- **A plain identifier is always `variable`, with no `declaration` modifier.**
|
||||
There is no `Semantics` to refine it with, so a module name is not a `class`
|
||||
and a parameter is not a `parameter`. Keywords, numbers, strings, comments,
|
||||
directives, macro uses, `$system` tasks and attributes are all exactly what
|
||||
the full pipeline says.
|
||||
- **A plain identifier is always `variable`, with no `declaration` modifier, and
|
||||
AST-only instantiation punctuation (`#`, `.`, `.*`) is unemitted.** There is
|
||||
no `Semantics` or `Document.tree` to refine them with, so a module name is
|
||||
not a `class` and a parameter or `#` is not a `parameter`. Keywords, numbers,
|
||||
strings, comments, directives, macro uses, `$system` tasks and attributes are
|
||||
all exactly what the full pipeline says.
|
||||
- **A `/*` inside a string or after a `//` fools the backward scan**, and so
|
||||
does a block comment whose opener is more than 64 KiB back — the documented
|
||||
answer there is "code", so a multi-megabyte block comment mis-highlights.
|
||||
|
||||
@@ -573,25 +573,35 @@ Modifiers: `0 declaration`.
|
||||
| `TokenKind::SystemIdent` (`$display`) | `function` |
|
||||
| `TokenKind::Attribute` (`(* ... *)`) | `decorator` |
|
||||
| `Comment` trivia (leading and trailing, incl. on the EOF token) | `comment` |
|
||||
| `TokenKind::Symbol` | **not emitted** |
|
||||
| `TokenKind::Ident`, otherwise | from `Semantics`, below |
|
||||
| `TokenKind::Symbol` (`#` before parameter lists; `.` / `.*` on named connections) | `parameter` / `property` |
|
||||
| `TokenKind::Symbol`, otherwise | **not emitted** |
|
||||
| `TokenKind::Ident`, otherwise | from `Document.tree` + `Semantics` + `ExternalResolutions`, below |
|
||||
|
||||
A plain identifier is looked up in the file's `Semantics` at its start offset:
|
||||
a declaration (`symbol_at`) gets its symbol's type **plus the `declaration`
|
||||
modifier**; a use (`reference_at`) that resolved in-file gets the resolved
|
||||
symbol's type; anything else — an external candidate, a not-found name, a name
|
||||
a macro would have produced — falls back to `variable`.
|
||||
A plain identifier first checks the AST overrides built by
|
||||
`tokens/instantiation.rs` (`docs/features/instantiation-highlighting/README.md`):
|
||||
an instantiated module or `extends` base takes `class` (`pkg::` prefixes take
|
||||
`namespace`), an instance name takes `function`, a `.PARAM` override and any
|
||||
unresolved constant identifier inside `#(...)` take `parameter` alongside `#`,
|
||||
and a `.port` connection takes `property`. Otherwise it is looked up through
|
||||
`ExternalResolutions::definition_of` (`Semantics` first, then the workspace
|
||||
overlay): a declaration (`symbol_at`) carries the `declaration` modifier, a
|
||||
resolved local or external reference takes its target's `SymbolKind`, and
|
||||
anything else falls back to `variable`.
|
||||
|
||||
`SymbolKind` → type: `Module`→`class`, `Package`→`namespace`,
|
||||
`Typedef`→`type`, `EnumVariant`→`enumMember`, `Param`/`TfArg`→`parameter`,
|
||||
`Function`/`Task`→`function`, `StructMember`→`property`, and
|
||||
`Port`/`Net`/`Var`/`Genvar`/`Instance`/`Block`→`variable`.
|
||||
`SymbolKind` → type: `Module`/`Interface`/`Modport`/`Class`/`Covergroup`→`class`,
|
||||
`Package`→`namespace`, `Typedef`→`type`, `EnumVariant`→`enumMember`,
|
||||
`Param`/`LocalParam`/`TfArg`→`parameter`,
|
||||
`Function`/`Task`/`Instance`/`Property`/`Sequence`→`function`,
|
||||
`StructMember`/`Constraint`/`Coverpoint`/`Cross`→`property`, and
|
||||
`Port`/`Net`/`Var`/`Genvar`/`Clocking`/`Block`→`variable`.
|
||||
|
||||
Two rules that are easy to get wrong and are tested:
|
||||
|
||||
- **Punctuation is not emitted.** Every editor already colors brackets from
|
||||
its TextMate grammar, and emitting one token per `;` roughly triples the
|
||||
payload for no visible gain.
|
||||
- **Ordinary punctuation (including `()`) is not emitted.** Every editor
|
||||
already colours brackets from its bracket-pair colorizer or TextMate grammar,
|
||||
and emitting one token per `;` roughly triples the payload for no visible
|
||||
gain; only the parameter-list `#` and named-connection `.`/`.*` carry AST
|
||||
highlights.
|
||||
- **No token ever spans a line break.** The spec requires it, and Verilog has
|
||||
three multi-line token shapes that would violate it — a block comment, a
|
||||
continued `` `define``, and a multi-line macro invocation. Every span is
|
||||
|
||||
+1
-1
@@ -159,7 +159,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
|
||||
| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. |
|
||||
| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]-<version>-<triple>` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `gates.sh` first (the release is gated since 0.65.1), then `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
|
||||
| `scripts/score.sh + tools/corpus_check.sh ──▶ lucisv` | depends | The frozen 0/1/2 exit-code contract, plus a **textual** dependency on the message prefixes `parse error:` / `lex error:` / `verification failed:` (a standing fragile coupling — rewording those means telling corpus-check; see §2.9). |
|
||||
|
||||
**Deliberately absent production edges** (also check shared file ownership):
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# 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
|
||||
extract_test.js
|
||||
restart_test.js
|
||||
hierarchyCurrent_test.js
|
||||
hierarchyPalette_test.js
|
||||
hierarchyModel_test.js
|
||||
hierarchySections_test.js
|
||||
hierarchyView_test.js
|
||||
referencesModel_test.js
|
||||
referencesView_test.js
|
||||
typing_test.js
|
||||
semanticTokens_test.js
|
||||
commentScan_test.js
|
||||
commentKeywords_test.js
|
||||
.vscode/**
|
||||
.gitignore
|
||||
@@ -5,6 +5,58 @@ 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.4 — 2026-11-19
|
||||
|
||||
- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a
|
||||
conditional-compilation region (`` `ifdef ``, `` `ifndef ``, `` `elsif ``,
|
||||
`` `else ``) collapses on its own; the next branch's line and `` `endif ``
|
||||
stay visible.
|
||||
- **They show in sticky scroll.** Scroll inside a long branch and its
|
||||
`` `ifdef `` or `` `else `` line stays pinned with the enclosing module and
|
||||
blocks.
|
||||
|
||||
## 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
|
||||
are editing are lit: every instance of its module in a light, bright orange
|
||||
with a solid bar at the edge, each parent above one shade dimmer, down to a
|
||||
faint floor. Switching files repaints only the rows that changed — no reload,
|
||||
nothing collapses.
|
||||
- **Restyle it or turn it off.** Six theme colours (`lucisv.hierarchyCurrent`,
|
||||
`lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor`,
|
||||
`lucisv.hierarchyCurrentBar`) and the setting
|
||||
`lucisv.hierarchy.highlightCurrent`.
|
||||
|
||||
## 0.65.1 — 2026-11-19
|
||||
|
||||
- **Nothing changes in the editor.** This is 0.65.0 rebuilt by a release
|
||||
process that now runs the full test gates before publishing.
|
||||
|
||||
## 0.65.0 — 2026-11-19
|
||||
|
||||
- **Module instantiations are now colour-coded by role.** Module names
|
||||
(`class`), instance names (`function`), port names (`.clk_i` and `.*`,
|
||||
`property`), and connected signals (`variable`) each take a distinct colour
|
||||
instead of blending together in white.
|
||||
- **`#` shares the parameter colour**, separate from `()`: the `#` before a
|
||||
parameter header or override list, `.PARAM` names, and parameter values
|
||||
highlight together as `parameter`, while `#5` delays stay untouched.
|
||||
- **Semantic highlighting works out of the box across themes.** The extension
|
||||
now enables `editor.semanticHighlighting.enabled` by default for Verilog and
|
||||
SystemVerilog and provides distinct TextMate fallback scopes for every role.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
- **`begin` + Enter writes the `end`.** The cursor lands on the indented
|
||||
|
||||
@@ -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.64.0**. Its platform packages include
|
||||
The current release is **0.65.4**. Its platform packages include
|
||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||
[Agents (MCP)](#agents-mcp)):
|
||||
|
||||
@@ -153,12 +153,13 @@ enabling both paths formats twice.
|
||||
| Document highlights | Highlights symbol occurrences or the matching opener/closer under the cursor |
|
||||
| Document and workspace symbols | Hierarchical outline plus indexed symbol search across the design |
|
||||
| Include links | Resolvable `` `include`` paths become clickable using local and filelist `+incdir+` search rules |
|
||||
| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries |
|
||||
| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if` — stays pinned at the top of the editor, up to ten lines deep |
|
||||
| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries; every branch of an `` `ifdef``/`` `ifndef`` region folds on its own, from its directive to the line before the next `` `elsif``/`` `else``/`` `endif``, which stays visible |
|
||||
| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if`, the `` `ifdef``/`` `else`` branch — stays pinned at the top of the editor, up to ten lines deep |
|
||||
| Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites |
|
||||
| Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site |
|
||||
| Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” |
|
||||
| Design hierarchy sidebar | Alphabetical instance paths from every top-level module, collapsed until you open them, in-memory fuzzy module/instance search, exact instance/definition jumps, path copy, bookmark highlighting, and split-right opening |
|
||||
| Current-file path | The pane lights the rows that lead to the file you are editing: every instance of the module it declares in a bright orange with a solid bar at its edge, each row above one shade dimmer with a narrower bar, down to a faint floor — in the plain tree, in every DUT section, and on a closed section's header. Switching files repaints only the rows that changed. The shades are the `lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor` and `lucisv.hierarchyCurrentBar` theme colours; `lucisv.hierarchy.highlightCurrent` turns it off |
|
||||
| DUT sections | Star a module as DUT and the pane splits into its own subtree, an upward tree of everything that instantiates it, and every module in neither — two sections per DUT plus one. Stars are remembered per workspace; `lucisv.hierarchy.duts` is the checked-in list a team shares |
|
||||
| Type hierarchy | Walks class `extends` relationships to supertypes and workspace subtypes |
|
||||
|
||||
@@ -170,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
|
||||
|
||||
@@ -318,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 |
|
||||
@@ -327,6 +332,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
|
||||
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
|
||||
| `lucisv.hierarchy.duts` | `[]` | Modules the Hierarchy pane treats as DUTs, by name — the checked-in list a team shares. Each one adds two sections ahead of "Other modules"; a DUT from this setting is shown locked and can only be removed here |
|
||||
| `lucisv.hierarchy.highlightCurrent` | `true` | Light the Hierarchy pane's rows leading to the active file, brightest on the file's own module and dimmer each level up |
|
||||
| `lucisv.index.scope` | `folder` | Index the folders your open files live in, or every workspace folder with `workspace`; answers stay scope-relative until the scope reaches a folder |
|
||||
| `lucisv.index.scopeDepth` | `0` | How many folders above an open file the `folder` scope starts from; `1` lets a file in `rtl/` index `include/` beside it |
|
||||
| `lucisv.index.maxFileSize` | `1 MiB` | Largest walked file the index reads, in bytes; `0` removes the cap, and a file you open is always indexed in full |
|
||||
@@ -421,6 +427,41 @@ 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.4 highlights
|
||||
|
||||
Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins
|
||||
the branch you are inside in sticky scroll.
|
||||
|
||||
## 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
|
||||
the module you are editing in a light, bright orange, and each parent above
|
||||
them a shade dimmer, so the path from the top of the design to the open file
|
||||
reads at a glance.
|
||||
|
||||
## Release 0.65.0 highlights
|
||||
|
||||
Version 0.65.0 gives module instantiations distinct syntax colours across
|
||||
themes: module names (`class`), instance names (`function`), port names
|
||||
(`.port` / `.*`, `property`), and connected signals (`variable`) each stand
|
||||
out, and parameter-list `#` signs share the `parameter` colour separately from
|
||||
parentheses.
|
||||
|
||||
## Release 0.64.0 highlights
|
||||
|
||||
Version 0.64.0 makes typing quicker: `begin` + Enter writes the `end`,
|
||||
|
||||
@@ -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 };
|
||||
@@ -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`);
|
||||
}
|
||||
});
|
||||
@@ -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) ? `(?<!${WORD_CHAR})` : '')
|
||||
+ escapeRegExp(word)
|
||||
+ (endsWord.test(word) ? `(?!${WORD_CHAR})` : ''));
|
||||
const flags = caseSensitive === false ? 'gi' : 'g';
|
||||
return new RegExp(alternatives.join('|'), flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `[start, end)` matches of `matcher` inside the bodies of `spans` — never
|
||||
* across a comment's own delimiters, whatever a custom word holds.
|
||||
*/
|
||||
function wordsInSpans(text, spans, matcher) {
|
||||
const found = [];
|
||||
for (const [, , start, end] of spans) {
|
||||
const inside = text.slice(start, end);
|
||||
matcher.lastIndex = 0;
|
||||
for (const match of inside.matchAll(matcher)) {
|
||||
found.push([start + match.index, start + match.index + match[0].length]);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per document: whether each line starts inside a block comment, computed
|
||||
* lazily from the top and kept until an edit above it invalidates it — so
|
||||
* scrolling or typing never rescans the lines above the edit.
|
||||
*
|
||||
* `maxLineLength` mirrors VS Code's `editor.maxTokenizationLineLength`: the
|
||||
* editor does not tokenize a line that long (`length >= 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,
|
||||
};
|
||||
@@ -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}`);
|
||||
}
|
||||
});
|
||||
@@ -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()),
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Which hierarchy rows lead to the file being edited, and how far from it each
|
||||
// one is. No `vscode` dependency, so plain Node tests cover all of it. See
|
||||
// docs/features/hierarchy-current-path/README.md.
|
||||
//
|
||||
// **A row's distance is a property of its module, not of its path.** It is how
|
||||
// many instantiation levels the module sits above the nearest module declared
|
||||
// in the current file — 0 for that module itself. The level below a row is the
|
||||
// module's own instance list wherever the row sits, so the answer is the same
|
||||
// for every row of a module, and one breadth-first walk up the module graph
|
||||
// answers it for every module at once. A row then costs a map lookup, and
|
||||
// nothing below a closed row is ever built to find out whether to light it.
|
||||
//
|
||||
// In a forward tree the lit rows are exactly the path from the root down to
|
||||
// each current instance. In an upward "Parents of" tree the same rule lights
|
||||
// the current file's parents among the DUT's parents — dimmer the further up
|
||||
// the design they are, which on that tree is further *down* the page.
|
||||
|
||||
const { headerId, parentIndex } = require('./hierarchySections');
|
||||
|
||||
/** The contributed theme colours, brightest first; the last one is the floor
|
||||
* every ancestor four or more levels up shares. */
|
||||
const LIT_COLORS = [
|
||||
'lucisv.hierarchyCurrent',
|
||||
'lucisv.hierarchyParent1',
|
||||
'lucisv.hierarchyParent2',
|
||||
'lucisv.hierarchyParent3',
|
||||
'lucisv.hierarchyAncestor',
|
||||
];
|
||||
|
||||
/** The solid bar at a lit row's left edge. The tints stay light enough for the
|
||||
* label to keep 4.5:1, so the bar is what carries "brightest": widest, solid
|
||||
* and fully opaque on the current row, narrower and fainter each level up. */
|
||||
const BAR_COLOR = 'lucisv.hierarchyCurrentBar';
|
||||
|
||||
/** The level a distance is painted at: 0 is the current row itself. */
|
||||
function litLevel(distance) {
|
||||
if (!Number.isInteger(distance) || distance < 0) return undefined;
|
||||
return Math.min(distance, LIT_COLORS.length - 1);
|
||||
}
|
||||
|
||||
/** The CSS variable a webview sees a theme colour as. VS Code replaces only the
|
||||
* *first* dot (`themeing.ts`: `entry.id.replace('.', '-')`), which is why every
|
||||
* id above has exactly one. */
|
||||
function cssVariableFor(colorId) {
|
||||
return `--vscode-${colorId.replace('.', '-')}`;
|
||||
}
|
||||
|
||||
/// The model's own spellings of the active file: every distinct definition URI
|
||||
/// `sameFile` accepts. The server and VS Code may spell one file differently, so
|
||||
/// the comparison is the caller's; this asks it once per file, not per module.
|
||||
function matchingFiles(model, sameFile) {
|
||||
const files = new Set();
|
||||
const asked = new Set();
|
||||
for (const module of model.modules) {
|
||||
const uri = module.definition.uri;
|
||||
if (asked.has(uri)) continue;
|
||||
asked.add(uri);
|
||||
if (sameFile(uri)) files.add(uri);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// Everything a render needs to light rows for one active file: the matching
|
||||
/// URIs, every module's distance, and a memo for the upward sections' headers.
|
||||
/// `undefined` when no module is declared there.
|
||||
function currentPath(model, files) {
|
||||
const current = model.modules.filter((module) => files.has(module.definition.uri));
|
||||
if (current.length === 0) return undefined;
|
||||
const parentsOf = (id) => (parentIndex(model).get(id) || []).map((edge) => edge.module);
|
||||
return { files, above: walk(current, parentsOf), parentsOf, sections: new Map() };
|
||||
}
|
||||
|
||||
/// Breadth-first from every current module at once, so where two chains meet
|
||||
/// the nearer one is the one recorded. Linear in modules plus instances.
|
||||
function walk(start, next) {
|
||||
const distance = new Map(start.map((module) => [module.id, 0]));
|
||||
let frontier = start;
|
||||
for (let step = 1; frontier.length > 0; step += 1) {
|
||||
const reached = [];
|
||||
for (const module of frontier) {
|
||||
for (const neighbour of next(module.id)) {
|
||||
if (distance.has(neighbour.id)) continue;
|
||||
distance.set(neighbour.id, step);
|
||||
reached.push(neighbour);
|
||||
}
|
||||
}
|
||||
frontier = reached;
|
||||
}
|
||||
return distance;
|
||||
}
|
||||
|
||||
/// The node's distance, or `undefined` when it is not lit. A forward row that
|
||||
/// cannot open (a leaf, a `recursive` repeat, an unresolved or ambiguous type)
|
||||
/// can only be current itself: what it would lead to is not under it on screen.
|
||||
/// An upward row is always its own module, so its module's distance is its own.
|
||||
function nodeDistance(node, path) {
|
||||
if (node.definition && path.files.has(node.definition.uri)) return 0;
|
||||
if (!node.moduleId || (!node.up && !node.hasChildren)) return undefined;
|
||||
return path.above.get(node.moduleId);
|
||||
}
|
||||
|
||||
/// A header lights one step dimmer than the nearest module its section holds,
|
||||
/// shown or not — which is what tells the user a *closed* section holds the
|
||||
/// current file, or the current file's parents.
|
||||
function sectionDistance(section, path) {
|
||||
const nearest = section.kind === 'parents' ? closureDistance(section, path) : forwardDistance(section, path);
|
||||
return nearest === undefined ? undefined : nearest + 1;
|
||||
}
|
||||
|
||||
/// A forward tree holds the current module exactly when one of its roots has
|
||||
/// a distance, and the current module is 0.
|
||||
function forwardDistance(section, path) {
|
||||
const roots = section.kind === 'others' ? section.roots.map(({ module }) => module)
|
||||
: (section.root ? [section.root] : []);
|
||||
return roots.some((root) => path.above.has(root.moduleId || root.id)) ? 0 : undefined;
|
||||
}
|
||||
|
||||
/// The upward tree holds the DUT and everything above it: the nearest of
|
||||
/// those, walked once per (path, section) and remembered on the path.
|
||||
function closureDistance(section, path) {
|
||||
if (!section.root) return undefined;
|
||||
const key = section.root.moduleId;
|
||||
if (path.sections.has(key)) return path.sections.get(key);
|
||||
let nearest;
|
||||
const seen = new Set([key]);
|
||||
const stack = [section.root.moduleId];
|
||||
while (stack.length > 0) {
|
||||
const id = stack.pop();
|
||||
const distance = path.above.get(id);
|
||||
if (distance !== undefined && (nearest === undefined || distance < nearest)) nearest = distance;
|
||||
for (const parent of path.parentsOf(id)) {
|
||||
if (!seen.has(parent.id)) {
|
||||
seen.add(parent.id);
|
||||
stack.push(parent.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
path.sections.set(key, nearest);
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/// Row id → lit level for the rows on screen. `nodes` is the id → node map the
|
||||
/// tree builders return; `list` is the section list, empty for the plain tree.
|
||||
/// Only lit rows are in the answer.
|
||||
function rowLevels(rows, nodes, list, path) {
|
||||
const levels = new Map();
|
||||
if (!path) return levels;
|
||||
const headers = new Map(list.map((section) => [headerId(section), section]));
|
||||
for (const row of rows) {
|
||||
const node = nodes.get(row.id);
|
||||
let distance;
|
||||
if (node) distance = nodeDistance(node, path);
|
||||
else if (row.kind === 'section' && headers.has(row.id)) distance = sectionDistance(headers.get(row.id), path);
|
||||
const level = litLevel(distance);
|
||||
if (level !== undefined) levels.set(row.id, level);
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
/// What changed between two answers of `rowLevels`, as `[id, level | null]`
|
||||
/// pairs: the only rows a new active file repaints.
|
||||
function levelChanges(before, after) {
|
||||
const changes = [];
|
||||
for (const [id, level] of after) {
|
||||
if (before.get(id) !== level) changes.push([id, level]);
|
||||
}
|
||||
for (const id of before.keys()) {
|
||||
if (!after.has(id)) changes.push([id, null]);
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BAR_COLOR,
|
||||
LIT_COLORS,
|
||||
cssVariableFor,
|
||||
currentPath,
|
||||
levelChanges,
|
||||
litLevel,
|
||||
matchingFiles,
|
||||
nodeDistance,
|
||||
rowLevels,
|
||||
};
|
||||
@@ -0,0 +1,322 @@
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildHierarchy, treeRows } = require('./hierarchyModel');
|
||||
const { sectionRows, sections } = require('./hierarchySections');
|
||||
const {
|
||||
BAR_COLOR,
|
||||
LIT_COLORS,
|
||||
cssVariableFor,
|
||||
currentPath,
|
||||
levelChanges,
|
||||
litLevel,
|
||||
matchingFiles,
|
||||
rowLevels,
|
||||
} = require('./hierarchyCurrent');
|
||||
|
||||
/** A snapshot from `{ module: [instantiated type, …] }`, one file per module
|
||||
* (`file:///<module>.sv`), instance names `u_<type>` (`u_<type>_<n>` for a
|
||||
* repeat). A type naming no module is an unresolved instance. */
|
||||
function design(graph, extraDeclarations = []) {
|
||||
const names = Object.keys(graph);
|
||||
const files = [...names.map((name) => `file:///${name}.sv`),
|
||||
...extraDeclarations.map((name) => `file:///${name}_2.sv`)];
|
||||
const place = (file, line) => ({ file, range: [line, 0, line, 9], selectionRange: [line, 1, line, 5] });
|
||||
const modules = names.map((name, file) => {
|
||||
const counts = new Map();
|
||||
const instances = graph[name].map((type, line) => {
|
||||
const n = (counts.get(type) || 0) + 1;
|
||||
counts.set(type, n);
|
||||
return { instanceName: n === 1 ? `u_${type}` : `u_${type}_${n}`, moduleName: type, site: place(file, line + 1) };
|
||||
});
|
||||
return { moduleName: name, definition: place(file, 0), instances };
|
||||
});
|
||||
// A second declaration of an existing name, in its own file: ambiguous.
|
||||
extraDeclarations.forEach((name, at) => {
|
||||
modules.push({ moduleName: name, definition: place(names.length + at, 0), instances: [] });
|
||||
});
|
||||
return buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files, modules });
|
||||
}
|
||||
|
||||
/** The current-file path for one module's file. */
|
||||
function pathFor(model, name) {
|
||||
return currentPath(model, matchingFiles(model, (uri) => uri === `file:///${name}.sv`));
|
||||
}
|
||||
|
||||
/** Every row of the plain tree, every row opened. */
|
||||
function openTree(model) {
|
||||
const expanded = new Set();
|
||||
for (;;) {
|
||||
const tree = treeRows(model, expanded, '');
|
||||
const before = expanded.size;
|
||||
for (const row of tree.rows) if (row.hasChildren) expanded.add(row.id);
|
||||
if (expanded.size === before) return { ...tree, list: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/** Label → level for the rows that are lit, in row order. */
|
||||
function lit(tree, pathValue) {
|
||||
const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathValue);
|
||||
return tree.rows.filter((row) => levels.has(row.id))
|
||||
.map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]);
|
||||
}
|
||||
|
||||
function distancesMapToLevelsWithAFloor() {
|
||||
assert.deepEqual([0, 1, 2, 3, 4, 5, 40].map(litLevel), [0, 1, 2, 3, 4, 4, 4]);
|
||||
assert.equal(litLevel(undefined), undefined);
|
||||
assert.equal(litLevel(-1), undefined);
|
||||
assert.equal(litLevel(1.5), undefined);
|
||||
assert.equal(LIT_COLORS.length, 5, 'one colour per level, the floor included');
|
||||
}
|
||||
|
||||
/** VS Code turns only the first dot into a dash (`themeing.ts`), so an id with
|
||||
* two dots would reach the webview under a name no stylesheet expects. */
|
||||
function colourIdsHaveOneDotAndTheCssUsesTheirVariables() {
|
||||
assert.equal(cssVariableFor('lucisv.hierarchyCurrent'), '--vscode-lucisv-hierarchyCurrent');
|
||||
assert.equal(cssVariableFor('a.b.c'), '--vscode-a-b.c', 'first dot only, as VS Code does');
|
||||
const css = fs.readFileSync(path.join(__dirname, 'media', 'hierarchy.css'), 'utf8');
|
||||
assert(css.includes(`var(${cssVariableFor(BAR_COLOR)},`), 'hierarchy.css paints the bar with its colour');
|
||||
assert.equal(BAR_COLOR.split('.').length, 2, `${BAR_COLOR} has exactly one dot`);
|
||||
LIT_COLORS.forEach((id, level) => {
|
||||
assert.equal(id.split('.').length, 2, `${id} has exactly one dot`);
|
||||
assert(css.includes(`.row[data-lit="${level}"] { --lit: var(${cssVariableFor(id)},`),
|
||||
`hierarchy.css paints level ${level} with ${id}`);
|
||||
});
|
||||
}
|
||||
|
||||
function packageJsonContributesTheColoursAndTheSetting() {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const ours = manifest.contributes.colors.filter((colour) => colour.id.startsWith('lucisv.hierarchy'));
|
||||
assert.deepEqual(ours.map((colour) => colour.id), [...LIT_COLORS, BAR_COLOR], 'contributed exactly, in level order');
|
||||
const bar = ours.at(-1);
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
assert.match(bar.defaults[theme], /^#[0-9A-F]{6}$/, `the bar is opaque in ${theme}`);
|
||||
}
|
||||
const colours = ours.slice(0, -1);
|
||||
for (const colour of colours) {
|
||||
assert(colour.description, `${colour.id} has a description`);
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
assert.match(colour.defaults[theme], /^#[0-9A-F]{8}$/, `${colour.id} has a translucent ${theme} default`);
|
||||
}
|
||||
}
|
||||
// Dimmer each step: the alpha falls level by level in every theme.
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
const alphas = colours.map((colour) => parseInt(colour.defaults[theme].slice(7), 16));
|
||||
assert(alphas.every((alpha, at) => at === 0 || alpha < alphas[at - 1]), `${theme} dims level by level`);
|
||||
assert(alphas.at(-1) > 0, `${theme}'s floor is still visible`);
|
||||
}
|
||||
const setting = manifest.contributes.configuration.properties['lucisv.hierarchy.highlightCurrent'];
|
||||
assert.equal(setting.type, 'boolean');
|
||||
assert.equal(setting.default, true);
|
||||
}
|
||||
|
||||
function theCurrentRowAndEachAncestorAreLitByDistance() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf', 'other'], leaf: [], other: [], lonely: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [
|
||||
['tb', 2],
|
||||
[' u_dut (dut)', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
], 'the sibling and the unrelated root stay unlit');
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'tb')), [['tb', 0]]);
|
||||
}
|
||||
|
||||
/** The point of the feature: a closed tree still says where the file is. */
|
||||
function aClosedTreeLightsTheRowsItShows() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] });
|
||||
const closed = { ...treeRows(model, new Set(), ''), list: [] };
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['tb', 2]]);
|
||||
}
|
||||
|
||||
function everyInstanceAndItsChainIsLitAndTheNearestDistanceWins() {
|
||||
// `shared` is under `top` directly and through `mid`, twice.
|
||||
const model = design({ top: ['mid', 'shared'], mid: ['shared', 'shared'], shared: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'shared')), [
|
||||
['top', 1],
|
||||
[' u_mid (mid)', 1],
|
||||
[' u_shared (shared)', 0],
|
||||
[' u_shared_2 (shared)', 0],
|
||||
[' u_shared (shared)', 0],
|
||||
], 'top is one level above its own instance, not two through mid');
|
||||
}
|
||||
|
||||
function deepAncestorsShareTheFloor() {
|
||||
const model = design({ a: ['b'], b: ['c'], c: ['d'], d: ['e'], e: ['f'], f: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'f')).map(([, level]) => level), [4, 4, 3, 2, 1, 0]);
|
||||
}
|
||||
|
||||
/** A file declaring two modules lights both, each with its own path. */
|
||||
function aFileDeclaringTwoModulesLightsBoth() {
|
||||
const model = design({ top: ['x', 'y'], x: [], y: [] });
|
||||
const both = currentPath(model, matchingFiles(model, (uri) => uri === 'file:///x.sv' || uri === 'file:///y.sv'));
|
||||
assert.deepEqual(lit(openTree(model), both), [['top', 1], [' u_x (x)', 0], [' u_y (y)', 0]]);
|
||||
}
|
||||
|
||||
/** A row that cannot open is lit only when it is itself current: an unresolved
|
||||
* or ambiguous type names no one module, and a `recursive` repeat leads
|
||||
* nowhere on screen. */
|
||||
function rowsThatCannotOpenAreOnlyEverCurrent() {
|
||||
const ambiguous = design({ top: ['dup', 'ghost'], dup: [] }, ['dup']);
|
||||
assert.deepEqual(lit(openTree(ambiguous), pathFor(ambiguous, 'dup')), [['dup', 0]],
|
||||
'the declaration in the file is lit; the ambiguous instance names no one module, so top is not above it');
|
||||
|
||||
const cycle = design({ top: ['a'], a: ['b'], b: ['a'] });
|
||||
assert.deepEqual(lit(openTree(cycle), pathFor(cycle, 'a')), [
|
||||
['top', 1],
|
||||
[' u_a (a)', 0],
|
||||
[' u_b (b)', 1],
|
||||
[' u_a (a)', 0],
|
||||
], 'the recursive repeat is current itself; b, between them, is one above it');
|
||||
const rows = lit(openTree(cycle), pathFor(cycle, 'b'));
|
||||
assert.deepEqual(rows, [['top', 2], [' u_a (a)', 1], [' u_b (b)', 0]],
|
||||
'the recursive `a` under b does not open, so it is not lit as b\'s parent');
|
||||
}
|
||||
|
||||
function aFileNoModuleIsDeclaredInLightsNothing() {
|
||||
const model = design({ top: ['leaf'], leaf: [] });
|
||||
assert.equal(currentPath(model, matchingFiles(model, () => false)), undefined);
|
||||
const tree = openTree(model);
|
||||
assert.equal(rowLevels(tree.rows, tree.nodes, tree.list, undefined).size, 0);
|
||||
}
|
||||
|
||||
function theFileComparisonIsAskedOncePerFile() {
|
||||
const model = design({ top: ['leaf', 'leaf'], leaf: [] });
|
||||
const asked = [];
|
||||
matchingFiles(model, (uri) => { asked.push(uri); return false; });
|
||||
assert.deepEqual(asked.sort(), ['file:///leaf.sv', 'file:///top.sv']);
|
||||
}
|
||||
|
||||
/** DUT sections: the forward section lights like the plain tree, the upward
|
||||
* "Parents of" tree lights the current file's parents by the same distance,
|
||||
* and every header is one level dimmer than the nearest module it holds. */
|
||||
function sectionsLightTheirTreesAndTheirHeaders() {
|
||||
const model = design({ tb: ['dut', 'mon'], dut: ['leaf'], leaf: [], mon: [], lonely: [] });
|
||||
const list = sections(model, ['dut']);
|
||||
const expanded = new Set(['sec:dut:dut', 'sec:parents:dut', 'sec:others']);
|
||||
for (let round = 0; round < 4; round += 1) {
|
||||
for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id);
|
||||
}
|
||||
const tree = { ...sectionRows(model, list, expanded, ''), list };
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'leaf')), [
|
||||
['DUT: dut', 1],
|
||||
[' dut', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
['Parents of dut', 2],
|
||||
[' dut', 1],
|
||||
[' tb', 2],
|
||||
], "the forward section is the path down to leaf; the upward one is leaf's parents, dimmer going up the design");
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'tb')), [
|
||||
['Parents of dut', 1],
|
||||
[' tb', 0],
|
||||
], 'tb is current wherever it is shown; the DUT is below it, so it is not lit');
|
||||
|
||||
// mon is beside the DUT, not above it: the upward tree holds mon's parent tb,
|
||||
// and mon itself is re-rooted in "Other modules" (dut-hierarchy's rule).
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'mon')), [
|
||||
['Parents of dut', 2],
|
||||
[' tb', 1],
|
||||
['Other modules', 1],
|
||||
[' mon', 0],
|
||||
]);
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'lonely')), [
|
||||
['Other modules', 1],
|
||||
[' lonely', 0],
|
||||
]);
|
||||
|
||||
// Closed sections still say which ones hold the file or its parents.
|
||||
const closed = { ...sectionRows(model, list, new Set(), ''), list };
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['DUT: dut', 1], ['Parents of dut', 2]]);
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'lonely')), [['Other modules', 1]]);
|
||||
}
|
||||
|
||||
/** A recursive repeat in the upward tree is still its own module, so it is lit
|
||||
* as that module — the upward rule has no "cannot open" exception. */
|
||||
function anUpwardRepeatIsLitAsItsModule() {
|
||||
const model = design({ top: ['a'], a: ['b'], b: ['a', 'leaf'], leaf: [] });
|
||||
const list = sections(model, ['b']);
|
||||
const expanded = new Set(['sec:parents:b']);
|
||||
for (let round = 0; round < 5; round += 1) {
|
||||
for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id);
|
||||
}
|
||||
const tree = { ...sectionRows(model, list, expanded, ''), list };
|
||||
const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf'));
|
||||
const upward = tree.rows.filter((row) => row.id === 'sec:parents:b' || row.id.startsWith('parents:'))
|
||||
.map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]);
|
||||
assert.deepEqual(upward, [
|
||||
['Parents of b', 2],
|
||||
[' b', 1],
|
||||
[' a', 2],
|
||||
[' b', 1],
|
||||
[' top', 3],
|
||||
], 'the repeated b closes the cycle and does not open, but is still b, one above leaf');
|
||||
}
|
||||
|
||||
function changesNameOnlyTheRowsWhoseLevelMoved() {
|
||||
const before = new Map([['a', 0], ['b', 1], ['c', 2]]);
|
||||
const after = new Map([['a', 0], ['b', 2], ['d', 0]]);
|
||||
assert.deepEqual(levelChanges(before, after), [['b', 2], ['d', 0], ['c', null]]);
|
||||
assert.deepEqual(levelChanges(after, after), []);
|
||||
}
|
||||
|
||||
/** Ids are untouched: lighting is a separate answer, never part of a row's id. */
|
||||
function lightingNeverChangesRowIds() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] });
|
||||
const tree = openTree(model);
|
||||
const ids = tree.rows.map((row) => row.id);
|
||||
rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf'));
|
||||
assert.deepEqual(openTree(model).rows.map((row) => row.id), ids);
|
||||
}
|
||||
|
||||
/** QA, 2026-11-19: edge cases the suite did not pin. */
|
||||
function anEmptySnapshotLightsNothing() {
|
||||
const model = buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files: [], modules: [] });
|
||||
assert.equal(currentPath(model, matchingFiles(model, () => true)), undefined);
|
||||
}
|
||||
|
||||
/** Two chains of different length to one ancestor: the shorter one is its
|
||||
* distance, and each row on the longer chain keeps its own. */
|
||||
function theShorterOfTwoUnequalChainsWins() {
|
||||
const model = design({ top: ['a', 'leaf'], a: ['b'], b: ['c'], c: ['leaf'], leaf: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [
|
||||
['top', 1],
|
||||
[' u_a (a)', 3],
|
||||
[' u_b (b)', 2],
|
||||
[' u_c (c)', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
[' u_leaf (leaf)', 0],
|
||||
]);
|
||||
}
|
||||
|
||||
/** A module instantiating itself terminates, and its cut repeat is lit only
|
||||
* when it is the current module. */
|
||||
function aSelfInstantiatingModuleTerminates() {
|
||||
const model = design({ top: ['a'], a: ['a', 'leaf'], leaf: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [['top', 2], [' u_a (a)', 1], [' u_leaf (leaf)', 0]]);
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'a')), [['top', 1], [' u_a (a)', 0], [' u_a (a)', 0]]);
|
||||
}
|
||||
|
||||
const tests = [
|
||||
anEmptySnapshotLightsNothing,
|
||||
theShorterOfTwoUnequalChainsWins,
|
||||
aSelfInstantiatingModuleTerminates,
|
||||
distancesMapToLevelsWithAFloor,
|
||||
colourIdsHaveOneDotAndTheCssUsesTheirVariables,
|
||||
packageJsonContributesTheColoursAndTheSetting,
|
||||
theCurrentRowAndEachAncestorAreLitByDistance,
|
||||
aClosedTreeLightsTheRowsItShows,
|
||||
everyInstanceAndItsChainIsLitAndTheNearestDistanceWins,
|
||||
deepAncestorsShareTheFloor,
|
||||
aFileDeclaringTwoModulesLightsBoth,
|
||||
rowsThatCannotOpenAreOnlyEverCurrent,
|
||||
aFileNoModuleIsDeclaredInLightsNothing,
|
||||
theFileComparisonIsAskedOncePerFile,
|
||||
sectionsLightTheirTreesAndTheirHeaders,
|
||||
anUpwardRepeatIsLitAsItsModule,
|
||||
changesNameOnlyTheRowsWhoseLevelMoved,
|
||||
lightingNeverChangesRowIds,
|
||||
];
|
||||
for (const test of tests) test();
|
||||
|
||||
console.log(`hierarchy current path: OK — ${tests.length} checks: distances and the floor, colour ids and CSS variables, the manifest, every instance lit, nearest distance wins, closed trees and sections, the upward tree, cycles and unresolved rows`);
|
||||
@@ -0,0 +1,149 @@
|
||||
// The current-path palette, measured: the five tints and the bar contributed in
|
||||
// package.json, blended over representative sidebar colours of the built-in
|
||||
// themes, must keep the row label readable (WCAG AA, 4.5:1) at every level —
|
||||
// hovered too — and keep neighbouring levels visibly apart (ΔE76 ≥ 3). This is
|
||||
// what stops a palette tweak from silently making the brightest row the
|
||||
// hardest one to read (QA F1/F2, docs/features/hierarchy-current-path).
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { BAR_COLOR, LIT_COLORS } = require('./hierarchyCurrent');
|
||||
|
||||
/** Sidebar background, list foreground, list hover background per theme. */
|
||||
const THEMES = [
|
||||
{ kind: 'dark', name: 'Dark Modern', background: '#181818', foreground: '#CCCCCC', hover: '#2A2D2E' },
|
||||
{ kind: 'dark', name: 'Dark+', background: '#252526', foreground: '#CCCCCC', hover: '#2A2D2E' },
|
||||
{ kind: 'light', name: 'Light Modern', background: '#F8F8F8', foreground: '#3B3B3B', hover: '#F2F2F2' },
|
||||
{ kind: 'light', name: 'Light+', background: '#F3F3F3', foreground: '#616161', hover: '#E8E8E8' },
|
||||
{ kind: 'highContrast', name: 'HC Dark', background: '#000000', foreground: '#FFFFFF' },
|
||||
{ kind: 'highContrastLight', name: 'HC Light', background: '#FFFFFF', foreground: '#292929' },
|
||||
];
|
||||
|
||||
const TEXT_CONTRAST = 4.5;
|
||||
const BAR_CONTRAST = 3;
|
||||
const NEIGHBOUR_DELTA_E = 3;
|
||||
|
||||
function rgba(hex) {
|
||||
const value = hex.replace('#', '');
|
||||
const channel = (at) => parseInt(value.slice(at, at + 2), 16);
|
||||
return { rgb: [channel(0), channel(2), channel(4)], alpha: value.length === 8 ? channel(6) / 255 : 1 };
|
||||
}
|
||||
|
||||
/** Source-over, rounded to 8 bits as the compositor does. */
|
||||
function over(hex, background) {
|
||||
const { rgb, alpha } = rgba(hex);
|
||||
const base = rgba(background).rgb;
|
||||
return rgb.map((c, at) => Math.round(c * alpha + base[at] * (1 - alpha)));
|
||||
}
|
||||
|
||||
function linear(channel) {
|
||||
const c = channel / 255;
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
function luminance(rgb) {
|
||||
const [r, g, b] = rgb.map(linear);
|
||||
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);
|
||||
}
|
||||
|
||||
function lab(rgb) {
|
||||
const [r, g, b] = rgb.map(linear);
|
||||
const x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;
|
||||
const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
|
||||
const z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;
|
||||
const f = (t) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);
|
||||
return [116 * f(y) - 16, 500 * (f(x) - f(y)), 200 * (f(y) - f(z))];
|
||||
}
|
||||
|
||||
function deltaE(a, b) {
|
||||
const [p, q] = [lab(a), lab(b)];
|
||||
return Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
|
||||
}
|
||||
|
||||
const toHex = (rgb) => `#${rgb.map((c) => c.toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const byId = new Map(manifest.contributes.colors.map((colour) => [colour.id, colour]));
|
||||
const defaultsOf = (id) => {
|
||||
assert(byId.has(id), `${id} is contributed`);
|
||||
return byId.get(id).defaults;
|
||||
};
|
||||
|
||||
/** One table row per theme, printed so a palette change shows its numbers. */
|
||||
function measure(theme) {
|
||||
const levels = LIT_COLORS.map((id) => over(defaultsOf(id)[theme.kind], theme.background));
|
||||
const unlit = rgba(theme.background).rgb;
|
||||
const foreground = rgba(theme.foreground).rgb;
|
||||
return {
|
||||
levels,
|
||||
text: levels.map((level) => contrast(foreground, level)),
|
||||
hovered: theme.hover
|
||||
? LIT_COLORS.map((id) => contrast(foreground, over(defaultsOf(id)[theme.kind], theme.hover)))
|
||||
: [],
|
||||
// Neighbours from the brightest down, then the floor against an unlit row.
|
||||
steps: [...levels.slice(1).map((level, at) => deltaE(level, levels[at])), deltaE(levels.at(-1), unlit)],
|
||||
fromUnlit: levels.map((level) => deltaE(level, unlit)),
|
||||
bar: contrast(over(defaultsOf(BAR_COLOR)[theme.kind], theme.background), unlit),
|
||||
};
|
||||
}
|
||||
|
||||
function everyLevelKeepsTheLabelReadable() {
|
||||
for (const theme of THEMES) {
|
||||
const { text, hovered } = measure(theme);
|
||||
text.forEach((ratio, level) => assert(ratio >= TEXT_CONTRAST,
|
||||
`${theme.name}: label on level ${level} is ${ratio.toFixed(2)}:1, under ${TEXT_CONTRAST}`));
|
||||
hovered.forEach((ratio, level) => assert(ratio >= TEXT_CONTRAST,
|
||||
`${theme.name}: label on hovered level ${level} is ${ratio.toFixed(2)}:1, under ${TEXT_CONTRAST}`));
|
||||
}
|
||||
}
|
||||
|
||||
function neighbouringLevelsCanBeToldApart() {
|
||||
for (const theme of THEMES) {
|
||||
measure(theme).steps.forEach((step, at) => {
|
||||
const pair = at === LIT_COLORS.length - 1 ? `floor/unlit` : `${at}/${at + 1}`;
|
||||
assert(step >= NEIGHBOUR_DELTA_E, `${theme.name}: levels ${pair} differ by ΔE ${step.toFixed(1)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function theCurrentRowIsTheBrightest() {
|
||||
for (const theme of THEMES) {
|
||||
const { fromUnlit } = measure(theme);
|
||||
assert(fromUnlit.every((distance, at) => at === 0 || distance < fromUnlit[at - 1]),
|
||||
`${theme.name}: each level is further from an unlit row than the next`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The bar carries the brightness the tint gave up for legibility, so it must
|
||||
* itself be visible: WCAG 1.4.11 non-text contrast against the sidebar. */
|
||||
function theBarStandsOutFromTheSidebar() {
|
||||
for (const theme of THEMES) {
|
||||
const { bar } = measure(theme);
|
||||
assert(bar >= BAR_CONTRAST, `${theme.name}: the current-row bar is ${bar.toFixed(2)}:1, under ${BAR_CONTRAST}`);
|
||||
}
|
||||
}
|
||||
|
||||
function printTable() {
|
||||
for (const theme of THEMES) {
|
||||
const m = measure(theme);
|
||||
const fmt = (list, digits) => list.map((value) => value.toFixed(digits)).join(' ');
|
||||
console.log(` ${theme.name.padEnd(12)} text ${fmt(m.text, 2)}${m.hovered.length ? ` | hovered ${fmt(m.hovered, 2)}` : ''}`
|
||||
+ ` | ΔE 0/1..floor/unlit ${fmt(m.steps, 1)} | bar ${m.bar.toFixed(2)} | ${m.levels.map(toHex).join(' ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
const tests = [
|
||||
everyLevelKeepsTheLabelReadable,
|
||||
neighbouringLevelsCanBeToldApart,
|
||||
theCurrentRowIsTheBrightest,
|
||||
theBarStandsOutFromTheSidebar,
|
||||
];
|
||||
for (const test of tests) test();
|
||||
if (process.env.LUCISV_PALETTE_TABLE) printTable();
|
||||
|
||||
console.log(`hierarchy palette: OK — ${tests.length} checks over ${THEMES.length} themes: label ≥ ${TEXT_CONTRAST}:1 on every level and hovered, neighbours ΔE ≥ ${NEIGHBOUR_DELTA_E}, brightest first, bar ≥ ${BAR_CONTRAST}:1`);
|
||||
@@ -303,6 +303,7 @@ function prefixFor(kind, name) {
|
||||
/** The `others` section's row id; it has no DUT name to be keyed by. */
|
||||
const OTHERS_ID = 'sec:others';
|
||||
|
||||
/** A section header's row id, stable across renders. */
|
||||
function headerId(section) {
|
||||
return section.kind === 'others' ? OTHERS_ID : `sec:${section.kind}:${section.name}`;
|
||||
}
|
||||
@@ -452,6 +453,7 @@ module.exports = {
|
||||
OTHERS_ID,
|
||||
decorate,
|
||||
defaultOpenIds,
|
||||
headerId,
|
||||
menuTable,
|
||||
parentIndex,
|
||||
sectionPrefixes,
|
||||
|
||||
@@ -17,6 +17,12 @@ const {
|
||||
sectionRows,
|
||||
sections,
|
||||
} = require('./hierarchySections');
|
||||
const {
|
||||
currentPath,
|
||||
levelChanges,
|
||||
matchingFiles,
|
||||
rowLevels,
|
||||
} = require('./hierarchyCurrent');
|
||||
|
||||
const VIEW_ID = 'lucisv.hierarchy';
|
||||
const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy';
|
||||
@@ -26,6 +32,8 @@ const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark';
|
||||
const DUTS_KEY = 'lucisv.hierarchy.duts';
|
||||
/** The same list as a setting, so a team can check theirs in. */
|
||||
const DUTS_SETTING = 'hierarchy.duts';
|
||||
/** Whether the rows leading to the active file are lit (default on). */
|
||||
const HIGHLIGHT_SETTING = 'hierarchy.highlightCurrent';
|
||||
const REFRESH_DEBOUNCE_MS = 100;
|
||||
|
||||
class HierarchyView {
|
||||
@@ -49,6 +57,14 @@ class HierarchyView {
|
||||
// more; `duts()` is the union the pane actually shows.
|
||||
this.starred = moduleNames(context.workspaceState.get(DUTS_KEY, []));
|
||||
this.seededFor = undefined;
|
||||
// The current-file path (TODO §71.6). `shown` is the tree the webview holds
|
||||
// — kept while a search list covers it, because its rows are still in the
|
||||
// page — and `levels` what each of its rows is lit at, so a new active file
|
||||
// repaints only the rows whose level changed.
|
||||
this.activeUri = activeUriOf(vscode.window.activeTextEditor);
|
||||
this.pathCache = undefined;
|
||||
this.shown = { rows: [], nodes: new Map(), list: [] };
|
||||
this.levels = new Map();
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(VIEW_ID, this, {
|
||||
@@ -60,10 +76,12 @@ class HierarchyView {
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.unstarDut', (name) => this.unstarDut(name)),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.clearDuts', () => this.clearDuts()),
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
if (event.affectsConfiguration(`lucisv.${HIGHLIGHT_SETTING}`)) this.relight();
|
||||
if (!event.affectsConfiguration('lucisv.hierarchy.duts')) return;
|
||||
this.seededFor = undefined;
|
||||
this.render();
|
||||
}),
|
||||
vscode.window.onDidChangeActiveTextEditor((editor) => this.activeEditorChanged(editor)),
|
||||
client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()),
|
||||
{ dispose: () => clearTimeout(this.refreshTimer) },
|
||||
);
|
||||
@@ -167,7 +185,14 @@ class HierarchyView {
|
||||
}
|
||||
const tree = this.treeOrSections(duts);
|
||||
this.nodes = tree.nodes;
|
||||
this.shown = tree;
|
||||
this.levels = rowLevels(tree.rows, tree.nodes, tree.list, this.currentPath());
|
||||
const rows = decorate(tree.rows, duts, locked);
|
||||
// Only a lit row carries the field, so an unlit pane's rows are exactly
|
||||
// what they were before this feature.
|
||||
for (const row of rows) {
|
||||
if (this.levels.has(row.id)) row.lit = this.levels.get(row.id);
|
||||
}
|
||||
this.post({ ...common, mode: 'tree', rows, truncated: 0, total: rows.length });
|
||||
}
|
||||
|
||||
@@ -177,11 +202,47 @@ class HierarchyView {
|
||||
if (duts.length === 0) {
|
||||
// Recorded even here, so re-starring after a clear seeds again.
|
||||
this.seededFor = key;
|
||||
return treeRows(this.model, this.expanded, this.bookmarkPath);
|
||||
return { ...treeRows(this.model, this.expanded, this.bookmarkPath), list: [] };
|
||||
}
|
||||
const list = sections(this.model, duts);
|
||||
this.seedExpansion(list, key);
|
||||
return sectionRows(this.model, list, this.expanded, this.bookmarkPath);
|
||||
return { ...sectionRows(this.model, list, this.expanded, this.bookmarkPath), list };
|
||||
}
|
||||
|
||||
/// A new active editor relights the tree the webview already holds. No
|
||||
/// snapshot request and no row rebuild: two walks over the module graph,
|
||||
/// one lookup per row on screen, and a message naming the rows that changed.
|
||||
activeEditorChanged(editor) {
|
||||
// Focus leaving for a panel or a webview is not a new file; only an editor
|
||||
// area with nothing open in it is.
|
||||
if (!editor && vscode.window.visibleTextEditors.length > 0) return;
|
||||
const uri = activeUriOf(editor);
|
||||
if (editor && uri === undefined) return;
|
||||
if (uri === this.activeUri) return;
|
||||
this.activeUri = uri;
|
||||
this.relight();
|
||||
}
|
||||
|
||||
relight() {
|
||||
if (!this.model) return;
|
||||
const levels = rowLevels(this.shown.rows, this.shown.nodes, this.shown.list, this.currentPath());
|
||||
const changes = levelChanges(this.levels, levels);
|
||||
this.levels = levels;
|
||||
if (changes.length > 0) this.post({ type: 'lit', changes });
|
||||
}
|
||||
|
||||
/// The distance maps for the active file, computed once per (snapshot, file)
|
||||
/// pair, so opening rows under one file never walks the graph again.
|
||||
currentPath() {
|
||||
const enabled = vscode.workspace.getConfiguration('lucisv').get(HIGHLIGHT_SETTING, true);
|
||||
if (enabled === false || !this.model || !this.activeUri) return undefined;
|
||||
const cache = this.pathCache;
|
||||
if (cache && cache.model === this.model && cache.uri === this.activeUri) return cache.path;
|
||||
const active = this.activeUri;
|
||||
const files = matchingFiles(this.model, (uri) => sameUri(uri, active));
|
||||
const path = currentPath(this.model, files);
|
||||
this.pathCache = { model: this.model, uri: active, path };
|
||||
return path;
|
||||
}
|
||||
|
||||
/// Open the new sections once, when the DUT list changes — not on every
|
||||
@@ -378,6 +439,26 @@ class HierarchyView {
|
||||
}
|
||||
}
|
||||
|
||||
/// The active editor's file as a comparable string, or `undefined` for none.
|
||||
/// The Output panel's channels are text editors too, and are never a module.
|
||||
function activeUriOf(editor) {
|
||||
const uri = editor && editor.document && editor.document.uri;
|
||||
if (!uri || uri.scheme === 'output') return undefined;
|
||||
return uri.toString();
|
||||
}
|
||||
|
||||
/// The server writes URIs itself, and may encode them differently from VS Code
|
||||
/// (`file:///c%3A/…` against `file:///c:/…`); parsing both through `vscode.Uri`
|
||||
/// puts them in one spelling.
|
||||
function sameUri(serverUri, activeUri) {
|
||||
if (serverUri === activeUri) return true;
|
||||
try {
|
||||
return vscode.Uri.parse(serverUri).toString() === activeUri;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// A stored or configured DUT list, made safe: non-strings, blanks and repeats
|
||||
/// are dropped, and the order the user chose is kept.
|
||||
function moduleNames(value) {
|
||||
|
||||
@@ -17,6 +17,9 @@ let provider;
|
||||
let receive;
|
||||
let changed;
|
||||
let configurationChanged;
|
||||
let activeEditorChanged;
|
||||
/** What `lucisv.hierarchy.highlightCurrent` is set to; unset is the default. */
|
||||
let highlightCurrent;
|
||||
|
||||
class Range {
|
||||
constructor(startLine, startCharacter, endLine, endCharacter) {
|
||||
@@ -43,7 +46,13 @@ const vscode = {
|
||||
asRelativePath(uri) { return uri.fsPath; },
|
||||
getConfiguration(section) {
|
||||
assert.equal(section, 'lucisv');
|
||||
return { get(key, fallback) { return key === 'hierarchy.duts' ? configuredDuts : fallback; } };
|
||||
return {
|
||||
get(key, fallback) {
|
||||
if (key === 'hierarchy.duts') return configuredDuts;
|
||||
if (key === 'hierarchy.highlightCurrent' && highlightCurrent !== undefined) return highlightCurrent;
|
||||
return fallback;
|
||||
},
|
||||
};
|
||||
},
|
||||
onDidChangeConfiguration(handler) { configurationChanged = handler; return disposables(); },
|
||||
async openTextDocument(uri) {
|
||||
@@ -56,6 +65,9 @@ const vscode = {
|
||||
},
|
||||
},
|
||||
window: {
|
||||
activeTextEditor: undefined,
|
||||
visibleTextEditors: [],
|
||||
onDidChangeActiveTextEditor(handler) { activeEditorChanged = handler; return disposables(); },
|
||||
registerWebviewViewProvider(_id, value) { provider = value; return disposables(); },
|
||||
async showTextDocument(document, options) { shown.push({ document, options }); },
|
||||
async showQuickPick(items) { picked = items; return items[0]; },
|
||||
@@ -304,8 +316,70 @@ async function run() {
|
||||
]);
|
||||
await commands.get('lucisv.hierarchy.clearDuts')();
|
||||
|
||||
await theActiveFileIsLitWithoutARefetch(rendered);
|
||||
await persistenceSurvivesAReload();
|
||||
console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, no preview, and DUT sections (star, unstar, clear, persistence, the setting lock)');
|
||||
console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, no preview, DUT sections (star, unstar, clear, persistence, the setting lock), and the active file lit (relit in place, no refetch, the setting)');
|
||||
}
|
||||
|
||||
function editorFor(value, scheme = 'file') {
|
||||
return { document: { uri: { scheme, toString: () => value } } };
|
||||
}
|
||||
|
||||
/// TODO §71.6: the rows leading to the active file are lit, and a new active
|
||||
/// file repaints only the rows whose level changed — no snapshot request, no
|
||||
/// render, ids untouched.
|
||||
async function theActiveFileIsLitWithoutARefetch(rendered) {
|
||||
// The bookmark from earlier paints its own background; clear it so these
|
||||
// rows show only the lighting.
|
||||
await commands.get('lucisv.hierarchy.clearBookmark')();
|
||||
const plain = rendered();
|
||||
assert(plain.rows.every((row) => !('lit' in row)), 'with no active file, no row carries `lit`');
|
||||
const ids = plain.rows.map((row) => row.id);
|
||||
assert.deepEqual(plain.rows.map((row) => row.label), ['top', 'u (sub)']);
|
||||
|
||||
const requestsBefore = requests;
|
||||
const rendersBefore = posted.filter((message) => message.type === 'render').length;
|
||||
vscode.window.visibleTextEditors = [editorFor('file:///sub.sv')];
|
||||
activeEditorChanged(editorFor('file:///sub.sv'));
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], 1], [ids[1], 0]] });
|
||||
|
||||
activeEditorChanged(editorFor('file:///top.sv'));
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], 0], [ids[1], null]] },
|
||||
'only the two rows whose level moved');
|
||||
const before = posted.length;
|
||||
activeEditorChanged(editorFor('file:///top.sv'));
|
||||
activeEditorChanged(undefined);
|
||||
activeEditorChanged(editorFor('output:channel', 'output'));
|
||||
assert.equal(posted.length, before, 'the same file, focus leaving for a panel, or the Output panel repaint nothing');
|
||||
assert.equal(requests, requestsBefore, 'relighting never asks the server');
|
||||
assert.equal(posted.filter((message) => message.type === 'render').length, rendersBefore, 'nor re-renders');
|
||||
|
||||
// A render — opening a row, a refresh — carries the level on the lit rows.
|
||||
await receive({ type: 'toggle', id: ids[0] });
|
||||
await receive({ type: 'toggle', id: ids[0] });
|
||||
assert.deepEqual(rendered().rows.map((row) => [row.label, row.lit]), [['top', 0], ['u (sub)', undefined]]);
|
||||
assert.deepEqual(rendered().rows.map((row) => row.id), ids, 'ids are untouched, so expansion survives');
|
||||
|
||||
// A file no module is declared in lights nothing.
|
||||
activeEditorChanged(editorFor('file:///notes.txt'));
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], null]] });
|
||||
|
||||
// The setting turns it off, and back on.
|
||||
activeEditorChanged(editorFor('file:///sub.sv'));
|
||||
highlightCurrent = false;
|
||||
configurationChanged({ affectsConfiguration: (key) => key === 'lucisv.hierarchy.highlightCurrent' });
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], null], [ids[1], null]] });
|
||||
await receive({ type: 'toggle', id: ids[0] });
|
||||
await receive({ type: 'toggle', id: ids[0] });
|
||||
assert(rendered().rows.every((row) => !('lit' in row)), 'off means no row is lit on a render either');
|
||||
highlightCurrent = undefined;
|
||||
configurationChanged({ affectsConfiguration: (key) => key === 'lucisv.hierarchy.highlightCurrent' });
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], 1], [ids[1], 0]] });
|
||||
|
||||
// Closing every editor clears it.
|
||||
vscode.window.visibleTextEditors = [];
|
||||
activeEditorChanged(undefined);
|
||||
assert.deepEqual(posted.at(-1), { type: 'lit', changes: [[ids[0], null], [ids[1], null]] });
|
||||
}
|
||||
|
||||
/// A fresh view over the same `workspaceState`: what was starred is starred
|
||||
|
||||
@@ -61,36 +61,44 @@ body {
|
||||
background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background));
|
||||
font-weight: 700;
|
||||
}
|
||||
#menu button[disabled] { color: var(--vscode-disabledForeground, var(--vscode-descriptionForeground)); }
|
||||
#menu button[disabled]:hover { background: transparent; color: var(--vscode-disabledForeground, var(--vscode-descriptionForeground)); }
|
||||
.twisty { width: 12px; flex: 0 0 12px; text-align: center; }
|
||||
.icon { width: 14px; flex: 0 0 14px; color: var(--vscode-symbolIcon-moduleForeground, var(--vscode-foreground)); }
|
||||
.label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.detail { margin-left: auto; font-size: .9em; color: var(--vscode-descriptionForeground); }
|
||||
#menu {
|
||||
position: fixed;
|
||||
z-index: 10;
|
||||
width: 185px;
|
||||
padding: 4px;
|
||||
background: var(--vscode-menu-background);
|
||||
color: var(--vscode-menu-foreground);
|
||||
border: 1px solid var(--vscode-menu-border, var(--vscode-widget-border));
|
||||
box-shadow: 0 4px 12px var(--vscode-widget-shadow);
|
||||
/* The path to the active file (docs/features/hierarchy-current-path).
|
||||
Two layers, both background *images* so they sit over whatever colour the
|
||||
row already has — hover, a sticky section header — instead of replacing it:
|
||||
- a translucent tint, kept light enough that the label stays >= 4.5:1 at
|
||||
every level (hierarchyPalette_test.js measures the defaults);
|
||||
- a bar at the left edge, which carries "brightest": solid, 4px and fully
|
||||
opaque on the current row, then narrower, fainter and finally dashed each
|
||||
level up. Width and style are the cue that is not colour.
|
||||
A bookmark is the user's own explicit mark: it keeps its yellow fill and
|
||||
border and drops the tint, and the bar stays to say the row is also current.
|
||||
The var() fallbacks are the dark defaults, for a host without the colours. */
|
||||
.row[data-lit] {
|
||||
--bar: color-mix(in srgb, var(--vscode-lucisv-hierarchyCurrentBar, #ffb347) var(--bar-alpha), transparent);
|
||||
--bar-solid: linear-gradient(var(--bar), var(--bar));
|
||||
--bar-dashed: repeating-linear-gradient(to bottom, var(--bar) 0 3px, transparent 3px 5px);
|
||||
background-image: var(--bar-image), linear-gradient(var(--lit), var(--lit));
|
||||
background-size: var(--bar-width) 100%, 100% 100%;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
#menu button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 4px 8px;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
}
|
||||
#menu button:hover, #menu button:focus {
|
||||
color: var(--vscode-menu-selectionForeground);
|
||||
background: var(--vscode-menu-selectionBackground);
|
||||
outline: none;
|
||||
.row[data-lit="0"] { --lit: var(--vscode-lucisv-hierarchyCurrent, #ffb34745); --bar-width: 4px; --bar-alpha: 100%; --bar-image: var(--bar-solid); }
|
||||
.row[data-lit="1"] { --lit: var(--vscode-lucisv-hierarchyParent1, #ffb34730); --bar-width: 3px; --bar-alpha: 80%; --bar-image: var(--bar-solid); }
|
||||
.row[data-lit="2"] { --lit: var(--vscode-lucisv-hierarchyParent2, #ffb34721); --bar-width: 2px; --bar-alpha: 65%; --bar-image: var(--bar-solid); }
|
||||
.row[data-lit="3"] { --lit: var(--vscode-lucisv-hierarchyParent3, #ffb34716); --bar-width: 2px; --bar-alpha: 55%; --bar-image: var(--bar-dashed); }
|
||||
.row[data-lit="4"] { --lit: var(--vscode-lucisv-hierarchyAncestor, #ffb3470d); --bar-width: 1px; --bar-alpha: 45%; --bar-image: var(--bar-dashed); }
|
||||
.row[data-lit="0"] .label { font-weight: 600; }
|
||||
.row.bookmarked[data-lit] { background-image: var(--bar-image); background-size: var(--bar-width) 100%; }
|
||||
/* High contrast: the current row also gets the theme's active border — unless
|
||||
it is bookmarked, whose border is the bookmark's. */
|
||||
body.vscode-high-contrast .row[data-lit="0"]:not(.bookmarked),
|
||||
body.vscode-high-contrast-light .row[data-lit="0"]:not(.bookmarked) {
|
||||
border-color: var(--vscode-contrastActiveBorder, var(--vscode-focusBorder));
|
||||
}
|
||||
[hidden] { display: none !important; }
|
||||
@media (forced-colors: active) { .row.bookmarked { outline: 2px solid Highlight; } }
|
||||
@media (forced-colors: active) {
|
||||
.row.bookmarked { outline: 2px solid Highlight; }
|
||||
/* Forced colours drop every background image, so the tint and the bar are
|
||||
gone and levels 1-4 have no cue here. The current row keeps a dashed
|
||||
*border* (and its bold label) — a border, not an outline, so the focus
|
||||
ring and the bookmark outline stay its own. */
|
||||
.row[data-lit="0"] { border-style: dashed; border-color: CanvasText; }
|
||||
}
|
||||
@@ -18,6 +18,8 @@ const SEARCH_DEBOUNCE_MS = 60;
|
||||
let payload = { mode: 'tree', rows: [], truncated: 0, query: '', menus: {} };
|
||||
let menuNode;
|
||||
let searchTimer;
|
||||
/** The tree's row buttons by id, so a new active file repaints in place. */
|
||||
let treeButtons = new Map();
|
||||
|
||||
search.addEventListener('input', () => {
|
||||
clearTimeout(searchTimer);
|
||||
@@ -47,6 +49,10 @@ window.addEventListener('message', ({ data }) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (data.type === 'lit') {
|
||||
relight(data.changes);
|
||||
return;
|
||||
}
|
||||
if (data.type !== 'render') return;
|
||||
payload = data;
|
||||
if (search.value !== data.query) search.value = data.query;
|
||||
@@ -60,8 +66,15 @@ function render() {
|
||||
const searching = payload.mode === 'search';
|
||||
const container = searching ? results : tree;
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const row of payload.rows) fragment.appendChild(renderRow(row, searching));
|
||||
const buttons = new Map();
|
||||
for (const row of payload.rows) {
|
||||
const node = renderRow(row, searching);
|
||||
buttons.set(row.id, node.firstChild);
|
||||
fragment.appendChild(node);
|
||||
}
|
||||
container.replaceChildren(fragment);
|
||||
// A search list leaves the tree's rows in the page, so they keep relighting.
|
||||
if (!searching) treeButtons = buttons;
|
||||
tree.hidden = searching;
|
||||
results.hidden = !searching;
|
||||
|
||||
@@ -94,6 +107,7 @@ function renderRow(row, searching) {
|
||||
button.style.setProperty('--depth', row.depth);
|
||||
if (row.bookmarked) button.classList.add('bookmarked');
|
||||
if (row.warning) button.classList.add('warning');
|
||||
setLit(button, row.lit);
|
||||
if (searching) button.classList.add('match');
|
||||
if (row.hasChildren) button.setAttribute('aria-expanded', String(row.expanded));
|
||||
|
||||
@@ -135,6 +149,25 @@ function renderRow(row, searching) {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
// The path to the active file: level 0 is the row whose module that file
|
||||
// declares, each step up one shade dimmer, down to a floor (hierarchy.css).
|
||||
// Only the rows whose level changed are touched; nothing is rebuilt.
|
||||
function relight(changes) {
|
||||
if (!Array.isArray(changes)) return;
|
||||
for (const change of changes) {
|
||||
// The host only sends pairs; anything else is ignored, never thrown on.
|
||||
if (!Array.isArray(change)) continue;
|
||||
const [id, level] = change;
|
||||
const button = treeButtons.get(id);
|
||||
if (button) setLit(button, level);
|
||||
}
|
||||
}
|
||||
|
||||
function setLit(button, level) {
|
||||
if (Number.isInteger(level) && level >= 0) button.dataset.lit = String(level);
|
||||
else delete button.dataset.lit;
|
||||
}
|
||||
|
||||
function key(event, row) {
|
||||
if ((event.key === 'ContextMenu') || (event.shiftKey && event.key === 'F10')) {
|
||||
event.preventDefault();
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "lucisv",
|
||||
"version": "0.64.0",
|
||||
"version": "0.65.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "lucisv",
|
||||
"version": "0.64.0",
|
||||
"version": "0.65.4",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "9.0.1"
|
||||
|
||||
+207
-1
@@ -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.64.0",
|
||||
"version": "0.65.4",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -193,15 +193,121 @@
|
||||
"configurationDefaults": {
|
||||
"[verilog]": {
|
||||
"editor.defaultColorDecorators": "never",
|
||||
"editor.semanticHighlighting.enabled": true,
|
||||
"editor.stickyScroll.defaultModel": "foldingProviderModel",
|
||||
"editor.stickyScroll.maxLineCount": 10
|
||||
},
|
||||
"[systemverilog]": {
|
||||
"editor.defaultColorDecorators": "never",
|
||||
"editor.semanticHighlighting.enabled": true,
|
||||
"editor.stickyScroll.defaultModel": "foldingProviderModel",
|
||||
"editor.stickyScroll.maxLineCount": 10
|
||||
}
|
||||
},
|
||||
"semanticTokenScopes": [
|
||||
{
|
||||
"language": "verilog",
|
||||
"scopes": {
|
||||
"namespace": [
|
||||
"entity.name.namespace",
|
||||
"entity.name.type.namespace",
|
||||
"entity.name.type"
|
||||
],
|
||||
"class": [
|
||||
"entity.name.type.class",
|
||||
"entity.name.type",
|
||||
"support.class"
|
||||
],
|
||||
"type": [
|
||||
"entity.name.type",
|
||||
"support.type"
|
||||
],
|
||||
"enumMember": [
|
||||
"variable.other.enummember",
|
||||
"variable.other.constant",
|
||||
"constant.other"
|
||||
],
|
||||
"parameter": [
|
||||
"keyword.control",
|
||||
"constant.language",
|
||||
"variable.parameter"
|
||||
],
|
||||
"variable": [
|
||||
"support.variable",
|
||||
"entity.other.attribute-name",
|
||||
"variable.other.readwrite"
|
||||
],
|
||||
"property": [
|
||||
"entity.name.tag.css",
|
||||
"entity.other.attribute-name",
|
||||
"variable.other.property"
|
||||
],
|
||||
"function": [
|
||||
"entity.name.function",
|
||||
"support.function"
|
||||
],
|
||||
"macro": [
|
||||
"entity.name.function.preprocessor",
|
||||
"meta.preprocessor"
|
||||
],
|
||||
"decorator": [
|
||||
"entity.name.function.decorator",
|
||||
"meta.attribute"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"language": "systemverilog",
|
||||
"scopes": {
|
||||
"namespace": [
|
||||
"entity.name.namespace",
|
||||
"entity.name.type.namespace",
|
||||
"entity.name.type"
|
||||
],
|
||||
"class": [
|
||||
"entity.name.type.class",
|
||||
"entity.name.type",
|
||||
"support.class"
|
||||
],
|
||||
"type": [
|
||||
"entity.name.type",
|
||||
"support.type"
|
||||
],
|
||||
"enumMember": [
|
||||
"variable.other.enummember",
|
||||
"variable.other.constant",
|
||||
"constant.other"
|
||||
],
|
||||
"parameter": [
|
||||
"keyword.control",
|
||||
"constant.language",
|
||||
"variable.parameter"
|
||||
],
|
||||
"variable": [
|
||||
"support.variable",
|
||||
"entity.other.attribute-name",
|
||||
"variable.other.readwrite"
|
||||
],
|
||||
"property": [
|
||||
"entity.name.tag.css",
|
||||
"entity.other.attribute-name",
|
||||
"variable.other.property"
|
||||
],
|
||||
"function": [
|
||||
"entity.name.function",
|
||||
"support.function"
|
||||
],
|
||||
"macro": [
|
||||
"entity.name.function.preprocessor",
|
||||
"meta.preprocessor"
|
||||
],
|
||||
"decorator": [
|
||||
"entity.name.function.decorator",
|
||||
"meta.attribute"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"languages": [
|
||||
{
|
||||
"id": "verilog",
|
||||
@@ -320,6 +426,76 @@
|
||||
"highContrast": "#FF1212",
|
||||
"highContrastLight": "#A80000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyCurrent",
|
||||
"description": "Hierarchy pane: background of a row whose module is declared in the active file.",
|
||||
"defaults": {
|
||||
"dark": "#FFB34745",
|
||||
"light": "#FFC26661",
|
||||
"highContrast": "#FFB34780",
|
||||
"highContrastLight": "#FF8C0099"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyParent1",
|
||||
"description": "Hierarchy pane: background of the row one level above the active file's row.",
|
||||
"defaults": {
|
||||
"dark": "#FFB34730",
|
||||
"light": "#FFC2664F",
|
||||
"highContrast": "#FFB34761",
|
||||
"highContrastLight": "#FF8C0073"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyParent2",
|
||||
"description": "Hierarchy pane: background of the row two levels above the active file's row.",
|
||||
"defaults": {
|
||||
"dark": "#FFB34721",
|
||||
"light": "#FFC2663B",
|
||||
"highContrast": "#FFB34745",
|
||||
"highContrastLight": "#FF8C0052"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyParent3",
|
||||
"description": "Hierarchy pane: background of the row three levels above the active file's row.",
|
||||
"defaults": {
|
||||
"dark": "#FFB34716",
|
||||
"light": "#FFC26629",
|
||||
"highContrast": "#FFB3472B",
|
||||
"highContrastLight": "#FF8C0033"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyAncestor",
|
||||
"description": "Hierarchy pane: background of every row four or more levels above the active file's row (the floor, still distinct from an unlit row).",
|
||||
"defaults": {
|
||||
"dark": "#FFB3470D",
|
||||
"light": "#FFC26615",
|
||||
"highContrast": "#FFB34717",
|
||||
"highContrastLight": "#FF8C001A"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lucisv.hierarchyCurrentBar",
|
||||
"description": "Hierarchy pane: the bar at the left edge of a lit row — solid and widest on the active file's row, narrower and fainter each level up.",
|
||||
"defaults": {
|
||||
"dark": "#FFB347",
|
||||
"light": "#C86400",
|
||||
"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": {
|
||||
@@ -368,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": {
|
||||
@@ -377,6 +577,12 @@
|
||||
"scope": "window",
|
||||
"markdownDescription": "Modules the Hierarchy pane treats as DUTs, by name. Each one splits the pane into two more sections — the DUT with its children, and an upward tree of everything that instantiates it — ahead of the \"Other modules\" section. This is the checked-in list a team shares (`.vscode/settings.json`); starring from the pane's own menu is the per-workspace way and the two are shown together. A DUT that comes from this setting is shown locked and cannot be unstarred from the pane."
|
||||
},
|
||||
"lucisv.hierarchy.highlightCurrent": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"scope": "window",
|
||||
"markdownDescription": "Light the Hierarchy pane's rows that lead to the active file: the row whose module the file declares in a bright orange with a solid bar at its edge, each row above it one shade dimmer, down to a faint floor. Every instance of the module is lit, with its whole path. The shades are the `lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor` and `lucisv.hierarchyCurrentBar` theme colours, which `workbench.colorCustomizations` can override."
|
||||
},
|
||||
"lucisv.format.uvmUtilsIndent": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Checks for the VS Code semantic-highlighting manifest contract:
|
||||
// `configurationDefaults` enables semantic highlighting for both language ids,
|
||||
// `semanticTokenScopes` covers both language ids identically, every mapped key
|
||||
// exists in `crates/lucisv_server/src/tokens.rs`'s legend, and the five module
|
||||
// instantiation roles map to distinct primary TextMate scopes.
|
||||
//
|
||||
// node semanticTokens_test.js
|
||||
//
|
||||
// See docs/features/instantiation-highlighting/README.md.
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let checks = 0;
|
||||
|
||||
function fail(what) {
|
||||
console.error(`semanticTokens_test: FAIL — ${what}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function ok(condition, what) {
|
||||
checks += 1;
|
||||
if (!condition) fail(what);
|
||||
}
|
||||
|
||||
const manifestPath = path.join(__dirname, 'package.json');
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
const vscodeignore = fs.readFileSync(path.join(__dirname, '.vscodeignore'), 'utf8');
|
||||
const tokensRust = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'crates', 'lucisv_server', 'src', 'tokens.rs'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// 1. `.vscodeignore` keeps this test out of packaged `.vsix` archives.
|
||||
ok(
|
||||
vscodeignore.split(/\r?\n/).includes('semanticTokens_test.js'),
|
||||
'semanticTokens_test.js is listed in .vscodeignore',
|
||||
);
|
||||
|
||||
// 2. Both language ids turn semantic highlighting on by default so themes with
|
||||
// `semanticHighlighting: false` or unset still render server tokens.
|
||||
const defaults = manifest.contributes.configurationDefaults;
|
||||
ok(defaults && typeof defaults === 'object', 'configurationDefaults exists');
|
||||
for (const lang of ['[verilog]', '[systemverilog]']) {
|
||||
ok(
|
||||
defaults[lang] && defaults[lang]['editor.semanticHighlighting.enabled'] === true,
|
||||
`${lang} sets editor.semanticHighlighting.enabled = true`,
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Extract the advertised legend names from `tokens.rs::token_types()`.
|
||||
const legendMap = {
|
||||
NAMESPACE: 'namespace',
|
||||
CLASS: 'class',
|
||||
TYPE: 'type',
|
||||
ENUM_MEMBER: 'enumMember',
|
||||
PARAMETER: 'parameter',
|
||||
VARIABLE: 'variable',
|
||||
PROPERTY: 'property',
|
||||
FUNCTION: 'function',
|
||||
MACRO: 'macro',
|
||||
KEYWORD: 'keyword',
|
||||
COMMENT: 'comment',
|
||||
STRING: 'string',
|
||||
NUMBER: 'number',
|
||||
DECORATOR: 'decorator',
|
||||
};
|
||||
const fnBody = tokensRust.split('pub fn token_types()')[1].split('}')[0];
|
||||
const advertised = [...fnBody.matchAll(/SemanticTokenType::([A-Z_]+)/g)].map(([, id]) => {
|
||||
ok(legendMap[id], `known SemanticTokenType::${id}`);
|
||||
return legendMap[id];
|
||||
});
|
||||
ok(advertised.length === 14, `legend stays at 14 types, got ${advertised.length}`);
|
||||
|
||||
// 4. `semanticTokenScopes` is registered identically for `verilog` and `systemverilog`,
|
||||
// and every key is in the server's advertised legend.
|
||||
const entries = manifest.contributes.semanticTokenScopes;
|
||||
ok(Array.isArray(entries) && entries.length === 2, 'two semanticTokenScopes entries');
|
||||
ok(entries[0].language === 'verilog', 'first entry is verilog');
|
||||
ok(entries[1].language === 'systemverilog', 'second entry is systemverilog');
|
||||
ok(
|
||||
JSON.stringify(entries[0].scopes) === JSON.stringify(entries[1].scopes),
|
||||
'verilog and systemverilog share identical semanticTokenScopes',
|
||||
);
|
||||
|
||||
const scopes = entries[0].scopes;
|
||||
for (const [tokenType, chain] of Object.entries(scopes)) {
|
||||
ok(advertised.includes(tokenType), `${tokenType} is in tokens::token_types()`);
|
||||
ok(Array.isArray(chain) && chain.length > 0, `${tokenType} has a non-empty scope fallback chain`);
|
||||
for (const scope of chain) {
|
||||
ok(typeof scope === 'string' && scope.length > 0, `${tokenType} scope is non-empty string`);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. All five module-instantiation roles map to pairwise-distinct primary scopes.
|
||||
const instantiationRoles = ['class', 'parameter', 'function', 'property', 'variable'];
|
||||
const primaryScopes = instantiationRoles.map((role) => {
|
||||
ok(Array.isArray(scopes[role]) && scopes[role].length > 0, `${role} is mapped`);
|
||||
return scopes[role][0];
|
||||
});
|
||||
ok(
|
||||
new Set(primaryScopes).size === instantiationRoles.length,
|
||||
`instantiation roles have distinct primary scopes: ${primaryScopes.join(', ')}`,
|
||||
);
|
||||
|
||||
console.log(`semanticTokens_test: ${checks} checks passed`);
|
||||
+11
-5
@@ -222,8 +222,9 @@ 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`,
|
||||
`referencesView.js`, `referencesModel.js`): an extension that ships without
|
||||
one fails to activate. Check that after any change to it:
|
||||
`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-<version>.vsix | grep -E 'smoke|_test'` must print
|
||||
nothing, `unzip -l dist/lucisv-<version>.vsix | grep -E 'restart.js|mcp.js|references(View|Model).js'`
|
||||
must print `extension/restart.js`, `extension/mcp.js`,
|
||||
@@ -320,7 +321,10 @@ git tag v<X.Y.Z>
|
||||
git push origin v<X.Y.Z>
|
||||
```
|
||||
|
||||
does the rest on the `mac-arm64` runner: `tools/release.sh --cross`, a
|
||||
does the rest on the `lustudio-arm64` runner: first `tools/gates.sh`, the
|
||||
whole of step 3 — a red gate stops the release before anything is built
|
||||
(since 0.65.1; 0.65.0 was published while its checks had not finished) —
|
||||
then `tools/release.sh --cross`, a
|
||||
tag-vs-`lucisv --version` consistency check,
|
||||
`tools/prune_release_assets.sh dist <version>`, which keeps **only the
|
||||
seven `.vsix` packages** in `dist/` (each checked by name — a missing
|
||||
@@ -333,8 +337,10 @@ from them — but never published: a standalone binary is a
|
||||
`cargo build --release` away for whoever wants one. Ordinary pushes run
|
||||
fmt/clippy/test via `.gitea/workflows/ci.yml`.
|
||||
|
||||
The runner is this Mac: `brew install gitea-runner`, registered
|
||||
instance-wide as `mac-arm64` (labels `macos-arm64`/`self-hosted`, host
|
||||
The runner is the Mac Studio (since 2026-11-19; `mac-arm64`, on the
|
||||
previous build Mac, was retired the same day): the one-time setup at the
|
||||
top of this file, then `brew install gitea-runner`, registered
|
||||
instance-wide as `lustudio-arm64` (labels `macos-arm64`/`self-hosted`, host
|
||||
mode), running via `brew services start gitea-runner`; config at
|
||||
`/opt/homebrew/etc/gitea-runner/config.yaml`, logs at
|
||||
`/opt/homebrew/var/log/gitea-runner.{log,err}`. Registration tokens are
|
||||
|
||||
Reference in new issue
Block a user