// Author: Guoliang Chen, a Senior Digital Design Engineer // 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'); const { createRestarter } = require('./restart'); const { executeCommand } = require('./extract'); const { HierarchyView } = require('./hierarchyView'); const { ReferencesView } = require('./referencesView'); const typing = require('./typing'); const { CommentKeywords } = require('./commentKeywords'); const mcp = require('./mcp'); /** The single client, kept only so `deactivate` can stop it. */ let client; /** * The one thing that starts or restarts the server, so that no two transitions * ever overlap. Created in `activate`; see `restart.js`. */ let restarter; /** The instance-oriented design hierarchy hosted in lucisv's sidebar. */ let hierarchyView; /** 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/` — a **platform package**, stamped with vsce's `--target`, so * its `bin/` is flat and holds exactly one platform's binaries. * 2. `bin/-/` — 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'; // `lucisv-server` needs no arguments and speaks LSP on stdin/stdout — // `editors/vscode/smoke.js` spawns it exactly that way. The one argument it // takes is `--verbose`, and only when the user asked for it // (docs/features/verbose-timing/README.md). The object is kept so the // restart below can put new arguments in it: every `start()` reads it // afresh. const serverOptions = { command: serverPath, args: serverArgs(), 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' }, // Where the server may keep its index cache, so that reopening a // workspace does not re-parse every file it already parsed last time // (docs/features/index-persistence/README.md). `storageUri` is VS Code's // own per-workspace folder for exactly this kind of state — it is // cleaned up when the workspace is forgotten, which is what makes it a // better answer than a directory the server would have to invent. It is // `undefined` when no workspace is open, and then the global one stands // in; the server falls back to this platform's cache directory if // neither reaches it, and to no cache at all if it cannot work one out. initializationOptions: { storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath, // Opt into the custom invalidation notification. Other LSP clients can // still request a snapshot, but receive no unsolicited lucisv traffic. hierarchyView: true, }, // The one place this extension steps between a server command and the // server. `lucisv.extractModule` needs a name for the new module and LSP // has no prompt, so the server's code action carries the command with a // default name and this asks the user for a better one before it goes out // (docs/features/extract-inline-module/README.md). Every other command // passes through untouched. It has to be middleware rather than a command // of our own: the language client registers every command the server // advertises, so a second registration of the same id would collide with // it at activation. middleware: { // `selectedCompletionInfo` as LSP spells it — the keyword ghost follows // the popup's selected entry, and the client would otherwise send VS // Code's own Range shape (docs/features/completion-ux, `typing.js`). provideInlineCompletionItems: (document, position, context, token, next) => next(document, position, typing.protocolInlineContext(context), token), executeCommand: (command, args, next) => executeCommand( { showInputBox: (options) => vscode.window.showInputBox(options) }, command, args, next, ), }, }; 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); 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. restarter = createRestarter({ client, serverOptions, onStarted: () => { repaintVisible(); hierarchyView.onStarted(); }, onStartFailed: reportStartFailure, }); // 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(); // TODO/FIXME/FIX_ME/TBD and `lucisv.commentKeywords.custom` inside comments // (docs/features/comment-highlighting). Client-side only: it needs nothing // from the server, so it paints even while the server is starting. new CommentKeywords(vscode, isVerilog, (line) => client.outputChannel.appendLine(line)) .activate(context.subscriptions); context.subscriptions.push( // A new editor has no decorations of its own; paint it as it appears. vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()), // 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)) return; scheduleRepaint(); // `begin` + Enter writes the `end` (docs/features/completion-ux). Next // tick, so the language client's own listener has sent this change // before the request about it goes out. setTimeout(() => typing.handleChange(autoEndDeps, event), 0); }), vscode.workspace.onDidChangeConfiguration((event) => { // A spawn argument can only change by spawning again, so this one // setting restarts the server. Nothing else here does. What the toggle // wants is recorded *now*, synchronously; the restarter decides when it // can act, and reconciles to whatever was asked for last. if (event.affectsConfiguration('lucisv.verbose')) restarter.want(serverArgs()); 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. // The first spawn goes through the restarter rather than around it, and that // is the whole of the fix for QA finding 1: a `lucisv.verbose` toggle that // lands while this start is still in flight — a large workspace's first scan // can hold it for a while — queues behind it instead of racing it, and is // then reconciled by a real restart. Calling `client.start()` here directly // would put one transition outside the chain again. restarter.start(); mcp.activate(context, { bundledBinary, outputChannel: client.outputChannel }); } /** Stop the server; VS Code waits on the returned promise. */ function deactivate() { clearTimeout(repaintTimer); // Through the restarter, never around it. A `client.stop()` here would be a // transition outside the chain — and a `lucisv.verbose` toggle landing in the // same tick would queue a whole reconcile *beside* it, spawning a server with // nothing left to await or stop it (QA finding 3). `dispose()` shuts the door // first, so any such toggle is a no-op, and puts the final stop on the same // chain as everything else. No client means no restarter and nothing spawned: // every start this extension makes goes through one of them. return restarter ? restarter.dispose() : undefined; } /** * What `typing.handleChange` needs from VS Code and the client. The edits are * applied with no undo stop before them, so they join the Enter's own undo * step where VS Code allows it. */ const autoEndDeps = { editorFor: (document) => vscode.window.visibleTextEditors.find((editor) => editor.document === document), formatOnType: (document) => vscode.workspace.getConfiguration('editor', document).get('formatOnType') === true, autoEnd: (document) => vscode.workspace.getConfiguration('lucisv', document).get('autoEnd') !== false, request: (document, position, editor) => client.sendRequest('textDocument/onTypeFormatting', { textDocument: { uri: document.uri.toString() }, position, ch: '\n', options: { tabSize: Number(editor.options.tabSize) || 2, insertSpaces: editor.options.insertSpaces !== false, }, }), apply: async (editor, edits) => { const converted = await client.protocol2CodeConverter.asTextEdits(edits); return editor.edit( (builder) => { for (const edit of converted || []) builder.replace(edit.range, edit.newText); }, { undoStopBefore: false, undoStopAfter: true }, ); }, placeCursor: (editor, line) => { const end = editor.document.lineAt(line).range.end; editor.selection = new vscode.Selection(end, end); }, }; /** 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; } /** * The arguments to spawn the server with: `--verbose` when `lucisv.verbose` is * on, and none otherwise — which is the spawn every version before this used. * * `=== true` rather than a truthy test: the setting is a boolean, and anything * else in it is somebody's mistake, not a request for a noisy log. */ function serverArgs() { return vscode.workspace.getConfiguration('lucisv').get('verbose') === true ? ['--verbose'] : []; } /** * A server that would not start — at activation or at a `lucisv.verbose` * restart, which is why both go through here rather than through an anonymous * `catch {}` that drops it. * * The language client says plenty about a server that will not spawn, in its * own output channel and its own words, so there is no popup here: at * activation there never was one, and a restart is not more alarming. What it * does *not* say is that a toggle asked for this, so one line goes into the * same channel the user is already reading. The restart chain survives, so the * next toggle tries again. */ function reportStartFailure(error) { const reason = (error && error.message) || error; try { client.outputChannel.appendLine(`lucisv: the server did not start: ${reason}`); } catch { // No channel to write to — no client yet, or one already disposed. The // client's own report is then all there is, which is exactly what // activation has always given. } } /** 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 }; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com