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 { Config, NIGHTLY_TAG } from './config';
11 import { log, assert, isValidExecutable } from './util';
12 import { PersistentState } from './persistent_state';
13 import { fetchRelease, download } from './net';
14 import { activateTaskProvider } from './tasks';
16 let ctx: Ctx | undefined;
18 export async function activate(context: vscode.ExtensionContext) {
19 // Register a "dumb" onEnter command for the case where server fails to
22 // FIXME: refactor command registration code such that commands are
23 // **always** registered, even if the server does not start. Use API like
28 // factory: (Ctx) => ((Ctx) => any),
29 // fallback: () => any = () => vscode.window.showErrorMessage(
30 // "rust-analyzer is not available"
33 const defaultOnEnter = vscode.commands.registerCommand(
34 'rust-analyzer.onEnter',
35 () => vscode.commands.executeCommand('default:type', { text: '\n' }),
37 context.subscriptions.push(defaultOnEnter);
39 const config = new Config(context);
40 const state = new PersistentState(context.globalState);
41 const serverPath = await bootstrap(config, state);
43 const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
44 if (workspaceFolder === undefined) {
45 const err = "Cannot activate rust-analyzer when no folder is opened";
46 void vscode.window.showErrorMessage(err);
50 // Note: we try to start the server before we activate type hints so that it
51 // registers its `onDidChangeDocument` handler before us.
53 // This a horribly, horribly wrong way to deal with this problem.
54 ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath);
56 // Commands which invokes manually via command palette, shortcut, etc.
58 // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
59 ctx.registerCommand('reload', _ => async () => {
60 void vscode.window.showInformationMessage('Reloading rust-analyzer...');
62 while (context.subscriptions.length > 0) {
64 context.subscriptions.pop()!.dispose();
66 log.error("Dispose error:", err);
69 await activate(context).catch(log.error);
72 ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
73 ctx.registerCommand('collectGarbage', commands.collectGarbage);
74 ctx.registerCommand('matchingBrace', commands.matchingBrace);
75 ctx.registerCommand('joinLines', commands.joinLines);
76 ctx.registerCommand('parentModule', commands.parentModule);
77 ctx.registerCommand('syntaxTree', commands.syntaxTree);
78 ctx.registerCommand('expandMacro', commands.expandMacro);
79 ctx.registerCommand('run', commands.run);
80 ctx.registerCommand('debug', commands.debug);
81 ctx.registerCommand('newDebugConfig', commands.newDebugConfig);
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('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
95 ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
97 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
99 activateStatusDisplay(ctx);
101 activateInlayHints(ctx);
103 vscode.workspace.onDidChangeConfiguration(
104 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
110 export async function deactivate() {
111 await ctx?.client.stop();
115 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
116 await fs.mkdir(config.globalStoragePath, { recursive: true });
118 await bootstrapExtension(config, state);
119 const path = await bootstrapServer(config, state);
124 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
125 if (config.package.releaseTag === null) return;
126 if (config.channel === "stable") {
127 if (config.package.releaseTag === NIGHTLY_TAG) {
128 void vscode.window.showWarningMessage(
129 `You are running a nightly version of rust-analyzer extension. ` +
130 `To switch to stable, uninstall the extension and re-install it from the marketplace`
136 const lastCheck = state.lastCheck;
137 const now = Date.now();
139 const anHour = 60 * 60 * 1000;
140 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
142 if (!shouldDownloadNightly) return;
144 const release = await fetchRelease("nightly").catch((e) => {
146 if (state.releaseId === undefined) { // Show error only for the initial download
147 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
151 if (release === undefined || release.id === state.releaseId) return;
153 const userResponse = await vscode.window.showInformationMessage(
154 "New version of rust-analyzer (nightly) is available (requires reload).",
157 if (userResponse !== "Update") return;
159 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
160 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
162 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
163 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
165 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
166 await fs.unlink(dest);
168 await state.updateReleaseId(release.id);
169 await state.updateLastCheck(now);
170 await vscode.commands.executeCommand("workbench.action.reloadWindow");
173 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
174 const path = await getServer(config, state);
177 "Rust Analyzer Language Server is not available. " +
178 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
182 log.debug("Using server binary at", path);
184 if (!isValidExecutable(path)) {
185 throw new Error(`Failed to execute ${path} --version`);
191 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
192 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
194 if (explicitPath.startsWith("~/")) {
195 return os.homedir() + explicitPath.slice("~".length);
199 if (config.package.releaseTag === null) return "rust-analyzer";
201 let binaryName: string | undefined = undefined;
202 if (process.arch === "x64" || process.arch === "ia32") {
203 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
204 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
205 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
207 if (binaryName === undefined) {
208 vscode.window.showErrorMessage(
209 "Unfortunately we don't ship binaries for your platform yet. " +
210 "You need to manually clone rust-analyzer repository and " +
211 "run `cargo xtask install --server` to build the language server from sources. " +
212 "If you feel that your platform should be supported, please create an issue " +
213 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
219 const dest = path.join(config.globalStoragePath, binaryName);
220 const exists = await fs.stat(dest).then(() => true, () => false);
222 await state.updateServerVersion(undefined);
225 if (state.serverVersion === config.package.version) return dest;
227 if (config.askBeforeDownload) {
228 const userResponse = await vscode.window.showInformationMessage(
229 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
232 if (userResponse !== "Download now") return dest;
235 const release = await fetchRelease(config.package.releaseTag);
236 const artifact = release.assets.find(artifact => artifact.name === binaryName);
237 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
239 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
240 await state.updateServerVersion(config.package.version);