1 import * as vscode from 'vscode';
2 import * as path from "path";
3 import * as os from "os";
4 import { promises as fs } from "fs";
6 import * as commands from './commands';
7 import { activateInlayHints } from './inlay_hints';
8 import { activateStatusDisplay } from './status_display';
9 import { Ctx } from './ctx';
10 import { activateHighlighting } from './highlighting';
11 import { Config, NIGHTLY_TAG } from './config';
12 import { log, assert } from './util';
13 import { PersistentState } from './persistent_state';
14 import { fetchRelease, download } from './net';
15 import { spawnSync } from 'child_process';
17 let ctx: Ctx | undefined;
19 export async function activate(context: vscode.ExtensionContext) {
20 // Register a "dumb" onEnter command for the case where server fails to
23 // FIXME: refactor command registration code such that commands are
24 // **always** registered, even if the server does not start. Use API like
29 // factory: (Ctx) => ((Ctx) => any),
30 // fallback: () => any = () => vscode.window.showErrorMessage(
31 // "rust-analyzer is not available"
34 const defaultOnEnter = vscode.commands.registerCommand(
35 'rust-analyzer.onEnter',
36 () => vscode.commands.executeCommand('default:type', { text: '\n' }),
38 context.subscriptions.push(defaultOnEnter);
40 const config = new Config(context);
41 const state = new PersistentState(context.globalState);
42 const serverPath = await bootstrap(config, state);
44 // Note: we try to start the server before we activate type hints so that it
45 // registers its `onDidChangeDocument` handler before us.
47 // This a horribly, horribly wrong way to deal with this problem.
48 ctx = await Ctx.create(config, context, serverPath);
50 // Commands which invokes manually via command palette, shortcut, etc.
52 // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
53 ctx.registerCommand('reload', _ => async () => {
54 void vscode.window.showInformationMessage('Reloading rust-analyzer...');
56 while (context.subscriptions.length > 0) {
58 context.subscriptions.pop()!.dispose();
60 log.error("Dispose error:", err);
63 await activate(context).catch(log.error);
66 ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
67 ctx.registerCommand('collectGarbage', commands.collectGarbage);
68 ctx.registerCommand('matchingBrace', commands.matchingBrace);
69 ctx.registerCommand('joinLines', commands.joinLines);
70 ctx.registerCommand('parentModule', commands.parentModule);
71 ctx.registerCommand('syntaxTree', commands.syntaxTree);
72 ctx.registerCommand('expandMacro', commands.expandMacro);
73 ctx.registerCommand('run', commands.run);
75 defaultOnEnter.dispose();
76 ctx.registerCommand('onEnter', commands.onEnter);
78 ctx.registerCommand('ssr', commands.ssr);
79 ctx.registerCommand('serverVersion', commands.serverVersion);
81 // Internal commands which are invoked by the server.
82 ctx.registerCommand('runSingle', commands.runSingle);
83 ctx.registerCommand('debugSingle', commands.debugSingle);
84 ctx.registerCommand('showReferences', commands.showReferences);
85 ctx.registerCommand('applySourceChange', commands.applySourceChange);
86 ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
88 activateStatusDisplay(ctx);
90 if (!ctx.config.highlightingSemanticTokens) {
91 activateHighlighting(ctx);
93 activateInlayHints(ctx);
95 vscode.workspace.onDidChangeConfiguration(
96 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
102 export async function deactivate() {
103 await ctx?.client.stop();
107 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
108 await fs.mkdir(config.globalStoragePath, { recursive: true });
110 await bootstrapExtension(config, state);
111 const path = await bootstrapServer(config, state);
116 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
117 if (config.package.releaseTag === null) return;
118 if (config.channel === "stable") {
119 if (config.package.releaseTag === NIGHTLY_TAG) {
120 void vscode.window.showWarningMessage(
121 `You are running a nightly version of rust-analyzer extension. ` +
122 `To switch to stable, uninstall the extension and re-install it from the marketplace`
128 const lastCheck = state.lastCheck;
129 const now = Date.now();
131 const anHour = 60 * 60 * 1000;
132 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
134 if (!shouldDownloadNightly) return;
136 const release = await fetchRelease("nightly").catch((e) => {
138 if (state.releaseId === undefined) { // Show error only for the initial download
139 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
143 if (release === undefined || release.id === state.releaseId) return;
145 const userResponse = await vscode.window.showInformationMessage(
146 "New version of rust-analyzer (nightly) is available (requires reload).",
149 if (userResponse !== "Update") return;
151 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
152 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
154 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
155 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
157 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
158 await fs.unlink(dest);
160 await state.updateReleaseId(release.id);
161 await state.updateLastCheck(now);
162 await vscode.commands.executeCommand("workbench.action.reloadWindow");
165 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
166 const path = await getServer(config, state);
169 "Rust Analyzer Language Server is not available. " +
170 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
174 const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
175 log.debug("Checked binary availability via --version", res);
176 log.debug(res, "--version output:", res.output);
177 if (res.status !== 0) {
178 throw new Error(`Failed to execute ${path} --version`);
184 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
185 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
187 if (explicitPath.startsWith("~/")) {
188 return os.homedir() + explicitPath.slice("~".length);
192 if (config.package.releaseTag === null) return "rust-analyzer";
194 let binaryName: string | undefined = undefined;
195 if (process.arch === "x64" || process.arch === "ia32") {
196 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
197 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
198 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
200 if (binaryName === undefined) {
201 vscode.window.showErrorMessage(
202 "Unfortunately we don't ship binaries for your platform yet. " +
203 "You need to manually clone rust-analyzer repository and " +
204 "run `cargo xtask install --server` to build the language server from sources. " +
205 "If you feel that your platform should be supported, please create an issue " +
206 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
212 const dest = path.join(config.globalStoragePath, binaryName);
213 const exists = await fs.stat(dest).then(() => true, () => false);
215 await state.updateServerVersion(undefined);
218 if (state.serverVersion === config.package.version) return dest;
220 if (config.askBeforeDownload) {
221 const userResponse = await vscode.window.showInformationMessage(
222 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
225 if (userResponse !== "Download now") return dest;
228 const release = await fetchRelease(config.package.releaseTag);
229 const artifact = release.assets.find(artifact => artifact.name === binaryName);
230 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
232 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
233 await state.updateServerVersion(config.package.version);