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';
16 import { activateTaskProvider } from './tasks';
18 let ctx: Ctx | undefined;
20 export async function activate(context: vscode.ExtensionContext) {
21 // Register a "dumb" onEnter command for the case where server fails to
24 // FIXME: refactor command registration code such that commands are
25 // **always** registered, even if the server does not start. Use API like
30 // factory: (Ctx) => ((Ctx) => any),
31 // fallback: () => any = () => vscode.window.showErrorMessage(
32 // "rust-analyzer is not available"
35 const defaultOnEnter = vscode.commands.registerCommand(
36 'rust-analyzer.onEnter',
37 () => vscode.commands.executeCommand('default:type', { text: '\n' }),
39 context.subscriptions.push(defaultOnEnter);
41 const config = new Config(context);
42 const state = new PersistentState(context.globalState);
43 const serverPath = await bootstrap(config, state);
45 const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
46 if (workspaceFolder === undefined) {
47 const err = "Cannot activate rust-analyzer when no folder is opened";
48 void vscode.window.showErrorMessage(err);
52 // Note: we try to start the server before we activate type hints so that it
53 // registers its `onDidChangeDocument` handler before us.
55 // This a horribly, horribly wrong way to deal with this problem.
56 ctx = await Ctx.create(config, context, serverPath, workspaceFolder);
58 // Commands which invokes manually via command palette, shortcut, etc.
60 // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
61 ctx.registerCommand('reload', _ => async () => {
62 void vscode.window.showInformationMessage('Reloading rust-analyzer...');
64 while (context.subscriptions.length > 0) {
66 context.subscriptions.pop()!.dispose();
68 log.error("Dispose error:", err);
71 await activate(context).catch(log.error);
74 ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
75 ctx.registerCommand('collectGarbage', commands.collectGarbage);
76 ctx.registerCommand('matchingBrace', commands.matchingBrace);
77 ctx.registerCommand('joinLines', commands.joinLines);
78 ctx.registerCommand('parentModule', commands.parentModule);
79 ctx.registerCommand('syntaxTree', commands.syntaxTree);
80 ctx.registerCommand('expandMacro', commands.expandMacro);
81 ctx.registerCommand('run', commands.run);
83 defaultOnEnter.dispose();
84 ctx.registerCommand('onEnter', commands.onEnter);
86 ctx.registerCommand('ssr', commands.ssr);
87 ctx.registerCommand('serverVersion', commands.serverVersion);
89 // Internal commands which are invoked by the server.
90 ctx.registerCommand('runSingle', commands.runSingle);
91 ctx.registerCommand('debugSingle', commands.debugSingle);
92 ctx.registerCommand('showReferences', commands.showReferences);
93 ctx.registerCommand('applySourceChange', commands.applySourceChange);
94 ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
96 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
98 activateStatusDisplay(ctx);
100 if (!ctx.config.highlightingSemanticTokens) {
101 activateHighlighting(ctx);
103 activateInlayHints(ctx);
105 vscode.workspace.onDidChangeConfiguration(
106 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
112 export async function deactivate() {
113 await ctx?.client.stop();
117 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
118 await fs.mkdir(config.globalStoragePath, { recursive: true });
120 await bootstrapExtension(config, state);
121 const path = await bootstrapServer(config, state);
126 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
127 if (config.package.releaseTag === null) return;
128 if (config.channel === "stable") {
129 if (config.package.releaseTag === NIGHTLY_TAG) {
130 void vscode.window.showWarningMessage(
131 `You are running a nightly version of rust-analyzer extension. ` +
132 `To switch to stable, uninstall the extension and re-install it from the marketplace`
138 const lastCheck = state.lastCheck;
139 const now = Date.now();
141 const anHour = 60 * 60 * 1000;
142 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
144 if (!shouldDownloadNightly) return;
146 const release = await fetchRelease("nightly").catch((e) => {
148 if (state.releaseId === undefined) { // Show error only for the initial download
149 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
153 if (release === undefined || release.id === state.releaseId) return;
155 const userResponse = await vscode.window.showInformationMessage(
156 "New version of rust-analyzer (nightly) is available (requires reload).",
159 if (userResponse !== "Update") return;
161 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
162 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
164 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
165 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
167 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
168 await fs.unlink(dest);
170 await state.updateReleaseId(release.id);
171 await state.updateLastCheck(now);
172 await vscode.commands.executeCommand("workbench.action.reloadWindow");
175 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
176 const path = await getServer(config, state);
179 "Rust Analyzer Language Server is not available. " +
180 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
184 const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
185 log.debug("Checked binary availability via --version", res);
186 log.debug(res, "--version output:", res.output);
187 if (res.status !== 0) {
188 throw new Error(`Failed to execute ${path} --version`);
194 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
195 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
197 if (explicitPath.startsWith("~/")) {
198 return os.homedir() + explicitPath.slice("~".length);
202 if (config.package.releaseTag === null) return "rust-analyzer";
204 let binaryName: string | undefined = undefined;
205 if (process.arch === "x64" || process.arch === "ia32") {
206 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
207 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
208 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
210 if (binaryName === undefined) {
211 vscode.window.showErrorMessage(
212 "Unfortunately we don't ship binaries for your platform yet. " +
213 "You need to manually clone rust-analyzer repository and " +
214 "run `cargo xtask install --server` to build the language server from sources. " +
215 "If you feel that your platform should be supported, please create an issue " +
216 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
222 const dest = path.join(config.globalStoragePath, binaryName);
223 const exists = await fs.stat(dest).then(() => true, () => false);
225 await state.updateServerVersion(undefined);
228 if (state.serverVersion === config.package.version) return dest;
230 if (config.askBeforeDownload) {
231 const userResponse = await vscode.window.showInformationMessage(
232 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
235 if (userResponse !== "Download now") return dest;
238 const release = await fetchRelease(config.package.releaseTag);
239 const artifact = release.assets.find(artifact => artifact.name === binaryName);
240 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
242 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
243 await state.updateServerVersion(config.package.version);