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('resolveCodeAction', commands.resolveCodeAction);
102 ctx.registerCommand('applyActionGroup', commands.applyActionGroup);
104 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
106 activateStatusDisplay(ctx);
108 activateInlayHints(ctx);
110 vscode.workspace.onDidChangeConfiguration(
111 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
117 export async function deactivate() {
118 setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
119 await ctx?.client.stop();
123 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
124 await fs.mkdir(config.globalStoragePath, { recursive: true });
126 await bootstrapExtension(config, state);
127 const path = await bootstrapServer(config, state);
132 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
133 if (config.package.releaseTag === null) return;
134 if (config.channel === "stable") {
135 if (config.package.releaseTag === NIGHTLY_TAG) {
136 void vscode.window.showWarningMessage(
137 `You are running a nightly version of rust-analyzer extension. ` +
138 `To switch to stable, uninstall the extension and re-install it from the marketplace`
144 const lastCheck = state.lastCheck;
145 const now = Date.now();
147 const anHour = 60 * 60 * 1000;
148 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
150 if (!shouldDownloadNightly) return;
152 const release = await fetchRelease("nightly").catch((e) => {
154 if (state.releaseId === undefined) { // Show error only for the initial download
155 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
159 if (release === undefined || release.id === state.releaseId) return;
161 const userResponse = await vscode.window.showInformationMessage(
162 "New version of rust-analyzer (nightly) is available (requires reload).",
165 if (userResponse !== "Update") return;
167 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
168 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
170 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
171 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
173 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
174 await fs.unlink(dest);
176 await state.updateReleaseId(release.id);
177 await state.updateLastCheck(now);
178 await vscode.commands.executeCommand("workbench.action.reloadWindow");
181 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
182 const path = await getServer(config, state);
185 "Rust Analyzer Language Server is not available. " +
186 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
190 log.debug("Using server binary at", path);
192 if (!isValidExecutable(path)) {
193 throw new Error(`Failed to execute ${path} --version`);
199 async function patchelf(dest: PathLike): Promise<void> {
200 await vscode.window.withProgress(
202 location: vscode.ProgressLocation.Notification,
203 title: "Patching rust-analyzer for NixOS"
205 async (progress, _) => {
207 {src, pkgs ? import <nixpkgs> {}}:
208 pkgs.stdenv.mkDerivation {
209 name = "rust-analyzer";
211 phases = [ "installPhase" "fixupPhase" ];
212 installPhase = "cp $src $out";
215 patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
219 const origFile = dest + "-orig";
220 await fs.rename(dest, origFile);
221 progress.report({ message: "Patching executable", increment: 20 });
222 await new Promise((resolve, reject) => {
223 const handle = exec(`nix-build -E - --arg src '${origFile}' -o ${dest}`,
224 (err, stdout, stderr) => {
226 reject(Error(stderr));
231 handle.stdin?.write(expression);
234 await fs.unlink(origFile);
239 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
240 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
242 if (explicitPath.startsWith("~/")) {
243 return os.homedir() + explicitPath.slice("~".length);
247 if (config.package.releaseTag === null) return "rust-analyzer";
249 let binaryName: string | undefined = undefined;
250 if (process.arch === "x64" || process.arch === "ia32") {
251 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
252 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
253 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
255 if (binaryName === undefined) {
256 vscode.window.showErrorMessage(
257 "Unfortunately we don't ship binaries for your platform yet. " +
258 "You need to manually clone rust-analyzer repository and " +
259 "run `cargo xtask install --server` to build the language server from sources. " +
260 "If you feel that your platform should be supported, please create an issue " +
261 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
267 const dest = path.join(config.globalStoragePath, binaryName);
268 const exists = await fs.stat(dest).then(() => true, () => false);
270 await state.updateServerVersion(undefined);
273 if (state.serverVersion === config.package.version) return dest;
275 if (config.askBeforeDownload) {
276 const userResponse = await vscode.window.showInformationMessage(
277 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
280 if (userResponse !== "Download now") return dest;
283 const release = await fetchRelease(config.package.releaseTag);
284 const artifact = release.assets.find(artifact => artifact.name === binaryName);
285 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
287 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
289 // Patching executable if that's NixOS.
290 if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) {
291 await patchelf(dest);
294 await state.updateServerVersion(config.package.version);