Files
lucisv/editors/vscode/extension.js
T
lucioandClaude Fable 5 cebb333bd7 All-platforms VSIX + the release flow consolidated in one script
A 7th package, lucisv-<v>-all.vsix, carries every platform's binary
pair under bin/<platform>-<arch>/ and the extension picks the right one
at runtime — flat bin/ (platform package) first, then the platform-arch
subdirectory, then PATH. Target-less on purpose, so Alpine and anything
else vsce refuses to name gets working static binaries. The release.yml
inline prune step moves into tools/prune_release_assets.sh, which now
requires all seven packages by name before anything is published.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 02:03:10 -07:00

309 lines
13 KiB
JavaScript

// The whole VS Code extension: start `lucisv-server` over stdio, let the
// language client do the rest, and paint one thing the protocol has no request
// for — the `begin`/`end` rainbow, whose ranges the server computes and hands
// over through the custom `lucisv/scopePairs` request.
//
// Every *answer* still comes from the server: nothing here parses Verilog, and
// the only reason this file is longer than the language client's setup is that
// LSP has no "decorate these ranges" notification, so the painting has to be
// driven from the client side (docs/features/editor-scopes).
const fs = require('fs');
const path = require('path');
const vscode = require('vscode');
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
/** The single client, kept only so `deactivate` can stop it. */
let client;
/** The languages this extension attaches to. */
const LANGUAGES = ['verilog', 'systemverilog'];
/**
* How many colours the rainbow cycles through. Six, to match VS Code's own
* bracket colouring — but the colours are **this extension's own**
* (`lucisv.rainbow1..6`, contributed with visible defaults for every theme kind
* in `package.json`), not `editorBracketHighlight.foreground1..6`. Those look
* like the obvious thing to borrow and are a trap: VS Code's registry defaults
* `foreground4`, `5` and `6` to `#00000000` — fully transparent — and leaves it
* to themes to define them, which most do not. Painting with them made every
* `begin` at depth 3, 4 or 5 invisible.
*/
const RAINBOW_COLORS = 6;
/** How long to let typing settle before re-asking for pairs. */
const REPAINT_DEBOUNCE_MS = 250;
/** One decoration type per colour, created once and reused. */
let decorationTypes = [];
/** The decoration for a `begin`/`end` whose counterpart is missing. */
let unmatchedType;
/** Whether the rainbow is on, per `lucisv.rainbowBeginEnd`. */
let rainbowEnabled = true;
/** The pending debounced repaint, if any. */
let repaintTimer;
/**
* The `lucisv.serverPath` scopes a *user* can write to, most specific first —
* the order VS Code's own `get()` resolves them in.
*
* `defaultValue` and `defaultLanguageValue` are deliberately absent: those are
* defaults contributed by a manifest, not something anybody chose, and treating
* them as a choice is exactly the bug this list exists to avoid (see
* `userServerPath`).
*/
const SERVER_PATH_SCOPES = [
'workspaceFolderLanguageValue',
'workspaceLanguageValue',
'globalLanguageValue',
'workspaceFolderValue',
'workspaceValue',
'globalValue',
];
/**
* The `lucisv.serverPath` the user set, or `undefined` if they never set one.
*
* `inspect()` and not `get()`, and this is the whole reason the function
* exists: `get()` answers `"lucisv-server"` for someone who has never touched
* the setting, because that is `package.json`'s own default — so a `get()`
* check would make the bundled server unreachable for every user who did not
* explicitly override it. A blank value counts as unset, as it always has.
*/
function userServerPath() {
const inspected = vscode.workspace.getConfiguration('lucisv').inspect('serverPath');
if (!inspected) return undefined;
for (const scope of SERVER_PATH_SCOPES) {
const value = inspected[scope];
if (typeof value === 'string' && value.trim() !== '') return value;
}
return undefined;
}
/**
* The path to a binary this package carries under `bin/`, or `undefined` if it
* carries none.
*
* Two layouts are looked at, most specific first
* (docs/features/editor-platform-vsix):
*
* 1. `bin/<name>` — a **platform package**, stamped with vsce's `--target`, so
* its `bin/` is flat and holds exactly one platform's binaries.
* 2. `bin/<platform>-<arch>/<name>` — the **all-platforms package**, which
* carries every platform's pair at once and picks between them here, at
* runtime. The directory names are literally `${process.platform}-${process.arch}`.
*
* The universal package has no `bin/` at all, so both lookups miss and the
* caller falls back to `PATH`. So does a platform we ship no binaries for —
* `win32-arm64`, say: it finds nothing in either layout, and the all-platforms
* package behaves for it exactly like the universal one.
*
* On anything but Windows the executable bit is restored first: VSIX extraction
* does not reliably preserve it — the same chmod, for the same reason, that
* rust-analyzer's extension does — and a server that cannot be spawned looks
* to the user exactly like a server that crashed.
*/
function bundledBinary(context, name) {
const file = process.platform === 'win32' ? `${name}.exe` : name;
const found = [
context.asAbsolutePath(path.join('bin', file)),
context.asAbsolutePath(path.join('bin', `${process.platform}-${process.arch}`, file)),
].find((candidate) => fs.existsSync(candidate));
if (!found) return undefined;
if (process.platform !== 'win32') {
try {
fs.chmodSync(found, 0o755);
} catch {
// A read-only install, or a file owned by someone else. Spawning may
// still work; if it does not, the language client says so in its own
// output channel, which is where the user is already looking.
}
}
return found;
}
/** Spawn the server and attach it to Verilog/SystemVerilog documents. */
function activate(context) {
// Nothing here spawns the bundled CLI, but the platform packages ship it so
// that installing the extension gives you `lucisv` too — which is only true
// if it is executable.
bundledBinary(context, 'lucisv');
// Resolved unconditionally, so both bundled binaries are made executable
// even when a user setting wins the spawn below.
const bundledServer = bundledBinary(context, 'lucisv-server');
// A setting the user wrote, else the binary in this package, else the bare
// name on PATH — which is what the universal package and a `cargo build`
// install have always used.
const serverPath = userServerPath() || bundledServer || 'lucisv-server';
// No arguments: `lucisv-server` takes none and speaks LSP on stdin/stdout.
// `editors/vscode/smoke.js` spawns it exactly this way.
const serverOptions = {
command: serverPath,
args: [],
transport: TransportKind.stdio,
};
// No `scheme` filter: the server serves `untitled:` buffers too, for
// everything single-file (docs/features/lucisv-server/README.md).
const clientOptions = {
documentSelector: LANGUAGES.map((language) => ({ language })),
// Push the whole `lucisv` section to the server as
// `workspace/didChangeConfiguration` — once when the client initializes
// and again on every change. The server reads `lucisv.lineLength`,
// `lucisv.indent` and `lucisv.exclude` from it and ignores the rest
// (docs/features/editor-settings/README.md).
synchronize: { configurationSection: 'lucisv' },
};
client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions);
// `textDocument/inlineCompletion` is LSP 3.18 and still proposed, so
// vscode-languageclient 9 does not register its client feature by default —
// without this, the server's `inlineCompletionProvider` capability is read
// and then ignored, and the request is never sent. The feature itself uses
// only stable VS Code API (`languages.registerInlineCompletionItemProvider`),
// so nothing here needs an API proposal (docs/features/inline-templates).
// Must happen before `start()`: features are registered at initialize time.
client.registerFeatures(ProposedFeatures.createAll(client));
context.subscriptions.push(client);
// Every colour is one this extension contributes, so every one of them has
// an opaque default in every theme kind: a theme that says nothing about
// `lucisv.rainbowN` gets our default, and a theme or user that overrides it
// gets what they asked for. Nothing here may ever be transparent — the
// rainbow colours code, it never hides it.
decorationTypes = Array.from({ length: RAINBOW_COLORS }, (_, index) =>
vscode.window.createTextEditorDecorationType({
color: new vscode.ThemeColor(`lucisv.rainbow${index + 1}`),
}),
);
// Half a pair has no nesting level and therefore no rainbow colour. It is
// still real text, so it is painted in the error colour rather than left
// undecorated: a `begin` that lost its `end` is exactly what the user wants
// to see.
unmatchedType = vscode.window.createTextEditorDecorationType({
color: new vscode.ThemeColor('lucisv.rainbowUnmatched'),
});
context.subscriptions.push(...decorationTypes, unmatchedType);
rainbowEnabled = readRainbowSetting();
context.subscriptions.push(
// A new editor has no decorations of its own; paint it as it appears.
vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()),
// Covers splits, tab drags, and an editor becoming visible again.
vscode.window.onDidChangeVisibleTextEditors(() => repaintVisible()),
// Typing moves every range after the cursor, so the answer is stale the
// moment it arrives; debounce rather than ask on every keystroke.
vscode.workspace.onDidChangeTextDocument((event) => {
if (isVerilog(event.document)) scheduleRepaint();
}),
vscode.workspace.onDidChangeConfiguration((event) => {
if (!event.affectsConfiguration('lucisv.rainbowBeginEnd')) return;
rainbowEnabled = readRainbowSetting();
// Honoured immediately, both ways: turning it off has to take the
// colours away, or "off" would only mean "off after a reload".
repaintVisible();
}),
);
// Closing an editor disposes its decorations with it, so there is nothing to
// clear on close; the only explicit clearing is turning the setting off,
// which `repaintVisible` does by painting empty ranges.
client.start().then(
() => repaintVisible(),
// The client reports a server that will not start, in its own output
// channel and its own words. Decorations are cosmetic; there is nothing
// useful to add here, and a second error popup would only be noise.
() => {},
);
}
/** Stop the server; VS Code waits on the returned promise. */
function deactivate() {
clearTimeout(repaintTimer);
return client ? client.stop() : undefined;
}
/** True for the documents this extension knows about. */
function isVerilog(document) {
return LANGUAGES.includes(document.languageId);
}
function readRainbowSetting() {
return vscode.workspace.getConfiguration('lucisv').get('rainbowBeginEnd') !== false;
}
/** Coalesce a burst of edits into one repaint. */
function scheduleRepaint() {
clearTimeout(repaintTimer);
repaintTimer = setTimeout(() => repaintVisible(), REPAINT_DEBOUNCE_MS);
}
/** Repaint every visible Verilog editor. */
function repaintVisible() {
for (const editor of vscode.window.visibleTextEditors) {
if (isVerilog(editor.document)) paint(editor);
}
}
/**
* Ask the server where this buffer's blocks are and colour them by depth.
*
* Turning the rainbow off paints empty ranges rather than skipping the editor:
* `setDecorations` with `[]` is how a decoration type is removed, so "off" and
* "no blocks here" are the same operation.
*/
async function paint(editor) {
const document = editor.document;
const askedAbout = document.version;
const buckets = decorationTypes.map(() => []);
const unmatched = [];
if (rainbowEnabled) {
let result;
try {
result = await client.sendRequest('lucisv/scopePairs', {
textDocument: { uri: document.uri.toString() },
});
} catch {
// The server is gone, restarting, or older than this extension. The
// client says so where it says everything else; leaving the old colours
// alone is better than blanking the file over a transient failure.
return;
}
// The answer describes the version we asked about. If the user typed while
// it was in flight, every range after the edit is now wrong — drop it and
// let the debounced repaint that the edit already scheduled do the work.
if (document.version !== askedAbout) return;
// The editor may have been closed while the request was in flight.
if (!vscode.window.visibleTextEditors.includes(editor)) return;
for (const pair of (result && result.pairs) || []) {
// `depth` is a `u32` from our own server; a server that answered
// anything else would otherwise index the buckets with `NaN`.
const depth = Number.isInteger(pair.depth) && pair.depth >= 0 ? pair.depth : 0;
const ranges = buckets[depth % RAINBOW_COLORS];
ranges.push(asRange(pair.open), asRange(pair.close));
}
// A server older than this extension answers without the field; `|| []`
// is what lets that pairing keep the rainbow and simply skip the reds.
for (const range of (result && result.unmatched) || []) {
unmatched.push(asRange(range));
}
}
for (const [index, ranges] of buckets.entries()) {
editor.setDecorations(decorationTypes[index], ranges);
}
editor.setDecorations(unmatchedType, unmatched);
}
/** An LSP range (UTF-16, which is what the server advertises) as a VS Code one. */
function asRange(range) {
return client.protocol2CodeConverter.asRange(range);
}
module.exports = { activate, deactivate };