1 import * as vscode from 'vscode';
2 import * as path from "path";
3 import * as os from "os";
4 import { promises as fs, PathLike } 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';
15 import { setContextValue } from './util';
16 import { exec } from 'child_process';
18 let ctx: Ctx | undefined;
20 const RUST_PROJECT_CONTEXT_NAME = "inRustProject";
22 export async function activate(context: vscode.ExtensionContext) {
23 // Register a "dumb" onEnter command for the case where server fails to
26 // FIXME: refactor command registration code such that commands are
27 // **always** registered, even if the server does not start. Use API like
32 // factory: (Ctx) => ((Ctx) => any),
33 // fallback: () => any = () => vscode.window.showErrorMessage(
34 // "rust-analyzer is not available"
37 const defaultOnEnter = vscode.commands.registerCommand(
38 'rust-analyzer.onEnter',
39 () => vscode.commands.executeCommand('default:type', { text: '\n' }),
41 context.subscriptions.push(defaultOnEnter);
43 const config = new Config(context);
44 const state = new PersistentState(context.globalState);
45 const serverPath = await bootstrap(config, state);
47 const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
48 if (workspaceFolder === undefined) {
49 const err = "Cannot activate rust-analyzer when no folder is opened";
50 void vscode.window.showErrorMessage(err);
54 // Note: we try to start the server before we activate type hints so that it
55 // registers its `onDidChangeDocument` handler before us.
57 // This a horribly, horribly wrong way to deal with this problem.
58 ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath);
60 setContextValue(RUST_PROJECT_CONTEXT_NAME, true);
62 // Commands which invokes manually via command palette, shortcut, etc.
64 // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
65 ctx.registerCommand('reload', _ => async () => {
66 void vscode.window.showInformationMessage('Reloading rust-analyzer...');
68 while (context.subscriptions.length > 0) {
70 context.subscriptions.pop()!.dispose();
72 log.error("Dispose error:", err);
75 await activate(context).catch(log.error);
78 ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
79 ctx.registerCommand('collectGarbage', commands.collectGarbage);
80 ctx.registerCommand('matchingBrace', commands.matchingBrace);
81 ctx.registerCommand('joinLines', commands.joinLines);
82 ctx.registerCommand('parentModule', commands.parentModule);
83 ctx.registerCommand('syntaxTree', commands.syntaxTree);
84 ctx.registerCommand('expandMacro', commands.expandMacro);
85 ctx.registerCommand('run', commands.run);
86 ctx.registerCommand('debug', commands.debug);
87 ctx.registerCommand('newDebugConfig', commands.newDebugConfig);
89 defaultOnEnter.dispose();
90 ctx.registerCommand('onEnter', commands.onEnter);
92 ctx.registerCommand('ssr', commands.ssr);
93 ctx.registerCommand('serverVersion', commands.serverVersion);
94 ctx.registerCommand('toggleInlayHints', commands.toggleInlayHints);
96 // Internal commands which are invoked by the server.
97 ctx.registerCommand('runSingle', commands.runSingle);
98 ctx.registerCommand('debugSingle', commands.debugSingle);
99 ctx.registerCommand('showReferences', commands.showReferences);
100 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
101 ctx.registerCommand('applyActionGroup', commands.applyActionGroup);
103 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
105 activateStatusDisplay(ctx);
107 activateInlayHints(ctx);
109 vscode.workspace.onDidChangeConfiguration(
110 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
116 export async function deactivate() {
117 setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
118 await ctx?.client.stop();
122 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
123 await fs.mkdir(config.globalStoragePath, { recursive: true });
125 await bootstrapExtension(config, state);
126 const path = await bootstrapServer(config, state);
131 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
132 if (config.package.releaseTag === null) return;
133 if (config.channel === "stable") {
134 if (config.package.releaseTag === NIGHTLY_TAG) {
135 void vscode.window.showWarningMessage(
136 `You are running a nightly version of rust-analyzer extension. ` +
137 `To switch to stable, uninstall the extension and re-install it from the marketplace`
143 const lastCheck = state.lastCheck;
144 const now = Date.now();
146 const anHour = 60 * 60 * 1000;
147 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
149 if (!shouldDownloadNightly) return;
151 const release = await fetchRelease("nightly").catch((e) => {
153 if (state.releaseId === undefined) { // Show error only for the initial download
154 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
158 if (release === undefined || release.id === state.releaseId) return;
160 const userResponse = await vscode.window.showInformationMessage(
161 "New version of rust-analyzer (nightly) is available (requires reload).",
164 if (userResponse !== "Update") return;
166 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
167 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
169 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
170 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
172 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
173 await fs.unlink(dest);
175 await state.updateReleaseId(release.id);
176 await state.updateLastCheck(now);
177 await vscode.commands.executeCommand("workbench.action.reloadWindow");
180 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
181 const path = await getServer(config, state);
184 "Rust Analyzer Language Server is not available. " +
185 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
189 log.debug("Using server binary at", path);
191 if (!isValidExecutable(path)) {
192 throw new Error(`Failed to execute ${path} --version`);
198 async function patchelf(dest: PathLike): Promise<void> {
199 await vscode.window.withProgress(
201 location: vscode.ProgressLocation.Notification,
202 title: "Patching rust-analyzer for NixOS"
204 async (progress, _) => {
206 {src, pkgs ? import <nixpkgs> {}}:
207 pkgs.stdenv.mkDerivation {
208 name = "rust-analyzer";
210 phases = [ "installPhase" "fixupPhase" ];
211 installPhase = "cp $src $out";
214 patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
218 const origFile = dest + "-orig";
219 await fs.rename(dest, origFile);
220 progress.report({ message: "Patching executable", increment: 20 });
221 await new Promise((resolve, reject) => {
222 const handle = exec(`nix-build -E - --arg src '${origFile}' -o ${dest}`,
223 (err, stdout, stderr) => {
225 reject(Error(stderr));
230 handle.stdin?.write(expression);
233 await fs.unlink(origFile);
238 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
239 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
241 if (explicitPath.startsWith("~/")) {
242 return os.homedir() + explicitPath.slice("~".length);
246 if (config.package.releaseTag === null) return "rust-analyzer";
248 let binaryName: string | undefined = undefined;
249 if (process.arch === "x64" || process.arch === "ia32") {
250 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
251 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
252 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
254 if (binaryName === undefined) {
255 vscode.window.showErrorMessage(
256 "Unfortunately we don't ship binaries for your platform yet. " +
257 "You need to manually clone rust-analyzer repository and " +
258 "run `cargo xtask install --server` to build the language server from sources. " +
259 "If you feel that your platform should be supported, please create an issue " +
260 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
266 const dest = path.join(config.globalStoragePath, binaryName);
267 const exists = await fs.stat(dest).then(() => true, () => false);
269 await state.updateServerVersion(undefined);
272 if (state.serverVersion === config.package.version) return dest;
274 if (config.askBeforeDownload) {
275 const userResponse = await vscode.window.showInformationMessage(
276 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
279 if (userResponse !== "Download now") return dest;
282 const release = await fetchRelease(config.package.releaseTag);
283 const artifact = release.assets.find(artifact => artifact.name === binaryName);
284 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
286 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
288 // Patching executable if that's NixOS.
289 if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) {
290 await patchelf(dest);
293 await state.updateServerVersion(config.package.version);