diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c85b45..4f08ff8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,39 @@ 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.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 diff --git a/Cargo.lock b/Cargo.lock index ac89028..34d30f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.1" +version = "0.65.2" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.1" +version = "0.65.2" [[package]] name = "lucisv_mcp" -version = "0.65.1" +version = "0.65.2" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.1" +version = "0.65.2" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.1" +version = "0.65.2" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.1" +version = "0.65.2" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.1" +version = "0.65.2" [[package]] name = "vlog_refactor" -version = "0.65.1" +version = "0.65.2" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.1" +version = "0.65.2" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 66d6257..21071e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.1" +version = "0.65.2" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/docs/features/hierarchy-current-path/README.md b/docs/features/hierarchy-current-path/README.md new file mode 100644 index 0000000..2818145 --- /dev/null +++ b/docs/features/hierarchy-current-path/README.md @@ -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 " (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` 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-.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. diff --git a/editors/vscode/.vscodeignore b/editors/vscode/.vscodeignore index 8d596bc..896bb14 100644 --- a/editors/vscode/.vscodeignore +++ b/editors/vscode/.vscodeignore @@ -6,6 +6,8 @@ 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 diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 745500d..2199276 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,18 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.65.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 diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 8b760d3..039e8fd 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.65.1**. Its platform packages include +The current release is **0.65.2**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -159,6 +159,7 @@ enabling both paths formats twice. | 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 | @@ -327,6 +328,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 +423,13 @@ Every nesting color is a proper VS Code theme color: } ``` +## 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 diff --git a/editors/vscode/hierarchyCurrent.js b/editors/vscode/hierarchyCurrent.js new file mode 100644 index 0000000..29f74fd --- /dev/null +++ b/editors/vscode/hierarchyCurrent.js @@ -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, +}; diff --git a/editors/vscode/hierarchyCurrent_test.js b/editors/vscode/hierarchyCurrent_test.js new file mode 100644 index 0000000..f832ef9 --- /dev/null +++ b/editors/vscode/hierarchyCurrent_test.js @@ -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:///.sv`), instance names `u_` (`u__` 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`); diff --git a/editors/vscode/hierarchyPalette_test.js b/editors/vscode/hierarchyPalette_test.js new file mode 100644 index 0000000..810447b --- /dev/null +++ b/editors/vscode/hierarchyPalette_test.js @@ -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`); diff --git a/editors/vscode/hierarchySections.js b/editors/vscode/hierarchySections.js index ad72c2f..c06dbd8 100644 --- a/editors/vscode/hierarchySections.js +++ b/editors/vscode/hierarchySections.js @@ -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, diff --git a/editors/vscode/hierarchyView.js b/editors/vscode/hierarchyView.js index 27e1f5d..c3807b7 100644 --- a/editors/vscode/hierarchyView.js +++ b/editors/vscode/hierarchyView.js @@ -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) { diff --git a/editors/vscode/hierarchyView_test.js b/editors/vscode/hierarchyView_test.js index f336bf4..302597d 100644 --- a/editors/vscode/hierarchyView_test.js +++ b/editors/vscode/hierarchyView_test.js @@ -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 diff --git a/editors/vscode/media/hierarchy.css b/editors/vscode/media/hierarchy.css index 43228b0..ed0d1b5 100644 --- a/editors/vscode/media/hierarchy.css +++ b/editors/vscode/media/hierarchy.css @@ -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; } +} diff --git a/editors/vscode/media/hierarchy.js b/editors/vscode/media/hierarchy.js index 59797b3..2ef60e5 100644 --- a/editors/vscode/media/hierarchy.js +++ b/editors/vscode/media/hierarchy.js @@ -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(); diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index eea31f5..12ab8ed 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.1", + "version": "0.65.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.1", + "version": "0.65.2", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 2c79295..fdcc795 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.65.1", + "version": "0.65.2", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT", @@ -426,6 +426,66 @@ "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" + } } ], "configuration": { @@ -483,6 +543,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, diff --git a/tools/RELEASING.md b/tools/RELEASING.md index dbc7a83..e009984 100644 --- a/tools/RELEASING.md +++ b/tools/RELEASING.md @@ -222,8 +222,8 @@ npx @vscode/vsce package --target darwin-arm64 \ where the platform packages' binaries are staged — nor any module `extension.js` requires at runtime (`restart.js`, `mcp.js`, `extract.js`, `hierarchyView.js`, `hierarchyModel.js`, `hierarchySections.js`, - `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`): an + extension that ships without one fails to activate. Check that after any change to it: `unzip -l dist/lucisv-.vsix | grep -E 'smoke|_test'` must print nothing, `unzip -l dist/lucisv-.vsix | grep -E 'restart.js|mcp.js|references(View|Model).js'` must print `extension/restart.js`, `extension/mcp.js`,