VS Code: Find All References with whole source lines (lucisv References view)
VS Code's built-in references pane cuts each preview to ~8 characters before the match. lucisv.references.show runs the same reference and definition providers and fills a tree view in the lucisv sidebar: one row per file (current file first), one row per reference with the trimmed full line and the identifier highlighted, the declaration marked; a click selects the exact range. The setting lucisv.references.fullLineView (default true) binds Shift+Alt+F12 to it in verilog/systemverilog editors only; Shift+F12 peek is untouched. Closed files are read with workspace.fs, so no didOpen reaches the server. QA (Sonnet): PASS with 4 lows (recorded). Node tests 8/8. tools/RELEASING.md must-ship list names every runtime module (lane handshake). docs/features/vscode-references-view. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
41a90917bb
commit
5e4af0be3d
11 files changed
+1170
-8
No files matched your search
@@ -0,0 +1,223 @@
|
||||
# vscode-references-view
|
||||
|
||||
## Goal
|
||||
|
||||
The user's report: "the find all references highlight doesn't show the full
|
||||
line in the references pane." The server's `textDocument/references` ranges are
|
||||
exact — each covers just the identifier (lead, verified at the LSP level). The
|
||||
truncation is VS Code's: its References view and peek build each preview from
|
||||
about eight characters before the match to the end of the line, so
|
||||
`always_ff @(posedge clk) r <= ~r;` reads `clk) r <= ~r;`. The server cannot
|
||||
change that, so the fix is in the extension: a lucisv **References** view
|
||||
that shows every reference's **whole line** with the identifier highlighted,
|
||||
grouped by file, and takes over Find All References (`Shift+Alt+F12`) in
|
||||
Verilog/SystemVerilog editors behind a setting.
|
||||
|
||||
### Design
|
||||
|
||||
- **Where the view goes:** a `TreeView` (`lucisv.references`) in the existing
|
||||
`lucisv` activity-bar container, under Hierarchy. The built-in References
|
||||
view also lives in the sidebar, so the user finds the answer where they
|
||||
already look for it; a second container (or the bottom panel) would be one
|
||||
more place for one view. The view is hidden (`when:
|
||||
lucisv.references.hasResults`) until the first search fills it, the way the
|
||||
built-in one is, so the Hierarchy sidebar is unchanged for anyone who never
|
||||
uses it. A **Clear** title action empties and hides it again.
|
||||
- **Rows:** one per file — the workspace-relative path
|
||||
(`workspace.asRelativePath`), the reference count as the description, the
|
||||
file icon — expanded; the current file first, then by path. Under it one row
|
||||
per reference in line order: the whole line trimmed, the identifier
|
||||
highlighted (`TreeItemLabel.highlights`), `line N` as the description, and
|
||||
`path:line:col` as the tooltip. The declaration — the reference that starts
|
||||
where a definition-provider answer does — gets the `symbol-key` icon and
|
||||
`declaration · line N`. A click runs `vscode.open` with the exact reference
|
||||
range as `selection`.
|
||||
- **Title:** `References: <name> (N in K files)`; an empty answer leaves
|
||||
`References: <name>` with the message `No references to <name>.`
|
||||
- **Command:** `lucisv.references.show`, "Find All References (full lines)",
|
||||
in the editor context menu and the command palette for verilog/systemverilog
|
||||
only. It runs `vscode.executeReferenceProvider` and
|
||||
`vscode.executeDefinitionProvider` at the cursor (VS Code's own provider
|
||||
commands, so the answer is exactly what the built-in view gets — the
|
||||
extension adds no request of its own), reads the lines, fills the view and
|
||||
reveals it (`setContext`, then `lucisv.references.focus`).
|
||||
- **Setting and keybinding:** `lucisv.references.fullLineView` (boolean,
|
||||
default `true`). A contributed keybinding binds `shift+alt+f12` (no `mac`
|
||||
override: macOS uses the same chord) to the command with
|
||||
`when: editorTextFocus && editorHasReferenceProvider &&
|
||||
config.lucisv.references.fullLineView && editorLangId =~ /^(system)?verilog$/`.
|
||||
When the setting is off, or the editor is any other language, the clause is
|
||||
false and the key resolves to whatever VS Code would have run — the built-in
|
||||
command is never unbound. `Shift+F12` (peek) is not touched.
|
||||
- **Reading lines:** an open document is read from its buffer (unsaved edits
|
||||
are what the server answered against); a closed file through
|
||||
`workspace.fs.readFile`, decoded as UTF-8, **not** `openTextDocument`. That
|
||||
is a deliberate deviation from the brief's "whichever the extension already
|
||||
uses" (Hierarchy uses `openTextDocument`, for one file it is about to show):
|
||||
`openTextDocument` on a closed Verilog file makes the language client send
|
||||
the server a `didOpen`, so a 500-reference answer across 100 files would open
|
||||
100 documents on the server and fill Problems with their diagnostics just to
|
||||
draw preview lines. Every file is read once, in parallel; a file that cannot
|
||||
be read still lists its references, labelled `line N`.
|
||||
- **Modules:** `referencesModel.js` is pure (no `vscode`): grouping, ordering,
|
||||
trimming, highlight offsets, the declaration mark, the title.
|
||||
`referencesView.js` is the TreeView, the commands and the line reader.
|
||||
`extension.js` gains two lines.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `vscode.executeReferenceProvider` asks providers with `includeDeclaration:
|
||||
true`, as VS Code's own Find All References does, so the declaration is in
|
||||
the list for the mark to find. Not enforced here; if it ever is not, no row
|
||||
is marked and nothing else changes.
|
||||
- An extension-contributed keybinding with a matching `when` clause wins over
|
||||
VS Code's default `shift+alt+f12` binding (including the built-in
|
||||
references-view extension's `references-view.findReferences`): user
|
||||
extensions' keybinding contributions are registered after the defaults and
|
||||
built-in extensions'. Not verifiable headless.
|
||||
- `editorLangId =~ /…/` regex `when` clauses are supported (they are since well
|
||||
before the extension's `engines.vscode` floor, 1.82).
|
||||
- The `<viewId>.focus` command VS Code generates for every contributed view
|
||||
reveals a view that was hidden by its `when` clause once the context key is
|
||||
set — the built-in references view does the same (`setContext`, then focus).
|
||||
- Closed files are UTF-8 (or ASCII). A Latin-1 byte decodes to U+FFFD, one
|
||||
UTF-16 unit for one byte, so offsets on such a line still line up; only that
|
||||
character's glyph is wrong in the preview.
|
||||
- A tab is shown as one space, so a highlight offset never moves; the preview
|
||||
is not column-aligned and does not need to be.
|
||||
- A line longer than 240 characters after trimming is cut to a 240-character
|
||||
window that keeps 60 characters before the match, with `…` marking each cut —
|
||||
so a generated netlist line cannot become a 100 000-character label.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes from VS Code:** `vscode.executeReferenceProvider`,
|
||||
`vscode.executeDefinitionProvider` (Location or LocationLink answers — a
|
||||
link is matched by `targetSelectionRange`, then `targetRange`),
|
||||
`vscode.open`, `setContext`, the generated `lucisv.references.focus`,
|
||||
`window.createTreeView`, `workspace.fs.readFile`,
|
||||
`workspace.textDocuments`, `workspace.asRelativePath`.
|
||||
- **Consumes from the server:** nothing new. The answers are the server's
|
||||
`textDocument/references` and `textDocument/definition`, through the
|
||||
language client's providers. No server change; the other lane's
|
||||
`crates/lucisv_server/**` is untouched.
|
||||
- **Promises:** a contributed view `lucisv.references` in the `lucisv`
|
||||
container, commands `lucisv.references.show` / `lucisv.references.clear`,
|
||||
context key `lucisv.references.hasResults`, setting
|
||||
`lucisv.references.fullLineView`.
|
||||
- **Request (release docs, not owned by this lane):** `tools/RELEASING.md`'s
|
||||
vsix-content check lists `restart.js` and `mcp.js` as the runtime files that
|
||||
must ship; it should also name `referencesModel.js` and `referencesView.js`
|
||||
(and, while it is there, the `hierarchy*.js` modules and `extract.js`, which
|
||||
it already omits). `tools/release.sh` asserts no JavaScript file list — only
|
||||
`bin/` contents — so it needs no change. In this lane the shipping is pinned
|
||||
by `referencesView_test.js::theRuntimeFilesShip` (reads `.vscodeignore`)
|
||||
and was confirmed with `vsce ls` (see the work log).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `referencesModel.js`: groups, order, trim/tab/CRLF offsets, multi-line
|
||||
and clamped ranges, over-long lines, declaration mark, title.
|
||||
- [x] `referencesView.js`: TreeView, show/clear commands, stale-answer guard,
|
||||
buffer-or-disk line reader.
|
||||
- [x] `package.json`: view, commands, context menu, palette, title action,
|
||||
keybinding, setting.
|
||||
- [x] `.vscodeignore`: the two new tests excluded; runtime files ship.
|
||||
- [x] `extension.js` wiring (two lines).
|
||||
- [x] `editors/vscode/README.md` (feature row + setting) and `CHANGELOG.md`
|
||||
(Unreleased).
|
||||
- [x] Headless tests: `referencesModel_test.js`, `referencesView_test.js`.
|
||||
- [ ] Manual check in a real VS Code: keybinding precedence over the built-in,
|
||||
reveal of the `when`-hidden view, highlight rendering (QA / lead).
|
||||
|
||||
## Work log
|
||||
|
||||
- 2026-10-14 (dev): Read the extension, the hierarchy view/model/tests and
|
||||
the hierarchy-sidebar README. Chose a native `TreeView` over another webview
|
||||
— `TreeItemLabel.highlights` is exactly "highlight a span of a label", and a
|
||||
tree gets keyboard navigation, collapse-all and theming for free; the
|
||||
hierarchy needed a webview only for its persistent search field. Put the
|
||||
view in the existing `lucisv` container, hidden until filled. Read closed
|
||||
files with `workspace.fs` rather than `openTextDocument` (reason in Design).
|
||||
Declaration mark: exact start match against the definition answer, with a
|
||||
containment fallback used only when nothing matches exactly (a provider
|
||||
whose definition range is the whole declaration). Duplicate locations are
|
||||
collapsed. A newer search wins over a slower older one (request counter).
|
||||
Tests: `node --test editors/vscode/*_test.js` under `tools/guard.sh -t 300`
|
||||
went from 6 files / 6 pass to 8 files / 8 pass. `npx --offline @vscode/vsce
|
||||
ls --no-dependencies` (cached vsce, no network) lists `referencesModel.js`
|
||||
and `referencesView.js` and none of the `*_test.js` files.
|
||||
|
||||
## QA log
|
||||
|
||||
- 2026-10-14 — QA agent (Sonnet). **Verdict: PASS with findings (all low).**
|
||||
- Suite: `tools/guard.sh -t 300 -- node --test editors/vscode/*_test.js`:
|
||||
8 files / 8 pass / 0 fail (`node --test` counts one test per file; each
|
||||
file is a single script of many assertions, so 8 is not an assertion
|
||||
count). `vsce ls --no-dependencies` (cached, offline, under the guard,
|
||||
rc 0) lists `referencesModel.js` and `referencesView.js`, no `*_test.js`.
|
||||
- Test strength: mutation-checked in a scratch copy. Deleting the
|
||||
`asked !== this.request` guard fails `aStaleAnswerDoesNotOverwriteANewerOne`;
|
||||
removing `.trim()` fails `theReportedLineIsShownWhole`. Not tautological.
|
||||
- Model attacks (scratch script, `referencesModel.js` required directly).
|
||||
Server negotiates UTF-16 (`crates/lucisv_server/src/main.rs:191`); the
|
||||
model indexes JS strings, which are UTF-16, so emoji and CJK before the
|
||||
match highlight exactly the identifier. Also clean: tabs, column 0,
|
||||
zero-length range (no highlight, line still shown), reversed ranges (same
|
||||
and cross line), negative character, empty file, reference past the last
|
||||
line (empty label, `line N` row), no trailing newline, NBSP indentation,
|
||||
5 000 references in one file (9 ms), 2 000 files (3 ms), `untitled:` and
|
||||
`file:///c%3A/...` URIs, URI objects deduped, LocationLink declaration
|
||||
mark, windowing at start, middle and end of a 2 005-char line (highlight
|
||||
always inside the window; ellipsis offsets right).
|
||||
- Manifest: language ids registered are only `verilog` and `systemverilog`
|
||||
(`package.json` contributes.languages; `extension.js:34`), so the
|
||||
`^(system)?verilog$` regex misses nothing. Setting default/description
|
||||
match `README.md:306`. Palette, view `when`, menu group fine.
|
||||
- Findings:
|
||||
1. LOW — `referencesModel.js:94`: the 240-char window can cut between the
|
||||
two halves of a surrogate pair (reproduce: `'😀'.repeat(300)+'sig'`,
|
||||
match at 600), leaving a lone surrogate (renders as a replacement
|
||||
glyph) at the edge next to the `…`. Cosmetic; highlight offsets stay
|
||||
correct.
|
||||
2. LOW — `referencesView.js:130`: every file is read whole and in
|
||||
parallel with no cap; 2 000 referenced files means 2 000 concurrent
|
||||
reads and all their text held at once until the groups are built. A
|
||||
huge generated netlist is read in full for one line. Unlikely, bounded
|
||||
by the answer, no correctness impact.
|
||||
3. LOW — `referencesView.js:141`: decoding is UTF-8 only. A BOM is
|
||||
stripped (matches VS Code's buffer, so columns agree). A UTF-16 file or
|
||||
an invalid UTF-8 sequence spanning several bytes decodes to fewer
|
||||
units than bytes, so on such a line the Assumptions' "one unit per
|
||||
byte" can be off and the highlight may shift. Latin-1 single bytes are
|
||||
fine.
|
||||
4. LOW (docs) — `tools/RELEASING.md:204-210` still names only
|
||||
`restart.js` and `mcp.js` as must-ship runtime files; the dev filed
|
||||
this as a handshake. Not touched (outside lane scope).
|
||||
- Reviewed and clean: stale-search guard covers the failure path and
|
||||
`clear()` (both bump/compare `this.request`); every disposable is in
|
||||
`context.subscriptions`; `readLines`/`fileReader` cannot reject
|
||||
(read errors caught), and the `show` command's own rejections surface as
|
||||
VS Code's command-error toast; no workspace folder makes
|
||||
`asRelativePath` return the absolute path, which is fine; no
|
||||
`openTextDocument`, so no didOpen flood.
|
||||
- Unverified (needs a real VS Code): the contributed keybinding beating the
|
||||
built-in `shift+alt+f12`; `config.lucisv.references.fullLineView`
|
||||
resolving true by default (not just when set explicitly); `.focus`
|
||||
revealing a `when`-hidden view; highlight rendering; the context menu
|
||||
showing both the built-in and this entry.
|
||||
- Fixes made by QA: none.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-10-14 — lead.** Accepted. The view is additive: a hidden tree view,
|
||||
one command, one keybinding gated on the setting and the two language ids,
|
||||
and no change to the server or the built-in commands. Reading closed files
|
||||
with `workspace.fs` rather than `openTextDocument` (no didOpen flood) is the
|
||||
right call. QA's four lows are recorded and accepted as is (the surrogate
|
||||
split is cosmetic; UTF-16/invalid-UTF-8 files are rare in RTL). The
|
||||
`tools/RELEASING.md` handshake is granted: its must-ship list now names
|
||||
every runtime module. Still to confirm in a real VS Code: the keybinding
|
||||
winning over the built-in Find All References, the hidden view revealing on
|
||||
first use, and how the highlights render.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# The checks are pre-publish/developer checks, not part of the shipped
|
||||
# extension. `restart.js` and `mcp.js` themselves ARE shipped — `extension.js`
|
||||
# requires them.
|
||||
# extension. `restart.js`, `mcp.js` and the `hierarchy*`/`references*` modules
|
||||
# themselves ARE shipped — `extension.js` requires them.
|
||||
smoke.js
|
||||
mcp_smoke.js
|
||||
mcp_test.js
|
||||
@@ -9,5 +9,7 @@ restart_test.js
|
||||
hierarchyModel_test.js
|
||||
hierarchySections_test.js
|
||||
hierarchyView_test.js
|
||||
referencesModel_test.js
|
||||
referencesView_test.js
|
||||
.vscode/**
|
||||
.gitignore
|
||||
@@ -5,6 +5,19 @@ 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).
|
||||
|
||||
## Unreleased
|
||||
|
||||
- **Find All References shows whole lines.** `Shift+Alt+F12` in a
|
||||
Verilog/SystemVerilog editor now opens lucisv's own **References** view in
|
||||
the lucisv sidebar: one group per file (the current file first), every
|
||||
reference's full source line with the identifier highlighted, the
|
||||
declaration marked, and a click that selects the reference. VS Code's own
|
||||
view starts each line a few characters before the match, so
|
||||
`always_ff @(posedge clk) r <= ~r;` read `clk) r <= ~r;`. New setting
|
||||
`lucisv.references.fullLineView` (default on) gives the key back to the
|
||||
built-in command; **lucisv: Find All References (full lines)** in the
|
||||
editor context menu works either way, and `Shift+F12` peek is unchanged.
|
||||
|
||||
## 0.60.0 — 2026-10-08
|
||||
|
||||
- **Rename a generate block label and every path through it moves.**
|
||||
|
||||
@@ -137,6 +137,7 @@ enabling both paths formats twice.
|
||||
| Go to definition | Local and cross-file symbols, macros, modules, packages, exported members, ports, and resolved `` `include`` targets |
|
||||
| Go to type definition | Values, handles, instances, interfaces, and aliases navigate to the declared type |
|
||||
| Find references | Local symbols stay local; indexed design units, package members, and ports resolve across files |
|
||||
| Full-line references view | **Find All References** (`Shift+Alt+F12`) opens lucisv's own References view in the lucisv sidebar: every reference's whole source line with the identifier highlighted, grouped by file (current file first), the declaration marked, a click selects the reference. VS Code's built-in view cuts each line to a few characters before the match; `lucisv.references.fullLineView` turns the takeover off. Also **lucisv: Find All References (full lines)** in the editor context menu |
|
||||
| Document highlights | Highlights symbol occurrences or the matching opener/closer under the cursor |
|
||||
| Document and workspace symbols | Hierarchical outline plus indexed symbol search across the design |
|
||||
| Include links | Resolvable `` `include`` paths become clickable using local and filelist `+incdir+` search rules |
|
||||
@@ -302,6 +303,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
|
||||
| Setting | Default | Purpose |
|
||||
|---|---:|---|
|
||||
| `lucisv.references.fullLineView` | `true` | `Shift+Alt+F12` in a Verilog/SystemVerilog editor opens lucisv's full-line References view instead of VS Code's, whose previews start a few characters before the match. `false` gives the key back to the built-in command; the context-menu entry works either way, and `Shift+F12` peek is never changed |
|
||||
| `lucisv.rainbowBeginEnd` | `true` | Color nested block pairs and unmatched keywords; updates immediately |
|
||||
| `lucisv.inlineTemplates` | `true` | Show context-aware structural ghost text; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
|
||||
|
||||
@@ -15,6 +15,7 @@ const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-lang
|
||||
const { createRestarter } = require('./restart');
|
||||
const { executeCommand } = require('./extract');
|
||||
const { HierarchyView } = require('./hierarchyView');
|
||||
const { ReferencesView } = require('./referencesView');
|
||||
const mcp = require('./mcp');
|
||||
|
||||
/** The single client, kept only so `deactivate` can stop it. */
|
||||
@@ -221,6 +222,9 @@ function activate(context) {
|
||||
context.subscriptions.push(client);
|
||||
|
||||
hierarchyView = new HierarchyView(context, client);
|
||||
// Find All References with whole source lines (docs/features/vscode-references-view).
|
||||
// It asks VS Code's provider commands, not the client, so it needs neither.
|
||||
new ReferencesView(context);
|
||||
|
||||
// Built before anything can ask it for a restart — the settings listener
|
||||
// below calls it, and nothing may reach that listener with this unset.
|
||||
|
||||
@@ -75,6 +75,11 @@
|
||||
"type": "webview",
|
||||
"id": "lucisv.hierarchy",
|
||||
"name": "Hierarchy"
|
||||
},
|
||||
{
|
||||
"id": "lucisv.references",
|
||||
"name": "References",
|
||||
"when": "lucisv.references.hasResults"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -111,12 +116,45 @@
|
||||
"command": "lucisv.mcp.copyConfig",
|
||||
"title": "Copy MCP server config",
|
||||
"category": "lucisv"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.references.show",
|
||||
"title": "Find All References (full lines)",
|
||||
"category": "lucisv"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.references.clear",
|
||||
"title": "Clear References",
|
||||
"category": "lucisv",
|
||||
"icon": "$(clear-all)"
|
||||
}
|
||||
],
|
||||
"keybindings": [
|
||||
{
|
||||
"command": "lucisv.references.show",
|
||||
"key": "shift+alt+f12",
|
||||
"when": "editorTextFocus && editorHasReferenceProvider && config.lucisv.references.fullLineView && editorLangId =~ /^(system)?verilog$/"
|
||||
}
|
||||
],
|
||||
"menus": {
|
||||
"commandPalette": [
|
||||
{
|
||||
"command": "lucisv.mcp.copyConfig"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.references.show",
|
||||
"when": "editorLangId =~ /^(system)?verilog$/"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.references.clear",
|
||||
"when": "lucisv.references.hasResults"
|
||||
}
|
||||
],
|
||||
"editor/context": [
|
||||
{
|
||||
"command": "lucisv.references.show",
|
||||
"when": "editorHasReferenceProvider && editorLangId =~ /^(system)?verilog$/",
|
||||
"group": "navigation@100"
|
||||
}
|
||||
],
|
||||
"view/title": [
|
||||
@@ -144,6 +182,11 @@
|
||||
"command": "lucisv.hierarchy.unstarDut",
|
||||
"when": "view == lucisv.hierarchy",
|
||||
"group": "1_duts@2"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.references.clear",
|
||||
"when": "view == lucisv.references",
|
||||
"group": "navigation@1"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -309,6 +352,11 @@
|
||||
"default": false,
|
||||
"markdownDescription": "Print how long every operation took in the lucisv output channel: one `timing:` line per request answered and per notification handled, plus the workspace scans, the index widens, the buffer flushes and any request that had to wait behind a rescan. Off by default and worth turning on only to answer \"why did that feel slow?\" — a busy session logs a line per keystroke. **Changing this restarts the language server**, because it is an argument the server is started with (`lucisv-server --verbose`), not something it can be told mid-session."
|
||||
},
|
||||
"lucisv.references.fullLineView": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"markdownDescription": "Make **Find All References** (`Shift+Alt+F12`) in Verilog/SystemVerilog editors open lucisv's References view, which shows every reference's whole source line with the identifier highlighted, instead of VS Code's own view, which cuts each line to a few characters before the match. Off leaves the built-in command on the key. **lucisv: Find All References (full lines)** in the editor context menu works either way, and `Shift+F12` peek is never changed."
|
||||
},
|
||||
"lucisv.rainbowBeginEnd": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// What the lucisv References view shows, as plain data: the server's reference
|
||||
// locations grouped by file, each with its whole source line and the
|
||||
// identifier's offsets inside it (docs/features/vscode-references-view).
|
||||
//
|
||||
// Nothing here touches `vscode`. Locations are read only through `.uri`
|
||||
// (stringified) and `.range.{start,end}.{line,character}`, so both VS Code's
|
||||
// own objects and plain test fixtures fit.
|
||||
|
||||
/**
|
||||
* The longest preview line kept whole. A longer one — a generated netlist, a
|
||||
* minified table — is cut to a window this wide around the match, so that one
|
||||
* pathological line cannot make a label of 100 000 characters.
|
||||
*/
|
||||
const MAX_PREVIEW = 240;
|
||||
|
||||
/** How much of the line before the match a cut window keeps. */
|
||||
const LEAD_CONTEXT = 60;
|
||||
|
||||
/** A document's lines the way VS Code counts them: `\r\n`, `\r` and `\n` all end one. */
|
||||
function linesOf(text) {
|
||||
return text.split(/\r\n|\r|\n/);
|
||||
}
|
||||
|
||||
/**
|
||||
* Group `locations` by file for the view.
|
||||
*
|
||||
* - `definitions`: what the definition provider answered — `Location`s or
|
||||
* `LocationLink`s — used only to mark which reference is the declaration.
|
||||
* - `currentUri`: the file the search started from; its group comes first.
|
||||
* - `lineText(uriKey, line)`: the 0-based line's text, or `undefined` when the
|
||||
* file could not be read.
|
||||
* - `relativePath(uri)`: the label for a file's group.
|
||||
*/
|
||||
function buildReferenceGroups({ locations, definitions = [], currentUri, lineText, relativePath }) {
|
||||
const unique = dedupe(Array.isArray(locations) ? locations.filter(isLocation) : []);
|
||||
const declarations = declarationsAmong(unique, definitionTargets(definitions));
|
||||
const byFile = new Map();
|
||||
for (const location of unique) {
|
||||
const key = String(location.uri);
|
||||
if (!byFile.has(key)) byFile.set(key, []);
|
||||
byFile.get(key).push(location);
|
||||
}
|
||||
const current = currentUri === undefined ? undefined : String(currentUri);
|
||||
const groups = [...byFile].map(([key, members]) => {
|
||||
members.sort((a, b) => comparePositions(a.range.start, b.range.start));
|
||||
return {
|
||||
uri: members[0].uri,
|
||||
key,
|
||||
path: relativePath(members[0].uri),
|
||||
count: members.length,
|
||||
items: members.map((location) => referenceItem(location, lineText(key, location.range.start.line), declarations.has(location))),
|
||||
};
|
||||
});
|
||||
return groups.sort((a, b) => compareGroups(a, b, current));
|
||||
}
|
||||
|
||||
/** One reference row: its trimmed line, the highlight inside it, and where it is. */
|
||||
function referenceItem(location, rawLine, declaration) {
|
||||
const preview = previewLine(rawLine, location.range);
|
||||
return {
|
||||
location,
|
||||
line: location.range.start.line + 1,
|
||||
character: location.range.start.character + 1,
|
||||
text: preview.text,
|
||||
highlights: preview.highlights,
|
||||
declaration,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The line as the view shows it — tabs as single spaces (one for one, so no
|
||||
* offset moves), surrounding whitespace trimmed — and the identifier's span in
|
||||
* that text. A range running onto later lines is highlighted to the end of its
|
||||
* first one; a range past the end of the line is clamped to it.
|
||||
*/
|
||||
function previewLine(rawLine, range) {
|
||||
if (typeof rawLine !== 'string') return { text: '', highlights: [] };
|
||||
const line = rawLine.replace(/\t/g, ' ');
|
||||
const start = clamp(range.start.character, 0, line.length);
|
||||
const end = range.end.line > range.start.line ? line.length : clamp(range.end.character, start, line.length);
|
||||
const trimmed = line.trim();
|
||||
const lead = line.length - line.trimStart().length;
|
||||
const from = clamp(start - lead, 0, trimmed.length);
|
||||
const to = clamp(end - lead, from, trimmed.length);
|
||||
return windowed(trimmed, from, to);
|
||||
}
|
||||
|
||||
/** Cut an over-long preview to `MAX_PREVIEW` characters around `[from, to)`, marking the cuts with `…`. */
|
||||
function windowed(text, from, to) {
|
||||
if (text.length <= MAX_PREVIEW) return { text, highlights: to > from ? [[from, to]] : [] };
|
||||
const begin = clamp(from - LEAD_CONTEXT, 0, text.length - MAX_PREVIEW);
|
||||
const finish = begin + MAX_PREVIEW;
|
||||
const prefix = begin > 0 ? '…' : '';
|
||||
const body = `${prefix}${text.slice(begin, finish)}${finish < text.length ? '…' : ''}`;
|
||||
const shift = prefix.length - begin;
|
||||
const start = from + shift;
|
||||
const end = Math.min(to, finish) + shift;
|
||||
return { text: body, highlights: end > start ? [[start, end]] : [] };
|
||||
}
|
||||
|
||||
/** `References: name (N in K files)` — the view's title for a filled answer. */
|
||||
function referencesTitle(name, groups) {
|
||||
const total = groups.reduce((sum, group) => sum + group.count, 0);
|
||||
const files = groups.length === 1 ? '1 file' : `${groups.length} files`;
|
||||
return `References: ${name} (${total} in ${files})`;
|
||||
}
|
||||
|
||||
/** The definition answer as `{ key, range }` targets; a `LocationLink` names its identifier by `targetSelectionRange`. */
|
||||
function definitionTargets(definitions) {
|
||||
const list = Array.isArray(definitions) ? definitions : definitions ? [definitions] : [];
|
||||
const targets = [];
|
||||
for (const definition of list) {
|
||||
if (!definition) continue;
|
||||
if (definition.targetUri !== undefined) {
|
||||
const range = definition.targetSelectionRange || definition.targetRange;
|
||||
if (isRange(range)) targets.push({ key: String(definition.targetUri), range });
|
||||
} else if (isLocation(definition)) {
|
||||
targets.push({ key: String(definition.uri), range: definition.range });
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/**
|
||||
* The references that are the declaration. A reference starting exactly where
|
||||
* a definition does is one; only if none does, a reference inside a
|
||||
* definition's range is — for a provider whose range is the whole declaration
|
||||
* rather than its name.
|
||||
*/
|
||||
function declarationsAmong(locations, targets) {
|
||||
const starts = new Set(targets.map((target) => positionKey(target.key, target.range.start)));
|
||||
const exact = locations.filter((location) => starts.has(positionKey(String(location.uri), location.range.start)));
|
||||
if (exact.length > 0 || targets.length === 0) return new Set(exact);
|
||||
return new Set(locations.filter((location) => targets.some((target) =>
|
||||
target.key === String(location.uri) && contains(target.range, location.range.start))));
|
||||
}
|
||||
|
||||
/** The same location twice is one reference. */
|
||||
function dedupe(locations) {
|
||||
const seen = new Set();
|
||||
return locations.filter((location) => {
|
||||
const { start, end } = location.range;
|
||||
const key = `${positionKey(String(location.uri), start)}-${end.line}:${end.character}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** The current file first, then by path, then by URI for a deterministic tie-break. */
|
||||
function compareGroups(a, b, current) {
|
||||
if ((a.key === current) !== (b.key === current)) return a.key === current ? -1 : 1;
|
||||
return compareStrings(a.path, b.path) || compareStrings(a.key, b.key);
|
||||
}
|
||||
|
||||
function compareStrings(a, b) {
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}
|
||||
|
||||
function comparePositions(a, b) {
|
||||
return a.line - b.line || a.character - b.character;
|
||||
}
|
||||
|
||||
function contains(range, position) {
|
||||
return comparePositions(range.start, position) <= 0 && comparePositions(position, range.end) <= 0;
|
||||
}
|
||||
|
||||
function positionKey(key, position) {
|
||||
return `${key}#${position.line}:${position.character}`;
|
||||
}
|
||||
|
||||
function clamp(value, low, high) {
|
||||
return Math.max(low, Math.min(high, Number.isFinite(value) ? value : low));
|
||||
}
|
||||
|
||||
function isPosition(value) {
|
||||
return Boolean(value) && Number.isInteger(value.line) && Number.isInteger(value.character);
|
||||
}
|
||||
|
||||
function isRange(value) {
|
||||
return Boolean(value) && isPosition(value.start) && isPosition(value.end);
|
||||
}
|
||||
|
||||
function isLocation(value) {
|
||||
return Boolean(value) && value.uri !== undefined && isRange(value.range);
|
||||
}
|
||||
|
||||
module.exports = { MAX_PREVIEW, buildReferenceGroups, linesOf, previewLine, referencesTitle };
|
||||
@@ -0,0 +1,193 @@
|
||||
const assert = require('assert/strict');
|
||||
const { MAX_PREVIEW, buildReferenceGroups, linesOf, previewLine, referencesTitle } = require('./referencesModel');
|
||||
|
||||
function at(uri, line, start, endLine, end) {
|
||||
return { uri, range: { start: { line, character: start }, end: { line: endLine, character: end } } };
|
||||
}
|
||||
|
||||
function word(uri, line, start, length) {
|
||||
return at(uri, line, start, line, start + length);
|
||||
}
|
||||
|
||||
/** A reader over in-memory files, keyed by URI string, as the view builds one. */
|
||||
function reader(files) {
|
||||
const lines = new Map(Object.entries(files).map(([uri, text]) => [uri, linesOf(text)]));
|
||||
return (key, line) => (lines.has(key) ? lines.get(key)[line] : undefined);
|
||||
}
|
||||
|
||||
function build(files, locations, options = {}) {
|
||||
return buildReferenceGroups({
|
||||
locations,
|
||||
definitions: options.definitions || [],
|
||||
currentUri: options.currentUri,
|
||||
lineText: reader(files),
|
||||
relativePath: (uri) => String(uri).replace('file:///ws/', ''),
|
||||
});
|
||||
}
|
||||
|
||||
/** The highlighted text of an item, which is what the user actually sees marked. */
|
||||
function marked(item) {
|
||||
return item.highlights.map(([start, end]) => item.text.slice(start, end));
|
||||
}
|
||||
|
||||
function theReportedLineIsShownWhole() {
|
||||
const files = { 'file:///ws/a.sv': 'module a;\n always_ff @(posedge clk) r <= ~r;\nendmodule\n' };
|
||||
const [group] = build(files, [word('file:///ws/a.sv', 1, 27, 1)]);
|
||||
const [item] = group.items;
|
||||
assert.equal(item.text, 'always_ff @(posedge clk) r <= ~r;', 'the whole line, not "clk) r <= ~r;"');
|
||||
assert.deepEqual(item.highlights, [[25, 26]]);
|
||||
assert.deepEqual(marked(item), ['r']);
|
||||
assert.equal(item.line, 2);
|
||||
assert.equal(item.character, 28);
|
||||
}
|
||||
|
||||
function groupsAreOneFilePerGroupCurrentFileFirstThenByPath() {
|
||||
const files = {
|
||||
'file:///ws/z.sv': 'x\n',
|
||||
'file:///ws/b/m.sv': 'x\n',
|
||||
'file:///ws/a.sv': 'x\nx\n',
|
||||
};
|
||||
const groups = build(files, [
|
||||
word('file:///ws/a.sv', 1, 0, 1),
|
||||
word('file:///ws/z.sv', 0, 0, 1),
|
||||
word('file:///ws/b/m.sv', 0, 0, 1),
|
||||
word('file:///ws/a.sv', 0, 0, 1),
|
||||
], { currentUri: 'file:///ws/z.sv' });
|
||||
assert.deepEqual(groups.map((group) => group.path), ['z.sv', 'a.sv', 'b/m.sv']);
|
||||
assert.deepEqual(groups.map((group) => group.count), [1, 2, 1]);
|
||||
assert.equal(referencesTitle('x', groups), 'References: x (4 in 3 files)');
|
||||
assert.equal(referencesTitle('x', groups.slice(0, 1)), 'References: x (1 in 1 file)');
|
||||
}
|
||||
|
||||
function itemsAreInLineOrderAndDuplicatesCollapse() {
|
||||
const files = { 'file:///ws/a.sv': 'a b a\nb\na a\n' };
|
||||
const [group] = build(files, [
|
||||
word('file:///ws/a.sv', 2, 2, 1),
|
||||
word('file:///ws/a.sv', 0, 4, 1),
|
||||
word('file:///ws/a.sv', 2, 0, 1),
|
||||
word('file:///ws/a.sv', 0, 0, 1),
|
||||
word('file:///ws/a.sv', 0, 0, 1),
|
||||
]);
|
||||
assert.equal(group.count, 4, 'the repeated location is one reference');
|
||||
assert.deepEqual(group.items.map((item) => [item.line, item.character]), [[1, 1], [1, 5], [3, 1], [3, 3]]);
|
||||
}
|
||||
|
||||
function trimmingMovesTheHighlightWithTheText() {
|
||||
const [item] = build({ 'file:///ws/a.sv': ' assign y = sig; \n' }, [word('file:///ws/a.sv', 0, 17, 3)])[0].items;
|
||||
assert.equal(item.text, 'assign y = sig;');
|
||||
assert.deepEqual(marked(item), ['sig']);
|
||||
}
|
||||
|
||||
function tabsBecomeSpacesWithoutMovingOffsets() {
|
||||
const [item] = build({ 'file:///ws/a.sv': '\t\tq\t<= d;\n' }, [word('file:///ws/a.sv', 0, 7, 1)])[0].items;
|
||||
assert.equal(item.text, 'q <= d;');
|
||||
assert.deepEqual(marked(item), ['d']);
|
||||
}
|
||||
|
||||
function crlfLinesCarryNoCarriageReturn() {
|
||||
const files = { 'file:///ws/a.sv': 'module a;\r\n wire w;\r\n assign w = 1;\r\nendmodule\r\n' };
|
||||
const [group] = build(files, [word('file:///ws/a.sv', 2, 9, 1), word('file:///ws/a.sv', 1, 7, 1)]);
|
||||
assert.deepEqual(group.items.map((item) => item.text), ['wire w;', 'assign w = 1;']);
|
||||
assert.deepEqual(group.items.map(marked), [['w'], ['w']]);
|
||||
assert.deepEqual(linesOf('a\rb\r\nc\nd'), ['a', 'b', 'c', 'd'], 'a lone CR ends a line, as in VS Code');
|
||||
}
|
||||
|
||||
function aMultiLineRangeIsHighlightedToTheEndOfItsFirstLine() {
|
||||
const files = { 'file:///ws/a.sv': ' foo #(\n .W(1)\n ) u ();\n' };
|
||||
const [item] = build(files, [at('file:///ws/a.sv', 0, 2, 2, 3)])[0].items;
|
||||
assert.equal(item.text, 'foo #(');
|
||||
assert.deepEqual(marked(item), ['foo #(']);
|
||||
}
|
||||
|
||||
function aRangePastTheEndOfTheLineIsClamped() {
|
||||
const short = previewLine(' ab', { start: { line: 0, character: 3 }, end: { line: 0, character: 99 } });
|
||||
assert.deepEqual(short, { text: 'ab', highlights: [[1, 2]] });
|
||||
const beyond = previewLine('ab', { start: { line: 0, character: 50 }, end: { line: 0, character: 60 } });
|
||||
assert.deepEqual(beyond, { text: 'ab', highlights: [] }, 'nothing to mark, but the line still shows');
|
||||
const inTrailingSpace = previewLine('ab ', { start: { line: 0, character: 3 }, end: { line: 0, character: 4 } });
|
||||
assert.deepEqual(inTrailingSpace, { text: 'ab', highlights: [] });
|
||||
}
|
||||
|
||||
function anUnreadableFileStillListsItsReferences() {
|
||||
const [group] = build({}, [word('file:///ws/gone.sv', 4, 0, 3)]);
|
||||
assert.equal(group.count, 1);
|
||||
assert.deepEqual([group.items[0].text, group.items[0].highlights, group.items[0].line], ['', [], 5]);
|
||||
const pastEnd = build({ 'file:///ws/a.sv': 'x\n' }, [word('file:///ws/a.sv', 9, 0, 1)])[0].items[0];
|
||||
assert.equal(pastEnd.text, '', 'a line the file no longer has');
|
||||
}
|
||||
|
||||
function anOverlongLineIsWindowedAroundTheMatch() {
|
||||
const filler = 'a'.repeat(1000);
|
||||
const line = `${filler} target ${filler}`;
|
||||
const preview = previewLine(line, { start: { line: 0, character: 1001 }, end: { line: 0, character: 1007 } });
|
||||
assert(preview.text.length <= MAX_PREVIEW + 2, 'two ellipses at most beyond the window');
|
||||
assert(preview.text.startsWith('…') && preview.text.endsWith('…'));
|
||||
const [[start, end]] = preview.highlights;
|
||||
assert.equal(preview.text.slice(start, end), 'target');
|
||||
const head = previewLine(`x ${filler}`, { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } });
|
||||
assert(!head.text.startsWith('…') && head.text.endsWith('…'));
|
||||
assert.deepEqual(head.highlights, [[0, 1]]);
|
||||
const tail = previewLine(`${filler} x`, { start: { line: 0, character: 1001 }, end: { line: 0, character: 1002 } });
|
||||
assert(tail.text.startsWith('…') && !tail.text.endsWith('…'));
|
||||
assert.equal(tail.text.slice(...tail.highlights[0]), 'x');
|
||||
}
|
||||
|
||||
function theDeclarationIsTheReferenceAtADefinitionsStart() {
|
||||
const files = { 'file:///ws/a.sv': 'logic v;\nassign v = 1;\n', 'file:///ws/b.sv': 'v\n' };
|
||||
const locations = [word('file:///ws/a.sv', 1, 7, 1), word('file:///ws/a.sv', 0, 6, 1), word('file:///ws/b.sv', 0, 0, 1)];
|
||||
const asLocation = build(files, locations, { definitions: [word('file:///ws/a.sv', 0, 6, 1)] });
|
||||
assert.deepEqual(asLocation.flatMap((group) => group.items.map((item) => item.declaration)), [true, false, false]);
|
||||
const asLink = build(files, locations, {
|
||||
definitions: [{ targetUri: 'file:///ws/a.sv', targetRange: at('file:///ws/a.sv', 0, 0, 0, 8).range, targetSelectionRange: word('file:///ws/a.sv', 0, 6, 1).range }],
|
||||
});
|
||||
assert.deepEqual(asLink.flatMap((group) => group.items.map((item) => item.declaration)), [true, false, false]);
|
||||
const wholeDeclaration = build(files, locations, { definitions: [at('file:///ws/a.sv', 0, 0, 0, 8)] });
|
||||
assert.deepEqual(wholeDeclaration.flatMap((group) => group.items.map((item) => item.declaration)), [true, false, false],
|
||||
'a definition range spanning the declaration marks the reference inside it');
|
||||
const elsewhere = build(files, locations, { definitions: [word('file:///ws/c.sv', 0, 6, 1)] });
|
||||
assert(elsewhere.every((group) => group.items.every((item) => !item.declaration)), 'same position, other file: not it');
|
||||
const none = build(files, locations, { definitions: undefined });
|
||||
assert(none.every((group) => group.items.every((item) => !item.declaration)));
|
||||
}
|
||||
|
||||
function anEmptyOrMalformedAnswerIsNoGroups() {
|
||||
assert.deepEqual(build({}, []), []);
|
||||
assert.deepEqual(build({}, undefined), []);
|
||||
assert.deepEqual(build({}, [null, { uri: 'file:///ws/a.sv' }, { uri: 'file:///ws/a.sv', range: { start: {} } }]), []);
|
||||
}
|
||||
|
||||
function fiveHundredReferencesAreCheap() {
|
||||
const text = Array.from({ length: 200 }, (_, line) => ` assign out_${line} = sig & mask_${line};`).join('\n');
|
||||
const files = {};
|
||||
const locations = [];
|
||||
for (let file = 0; file < 25; file += 1) {
|
||||
const uri = `file:///ws/f${String(file).padStart(2, '0')}.sv`;
|
||||
files[uri] = text;
|
||||
for (let line = 0; line < 20; line += 1) locations.push(word(uri, line * 10, 16 + String(line * 10).length, 3));
|
||||
}
|
||||
const started = process.hrtime.bigint();
|
||||
const groups = build(files, locations, { currentUri: 'file:///ws/f07.sv' });
|
||||
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
|
||||
assert.equal(groups.reduce((sum, group) => sum + group.count, 0), 500);
|
||||
assert.equal(groups[0].path, 'f07.sv');
|
||||
assert(groups.every((group) => group.items.every((item) => marked(item)[0] === 'sig')));
|
||||
assert(elapsedMs < 200, `500 references took ${elapsedMs} ms`);
|
||||
}
|
||||
|
||||
for (const test of [
|
||||
theReportedLineIsShownWhole,
|
||||
groupsAreOneFilePerGroupCurrentFileFirstThenByPath,
|
||||
itemsAreInLineOrderAndDuplicatesCollapse,
|
||||
trimmingMovesTheHighlightWithTheText,
|
||||
tabsBecomeSpacesWithoutMovingOffsets,
|
||||
crlfLinesCarryNoCarriageReturn,
|
||||
aMultiLineRangeIsHighlightedToTheEndOfItsFirstLine,
|
||||
aRangePastTheEndOfTheLineIsClamped,
|
||||
anUnreadableFileStillListsItsReferences,
|
||||
anOverlongLineIsWindowedAroundTheMatch,
|
||||
theDeclarationIsTheReferenceAtADefinitionsStart,
|
||||
anEmptyOrMalformedAnswerIsNoGroups,
|
||||
fiveHundredReferencesAreCheap,
|
||||
]) test();
|
||||
|
||||
console.log('references model: OK — whole lines, grouping and order, trim/tab/CRLF offsets, multi-line and clamped ranges, windows, the declaration mark, empty answers, and 500 references');
|
||||
@@ -0,0 +1,156 @@
|
||||
// The lucisv References view: Find All References with every reference's
|
||||
// whole source line, the identifier highlighted, grouped by file.
|
||||
//
|
||||
// VS Code's own References view and peek cut each preview to a few characters
|
||||
// before the match, so `always_ff @(posedge clk) r <= ~r;` reads `clk) r <= ~r;`.
|
||||
// The server's ranges are exact; the preview is the client's, so this view is
|
||||
// the client's too (docs/features/vscode-references-view). The answers still
|
||||
// come from the server, through VS Code's own provider commands.
|
||||
|
||||
const vscode = require('vscode');
|
||||
const { buildReferenceGroups, linesOf, referencesTitle } = require('./referencesModel');
|
||||
|
||||
const VIEW_ID = 'lucisv.references';
|
||||
/** Shows the view; it stays hidden until the first search fills it. */
|
||||
const HAS_RESULTS_KEY = 'lucisv.references.hasResults';
|
||||
|
||||
class ReferencesView {
|
||||
constructor(context) {
|
||||
this.groups = [];
|
||||
this.request = 0;
|
||||
this.changed = new vscode.EventEmitter();
|
||||
this.onDidChangeTreeData = this.changed.event;
|
||||
this.treeView = vscode.window.createTreeView(VIEW_ID, { treeDataProvider: this, showCollapseAll: true });
|
||||
context.subscriptions.push(
|
||||
this.treeView,
|
||||
this.changed,
|
||||
vscode.commands.registerCommand('lucisv.references.show', () => this.show()),
|
||||
vscode.commands.registerCommand('lucisv.references.clear', () => this.clear()),
|
||||
);
|
||||
}
|
||||
|
||||
/** Find the references at the active editor's cursor and fill the view with them. */
|
||||
async show() {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) return;
|
||||
const { document } = editor;
|
||||
const position = editor.selection.active;
|
||||
const asked = ++this.request;
|
||||
let locations;
|
||||
let definitions;
|
||||
try {
|
||||
[locations, definitions] = await Promise.all([
|
||||
vscode.commands.executeCommand('vscode.executeReferenceProvider', document.uri, position),
|
||||
// Only for the declaration mark: a failure here costs the mark, never the list.
|
||||
Promise.resolve(vscode.commands.executeCommand('vscode.executeDefinitionProvider', document.uri, position)).catch(() => []),
|
||||
]);
|
||||
} catch (error) {
|
||||
if (asked === this.request) vscode.window.showWarningMessage(`lucisv: Find All References failed: ${(error && error.message) || error}`);
|
||||
return;
|
||||
}
|
||||
const lineText = await readLines(locations || []);
|
||||
if (asked !== this.request) return;
|
||||
this.groups = buildReferenceGroups({
|
||||
locations: locations || [],
|
||||
definitions: definitions || [],
|
||||
currentUri: document.uri,
|
||||
lineText,
|
||||
relativePath: (uri) => vscode.workspace.asRelativePath(uri),
|
||||
});
|
||||
const name = wordAt(document, position);
|
||||
this.treeView.title = this.groups.length > 0 ? referencesTitle(name, this.groups) : `References: ${name}`;
|
||||
this.treeView.message = this.groups.length > 0 ? undefined : `No references to ${name}.`;
|
||||
this.changed.fire();
|
||||
await vscode.commands.executeCommand('setContext', HAS_RESULTS_KEY, true);
|
||||
await vscode.commands.executeCommand(`${VIEW_ID}.focus`);
|
||||
}
|
||||
|
||||
/** Empty the view and hide it again. */
|
||||
async clear() {
|
||||
this.request += 1;
|
||||
this.groups = [];
|
||||
this.treeView.title = 'References';
|
||||
this.treeView.message = undefined;
|
||||
this.changed.fire();
|
||||
await vscode.commands.executeCommand('setContext', HAS_RESULTS_KEY, false);
|
||||
}
|
||||
|
||||
getChildren(node) {
|
||||
if (!node) return this.groups;
|
||||
return node.items || [];
|
||||
}
|
||||
|
||||
getTreeItem(node) {
|
||||
return node.items ? fileItem(node) : referenceItem(node);
|
||||
}
|
||||
}
|
||||
|
||||
/** A file's row: its workspace-relative path and how many references it holds. */
|
||||
function fileItem(group) {
|
||||
const item = new vscode.TreeItem(group.path, vscode.TreeItemCollapsibleState.Expanded);
|
||||
item.resourceUri = group.uri;
|
||||
item.iconPath = vscode.ThemeIcon.File;
|
||||
item.description = String(group.count);
|
||||
item.tooltip = group.path;
|
||||
return item;
|
||||
}
|
||||
|
||||
/** A reference's row: the whole line, the identifier highlighted; a click selects it in its file. */
|
||||
function referenceItem(reference) {
|
||||
const label = reference.text === ''
|
||||
? { label: `line ${reference.line}` }
|
||||
: { label: reference.text, highlights: reference.highlights };
|
||||
const item = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.None);
|
||||
const { uri, range } = reference.location;
|
||||
item.description = reference.declaration ? `declaration · line ${reference.line}` : `line ${reference.line}`;
|
||||
if (reference.declaration) item.iconPath = new vscode.ThemeIcon('symbol-key');
|
||||
item.tooltip = `${vscode.workspace.asRelativePath(uri)}:${reference.line}:${reference.character}`;
|
||||
item.command = {
|
||||
command: 'vscode.open',
|
||||
title: 'Open Reference',
|
||||
arguments: [uri, { selection: range, preserveFocus: false, preview: true }],
|
||||
};
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* A `lineText(key, line)` reader over every file the answer names. An open
|
||||
* document is read from its buffer — unsaved edits are what the server
|
||||
* answered against. A closed file is read from disk with
|
||||
* `workspace.fs`, not `openTextDocument`: opening five hundred files' worth of
|
||||
* documents would send the server a `didOpen` for each, and fill Problems with
|
||||
* their diagnostics, for a preview line.
|
||||
*/
|
||||
async function readLines(locations) {
|
||||
const uris = new Map();
|
||||
for (const location of locations) {
|
||||
if (location && location.uri !== undefined) uris.set(String(location.uri), location.uri);
|
||||
}
|
||||
const open = new Map(vscode.workspace.textDocuments.map((document) => [document.uri.toString(), document]));
|
||||
const readers = new Map(await Promise.all([...uris].map(async ([key, uri]) => [key, await fileReader(open.get(key), uri)])));
|
||||
return (key, line) => {
|
||||
const reader = readers.get(key);
|
||||
return reader ? reader(line) : undefined;
|
||||
};
|
||||
}
|
||||
|
||||
/** One file's line reader, or `undefined` if it cannot be read. */
|
||||
async function fileReader(document, uri) {
|
||||
if (document) return (line) => (line >= 0 && line < document.lineCount ? document.lineAt(line).text : undefined);
|
||||
try {
|
||||
const lines = linesOf(new TextDecoder().decode(await vscode.workspace.fs.readFile(uri)));
|
||||
return (line) => lines[line];
|
||||
} catch {
|
||||
// Deleted since it was indexed, or a scheme `workspace.fs` cannot read: the
|
||||
// row still opens the location, and says which line it is.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The identifier under the cursor, for the title. */
|
||||
function wordAt(document, position) {
|
||||
const range = document.getWordRangeAtPosition(position);
|
||||
return range ? document.getText(range) : 'symbol';
|
||||
}
|
||||
|
||||
module.exports = { ReferencesView, VIEW_ID };
|
||||
@@ -0,0 +1,330 @@
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const Module = require('module');
|
||||
const path = require('path');
|
||||
|
||||
const disposables = () => ({ dispose() {} });
|
||||
const commands = new Map();
|
||||
const executed = [];
|
||||
const warned = [];
|
||||
const readFromDisk = [];
|
||||
let treeOptions;
|
||||
let treeView;
|
||||
let fired = 0;
|
||||
/** What the stubbed providers answer; each test sets them. */
|
||||
let references = [];
|
||||
let definitions = [];
|
||||
let referenceFailure;
|
||||
let definitionFailure;
|
||||
let activeTextEditor;
|
||||
const disk = new Map();
|
||||
const openDocuments = [];
|
||||
|
||||
class Range {
|
||||
constructor(startLine, startCharacter, endLine, endCharacter) {
|
||||
this.start = { line: startLine, character: startCharacter };
|
||||
this.end = { line: endLine, character: endCharacter };
|
||||
}
|
||||
}
|
||||
|
||||
class TreeItem {
|
||||
constructor(label, collapsibleState) {
|
||||
this.label = label;
|
||||
this.collapsibleState = collapsibleState;
|
||||
}
|
||||
}
|
||||
|
||||
class ThemeIcon {
|
||||
constructor(id) { this.id = id; }
|
||||
}
|
||||
ThemeIcon.File = new ThemeIcon('file');
|
||||
|
||||
class EventEmitter {
|
||||
constructor() { this.event = () => disposables(); }
|
||||
fire() { fired += 1; }
|
||||
dispose() {}
|
||||
}
|
||||
|
||||
function uri(value) {
|
||||
return { value, fsPath: value.replace('file://', ''), toString: () => value };
|
||||
}
|
||||
|
||||
function location(file, line, start, end) {
|
||||
return { uri: uri(file), range: new Range(line, start, line, end) };
|
||||
}
|
||||
|
||||
const vscode = {
|
||||
Range,
|
||||
TreeItem,
|
||||
ThemeIcon,
|
||||
EventEmitter,
|
||||
TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 },
|
||||
commands: {
|
||||
registerCommand(id, handler) { commands.set(id, handler); return disposables(); },
|
||||
async executeCommand(id, ...args) {
|
||||
executed.push([id, ...args]);
|
||||
if (id === 'vscode.executeReferenceProvider') {
|
||||
if (referenceFailure) throw referenceFailure;
|
||||
return references;
|
||||
}
|
||||
if (id === 'vscode.executeDefinitionProvider') {
|
||||
if (definitionFailure) throw definitionFailure;
|
||||
return definitions;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
},
|
||||
workspace: {
|
||||
textDocuments: openDocuments,
|
||||
asRelativePath(value) { return String(value).replace('file:///ws/', ''); },
|
||||
fs: {
|
||||
async readFile(value) {
|
||||
readFromDisk.push(value.toString());
|
||||
if (!disk.has(value.toString())) throw new Error('ENOENT');
|
||||
return new TextEncoder().encode(disk.get(value.toString()));
|
||||
},
|
||||
},
|
||||
async openTextDocument() { throw new Error('the view must not open documents to read a preview line'); },
|
||||
},
|
||||
window: {
|
||||
get activeTextEditor() { return activeTextEditor; },
|
||||
createTreeView(id, options) {
|
||||
assert.equal(id, 'lucisv.references');
|
||||
treeOptions = options;
|
||||
treeView = { title: 'References', message: undefined, dispose() {} };
|
||||
return treeView;
|
||||
},
|
||||
showWarningMessage(text) { warned.push(text); },
|
||||
},
|
||||
};
|
||||
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function load(request, parent, main) {
|
||||
if (request === 'vscode') return vscode;
|
||||
return originalLoad(request, parent, main);
|
||||
};
|
||||
const { ReferencesView } = require('./referencesView');
|
||||
Module._load = originalLoad;
|
||||
|
||||
/** An open, possibly unsaved buffer: its text wins over the file on disk. */
|
||||
function document(file, text) {
|
||||
const lines = text.split('\n');
|
||||
return {
|
||||
uri: uri(file),
|
||||
lineCount: lines.length,
|
||||
lineAt(line) { return { text: lines[line] }; },
|
||||
getWordRangeAtPosition(position) {
|
||||
const match = /\w+/g;
|
||||
let found;
|
||||
while ((found = match.exec(lines[position.line]))) {
|
||||
if (found.index <= position.character && position.character <= found.index + found[0].length) {
|
||||
return new Range(position.line, found.index, position.line, found.index + found[0].length);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
getText(range) { return lines[range.start.line].slice(range.start.character, range.end.character); },
|
||||
};
|
||||
}
|
||||
|
||||
const context = { subscriptions: [] };
|
||||
const view = new ReferencesView(context);
|
||||
|
||||
function labels(nodes) {
|
||||
return nodes.map((node) => view.getTreeItem(node));
|
||||
}
|
||||
|
||||
async function theCommandFillsGroupsAndRevealsTheView() {
|
||||
const top = document('file:///ws/top.sv', 'module top;\n always_ff @(posedge clk) r <= ~r;\n logic r;\nendmodule');
|
||||
openDocuments.push(top);
|
||||
disk.set('file:///ws/sub/b.sv', 'module b;\r\n\tassign y = top.r;\r\nendmodule\r\n');
|
||||
disk.set('file:///ws/a.sv', 'assign z = r;\n');
|
||||
activeTextEditor = { document: top, selection: { active: { line: 2, character: 8 } } };
|
||||
references = [
|
||||
location('file:///ws/sub/b.sv', 1, 16, 17),
|
||||
location('file:///ws/top.sv', 2, 8, 9),
|
||||
location('file:///ws/a.sv', 0, 11, 12),
|
||||
location('file:///ws/top.sv', 1, 27, 28),
|
||||
];
|
||||
definitions = [{ targetUri: uri('file:///ws/top.sv'), targetRange: new Range(2, 2, 2, 10), targetSelectionRange: new Range(2, 8, 2, 9) }];
|
||||
executed.length = 0;
|
||||
const before = fired;
|
||||
await commands.get('lucisv.references.show')();
|
||||
|
||||
const asked = executed.filter(([id]) => id.startsWith('vscode.execute'));
|
||||
assert.deepEqual(asked.map(([id, at, position]) => [id, at.toString(), position]), [
|
||||
['vscode.executeReferenceProvider', 'file:///ws/top.sv', { line: 2, character: 8 }],
|
||||
['vscode.executeDefinitionProvider', 'file:///ws/top.sv', { line: 2, character: 8 }],
|
||||
]);
|
||||
assert.equal(fired, before + 1, 'the tree is told to re-read');
|
||||
assert.equal(treeView.title, 'References: r (4 in 3 files)');
|
||||
assert.equal(treeView.message, undefined);
|
||||
const tail = executed.slice(-2);
|
||||
assert.deepEqual(tail, [['setContext', 'lucisv.references.hasResults', true], ['lucisv.references.focus']],
|
||||
'the view is unhidden, then revealed');
|
||||
assert.deepEqual(readFromDisk.sort(), ['file:///ws/a.sv', 'file:///ws/sub/b.sv'], 'the open buffer is not read from disk');
|
||||
|
||||
const groups = view.getChildren();
|
||||
const fileRows = labels(groups);
|
||||
assert.deepEqual(fileRows.map((row) => [row.label, row.description]), [['top.sv', '2'], ['a.sv', '1'], ['sub/b.sv', '1']]);
|
||||
assert(fileRows.every((row) => row.collapsibleState === vscode.TreeItemCollapsibleState.Expanded && row.resourceUri));
|
||||
|
||||
const topRows = labels(view.getChildren(groups[0]));
|
||||
assert.deepEqual(topRows.map((row) => row.label), [
|
||||
{ label: 'always_ff @(posedge clk) r <= ~r;', highlights: [[25, 26]] },
|
||||
{ label: 'logic r;', highlights: [[6, 7]] },
|
||||
]);
|
||||
assert.deepEqual(topRows.map((row) => row.description), ['line 2', 'declaration · line 3']);
|
||||
assert.equal(topRows[0].iconPath, undefined);
|
||||
assert.equal(topRows[1].iconPath.id, 'symbol-key');
|
||||
assert.equal(topRows[0].tooltip, 'top.sv:2:28');
|
||||
assert.equal(topRows[0].command.command, 'vscode.open');
|
||||
const [target, options] = topRows[0].command.arguments;
|
||||
assert.equal(target.toString(), 'file:///ws/top.sv');
|
||||
assert.deepEqual(options.selection, new Range(1, 27, 1, 28), 'a click selects exactly the identifier');
|
||||
|
||||
const crlfRow = labels(view.getChildren(groups[2]))[0];
|
||||
assert.deepEqual(crlfRow.label, { label: 'assign y = top.r;', highlights: [[15, 16]] }, 'tab and CRLF handled');
|
||||
assert.deepEqual(view.getChildren(view.getChildren(groups[0])[0]), [], 'a reference row is a leaf');
|
||||
}
|
||||
|
||||
async function anEmptyAnswerSaysSoInTheView() {
|
||||
references = [];
|
||||
definitions = [];
|
||||
await commands.get('lucisv.references.show')();
|
||||
assert.deepEqual(view.getChildren(), []);
|
||||
assert.equal(treeView.title, 'References: r');
|
||||
assert.equal(treeView.message, 'No references to r.');
|
||||
}
|
||||
|
||||
async function aMissingFileStillListsItsReference() {
|
||||
references = [location('file:///ws/deleted.sv', 6, 0, 1)];
|
||||
await commands.get('lucisv.references.show')();
|
||||
const [row] = labels(view.getChildren(view.getChildren()[0]));
|
||||
assert.deepEqual(row.label, { label: 'line 7' });
|
||||
assert.equal(row.command.command, 'vscode.open');
|
||||
}
|
||||
|
||||
async function aFailedDefinitionCostsOnlyTheMark() {
|
||||
references = [location('file:///ws/top.sv', 2, 8, 9)];
|
||||
definitionFailure = new Error('no definition provider');
|
||||
await commands.get('lucisv.references.show')();
|
||||
definitionFailure = undefined;
|
||||
const [row] = labels(view.getChildren(view.getChildren()[0]));
|
||||
assert.equal(row.description, 'line 3');
|
||||
assert.deepEqual(warned, []);
|
||||
}
|
||||
|
||||
async function aFailedSearchWarnsAndKeepsTheOldList() {
|
||||
const shown = view.getChildren();
|
||||
referenceFailure = new Error('server restarting');
|
||||
await commands.get('lucisv.references.show')();
|
||||
referenceFailure = undefined;
|
||||
assert.deepEqual(warned, ['lucisv: Find All References failed: server restarting']);
|
||||
assert.equal(view.getChildren(), shown);
|
||||
}
|
||||
|
||||
async function noEditorIsANoOp() {
|
||||
activeTextEditor = undefined;
|
||||
executed.length = 0;
|
||||
await commands.get('lucisv.references.show')();
|
||||
assert.deepEqual(executed, []);
|
||||
}
|
||||
|
||||
async function clearEmptiesAndHidesTheView() {
|
||||
await commands.get('lucisv.references.clear')();
|
||||
assert.deepEqual(view.getChildren(), []);
|
||||
assert.equal(treeView.title, 'References');
|
||||
assert.deepEqual(executed.at(-1), ['setContext', 'lucisv.references.hasResults', false]);
|
||||
}
|
||||
|
||||
async function aStaleAnswerDoesNotOverwriteANewerOne() {
|
||||
const top = document('file:///ws/top.sv', 'logic r;\nlogic s;');
|
||||
activeTextEditor = { document: top, selection: { active: { line: 0, character: 6 } } };
|
||||
let release;
|
||||
const gate = new Promise((resolve) => { release = resolve; });
|
||||
const original = vscode.commands.executeCommand;
|
||||
let calls = 0;
|
||||
vscode.commands.executeCommand = async (id, ...args) => {
|
||||
if (id === 'vscode.executeReferenceProvider' && calls++ === 0) {
|
||||
await gate;
|
||||
return [location('file:///ws/top.sv', 0, 6, 7)];
|
||||
}
|
||||
if (id === 'vscode.executeReferenceProvider') return [location('file:///ws/top.sv', 1, 6, 7)];
|
||||
return original(id, ...args);
|
||||
};
|
||||
const slow = commands.get('lucisv.references.show')();
|
||||
activeTextEditor = { document: top, selection: { active: { line: 1, character: 6 } } };
|
||||
await commands.get('lucisv.references.show')();
|
||||
release();
|
||||
await slow;
|
||||
vscode.commands.executeCommand = original;
|
||||
assert.equal(treeView.title, 'References: s (1 in 1 file)', 'the later search wins');
|
||||
}
|
||||
|
||||
function theManifestWiresTheViewCommandAndKeybinding() {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const { contributes } = manifest;
|
||||
const view = contributes.views.lucisv.find((entry) => entry.id === 'lucisv.references');
|
||||
assert(view, 'the view lives in the lucisv container');
|
||||
assert.equal(view.when, 'lucisv.references.hasResults');
|
||||
const titles = Object.fromEntries(contributes.commands.map((entry) => [entry.command, entry.title]));
|
||||
assert.equal(titles['lucisv.references.show'], 'Find All References (full lines)');
|
||||
assert(titles['lucisv.references.clear']);
|
||||
|
||||
const setting = contributes.configuration.properties['lucisv.references.fullLineView'];
|
||||
assert.deepEqual([setting.type, setting.default], ['boolean', true]);
|
||||
|
||||
const [binding, ...others] = contributes.keybindings.filter((entry) => entry.command === 'lucisv.references.show');
|
||||
assert.deepEqual(others, []);
|
||||
assert.equal(binding.key, 'shift+alt+f12');
|
||||
assert.equal(binding.mac, undefined, 'macOS uses the same chord as everywhere else');
|
||||
assert(binding.when.includes('config.lucisv.references.fullLineView'), 'off leaves the built-in on the key');
|
||||
assertVerilogOnly(binding.when);
|
||||
assert(!contributes.keybindings.some((entry) => /shift\+f12$/.test(entry.key) && !entry.key.includes('alt')), 'peek stays built-in');
|
||||
|
||||
const menu = contributes.menus['editor/context'].find((entry) => entry.command === 'lucisv.references.show');
|
||||
assertVerilogOnly(menu.when);
|
||||
const palette = contributes.menus.commandPalette.find((entry) => entry.command === 'lucisv.references.show');
|
||||
assertVerilogOnly(palette.when);
|
||||
}
|
||||
|
||||
/** The `when` clause's language test, checked against both languages and a near miss. */
|
||||
function assertVerilogOnly(when) {
|
||||
const match = /editorLangId =~ \/(.+)\/(?:\s|$)/.exec(when);
|
||||
assert(match, `a language test in ${when}`);
|
||||
const pattern = new RegExp(match[1]);
|
||||
assert(pattern.test('verilog') && pattern.test('systemverilog'));
|
||||
assert(!pattern.test('vhdl') && !pattern.test('verilog-ams') && !pattern.test('csystemverilog'));
|
||||
}
|
||||
|
||||
function theRuntimeFilesShip() {
|
||||
const ignored = fs.readFileSync(path.join(__dirname, '.vscodeignore'), 'utf8').split('\n').map((line) => line.trim());
|
||||
for (const file of ['referencesModel.js', 'referencesView.js']) {
|
||||
assert(!ignored.includes(file), `${file} is required at runtime and must ship`);
|
||||
}
|
||||
for (const file of ['referencesModel_test.js', 'referencesView_test.js']) {
|
||||
assert(ignored.includes(file), `${file} is a developer check and stays out of the package`);
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
await theCommandFillsGroupsAndRevealsTheView();
|
||||
await anEmptyAnswerSaysSoInTheView();
|
||||
await aMissingFileStillListsItsReference();
|
||||
await aFailedDefinitionCostsOnlyTheMark();
|
||||
await aFailedSearchWarnsAndKeepsTheOldList();
|
||||
await noEditorIsANoOp();
|
||||
await clearEmptiesAndHidesTheView();
|
||||
await aStaleAnswerDoesNotOverwriteANewerOne();
|
||||
theManifestWiresTheViewCommandAndKeybinding();
|
||||
theRuntimeFilesShip();
|
||||
assert(treeOptions.treeDataProvider === view && treeOptions.showCollapseAll);
|
||||
assert.equal(context.subscriptions.length, 4);
|
||||
console.log('references view: OK — command, grouping, full-line labels, declaration mark, click target, empty/failed/stale answers, clear, manifest and packaging');
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+9
-6
@@ -201,12 +201,15 @@ npx @vscode/vsce package --target darwin-arm64 \
|
||||
repo and only writes its *output* to `-o`.
|
||||
- `.vscodeignore` keeps `smoke.js`, `mcp_smoke.js`, every `*_test.js`,
|
||||
`.vscode/**` and `.gitignore` out of the package. It must **not** exclude `bin/`, which is
|
||||
where the platform packages' binaries are staged — nor `restart.js`, which
|
||||
`extension.js` requires at runtime (an extension that ships without it fails
|
||||
to activate), nor `mcp.js`, for the same reason. Check that after any change
|
||||
to it: `unzip -l dist/lucisv-<version>.vsix | grep -E 'smoke|_test'` must
|
||||
print nothing, `unzip -l dist/lucisv-<version>.vsix | grep -E 'restart.js|mcp.js'`
|
||||
must print `extension/restart.js` and `extension/mcp.js`, and
|
||||
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:
|
||||
`unzip -l dist/lucisv-<version>.vsix | grep -E 'smoke|_test'` must print
|
||||
nothing, `unzip -l dist/lucisv-<version>.vsix | grep -E 'restart.js|mcp.js|references(View|Model).js'`
|
||||
must print `extension/restart.js`, `extension/mcp.js`,
|
||||
`extension/referencesView.js` and `extension/referencesModel.js`, and
|
||||
`unzip -l dist/lucisv-<version>.vsix | grep syntaxes` must print the grammar —
|
||||
without it, hover cards ship unhighlighted.
|
||||
- **`editors/vscode/bin/` is transient.** `release.sh` stages one platform's
|
||||
|
||||
Reference in new issue
Block a user