Files
lucisv/editors/vscode/referencesView_test.js
T
lucioandClaude Opus 5.5 5e4af0be3d 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]>
2026-10-14 14:14:11 -07:00

331 lines
13 KiB
JavaScript

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;
});