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 { Ctx } from './ctx';
9 import { Config, NIGHTLY_TAG } from './config';
10 import { log, assert, isValidExecutable } from './util';
11 import { PersistentState } from './persistent_state';
12 import { fetchRelease, download } from './net';
13 import { activateTaskProvider } from './tasks';
14 import { setContextValue } from './util';
15 import { exec } from 'child_process';
17 let ctx: Ctx | undefined;
19 const RUST_PROJECT_CONTEXT_NAME = "inRustProject";
21 export async function activate(context: vscode.ExtensionContext) {
22 // Register a "dumb" onEnter command for the case where server fails to
25 // FIXME: refactor command registration code such that commands are
26 // **always** registered, even if the server does not start. Use API like
31 // factory: (Ctx) => ((Ctx) => any),
32 // fallback: () => any = () => vscode.window.showErrorMessage(
33 // "rust-analyzer is not available"
36 const defaultOnEnter = vscode.commands.registerCommand(
37 'rust-analyzer.onEnter',
38 () => vscode.commands.executeCommand('default:type', { text: '\n' }),
40 context.subscriptions.push(defaultOnEnter);
42 const config = new Config(context);
43 const state = new PersistentState(context.globalState);
44 const serverPath = await bootstrap(config, state);
46 const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
47 if (workspaceFolder === undefined) {
48 const err = "Cannot activate rust-analyzer when no folder is opened";
49 void vscode.window.showErrorMessage(err);
53 // Note: we try to start the server before we activate type hints so that it
54 // registers its `onDidChangeDocument` handler before us.
56 // This a horribly, horribly wrong way to deal with this problem.
57 ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath);
59 setContextValue(RUST_PROJECT_CONTEXT_NAME, true);
61 // Commands which invokes manually via command palette, shortcut, etc.
63 // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
64 ctx.registerCommand('reload', _ => async () => {
65 void vscode.window.showInformationMessage('Reloading rust-analyzer...');
67 while (context.subscriptions.length > 0) {
69 context.subscriptions.pop()!.dispose();
71 log.error("Dispose error:", err);
74 await activate(context).catch(log.error);
77 ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
78 ctx.registerCommand('collectGarbage', commands.collectGarbage);
79 ctx.registerCommand('matchingBrace', commands.matchingBrace);
80 ctx.registerCommand('joinLines', commands.joinLines);
81 ctx.registerCommand('parentModule', commands.parentModule);
82 ctx.registerCommand('syntaxTree', commands.syntaxTree);
83 ctx.registerCommand('expandMacro', commands.expandMacro);
84 ctx.registerCommand('run', commands.run);
85 ctx.registerCommand('debug', commands.debug);
86 ctx.registerCommand('newDebugConfig', commands.newDebugConfig);
88 defaultOnEnter.dispose();
89 ctx.registerCommand('onEnter', commands.onEnter);
91 ctx.registerCommand('ssr', commands.ssr);
92 ctx.registerCommand('serverVersion', commands.serverVersion);
93 ctx.registerCommand('toggleInlayHints', commands.toggleInlayHints);
95 // Internal commands which are invoked by the server.
96 ctx.registerCommand('runSingle', commands.runSingle);
97 ctx.registerCommand('debugSingle', commands.debugSingle);
98 ctx.registerCommand('showReferences', commands.showReferences);
99 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
100 ctx.registerCommand('resolveCodeAction', commands.resolveCodeAction);
101 ctx.registerCommand('applyActionGroup', commands.applyActionGroup);
103 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
105 activateInlayHints(ctx);
107 vscode.workspace.onDidChangeConfiguration(
108 _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
114 export async function deactivate() {
115 setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
116 await ctx?.client.stop();
120 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
121 await fs.mkdir(config.globalStoragePath, { recursive: true });
123 await bootstrapExtension(config, state);
124 const path = await bootstrapServer(config, state);
129 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
130 if (config.package.releaseTag === null) return;
131 if (config.channel === "stable") {
132 if (config.package.releaseTag === NIGHTLY_TAG) {
133 void vscode.window.showWarningMessage(
134 `You are running a nightly version of rust-analyzer extension. ` +
135 `To switch to stable, uninstall the extension and re-install it from the marketplace`
141 const lastCheck = state.lastCheck;
142 const now = Date.now();
144 const anHour = 60 * 60 * 1000;
145 const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
147 if (!shouldDownloadNightly) return;
149 const release = await fetchRelease("nightly").catch((e) => {
151 if (state.releaseId === undefined) { // Show error only for the initial download
152 vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
156 if (release === undefined || release.id === state.releaseId) return;
158 const userResponse = await vscode.window.showInformationMessage(
159 "New version of rust-analyzer (nightly) is available (requires reload).",
162 if (userResponse !== "Update") return;
164 const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
165 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
167 const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
168 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
170 await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
171 await fs.unlink(dest);
173 await state.updateReleaseId(release.id);
174 await state.updateLastCheck(now);
175 await vscode.commands.executeCommand("workbench.action.reloadWindow");
178 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
179 const path = await getServer(config, state);
182 "Rust Analyzer Language Server is not available. " +
183 "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
187 log.debug("Using server binary at", path);
189 if (!isValidExecutable(path)) {
190 throw new Error(`Failed to execute ${path} --version`);
196 async function patchelf(dest: PathLike): Promise<void> {
197 await vscode.window.withProgress(
199 location: vscode.ProgressLocation.Notification,
200 title: "Patching rust-analyzer for NixOS"
202 async (progress, _) => {
204 {src, pkgs ? import <nixpkgs> {}}:
205 pkgs.stdenv.mkDerivation {
206 name = "rust-analyzer";
208 phases = [ "installPhase" "fixupPhase" ];
209 installPhase = "cp $src $out";
212 patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
216 const origFile = dest + "-orig";
217 await fs.rename(dest, origFile);
218 progress.report({ message: "Patching executable", increment: 20 });
219 await new Promise((resolve, reject) => {
220 const handle = exec(`nix-build -E - --arg src '${origFile}' -o ${dest}`,
221 (err, stdout, stderr) => {
223 reject(Error(stderr));
228 handle.stdin?.write(expression);
231 await fs.unlink(origFile);
236 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
237 const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
239 if (explicitPath.startsWith("~/")) {
240 return os.homedir() + explicitPath.slice("~".length);
244 if (config.package.releaseTag === null) return "rust-analyzer";
246 let binaryName: string | undefined = undefined;
247 if (process.arch === "x64" || process.arch === "ia32") {
248 if (process.platform === "linux") binaryName = "rust-analyzer-linux";
249 if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
250 if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
252 if (binaryName === undefined) {
253 vscode.window.showErrorMessage(
254 "Unfortunately we don't ship binaries for your platform yet. " +
255 "You need to manually clone rust-analyzer repository and " +
256 "run `cargo xtask install --server` to build the language server from sources. " +
257 "If you feel that your platform should be supported, please create an issue " +
258 "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
264 const dest = path.join(config.globalStoragePath, binaryName);
265 const exists = await fs.stat(dest).then(() => true, () => false);
267 await state.updateServerVersion(undefined);
270 if (state.serverVersion === config.package.version) return dest;
272 if (config.askBeforeDownload) {
273 const userResponse = await vscode.window.showInformationMessage(
274 `Language server version ${config.package.version} for rust-analyzer is not installed.`,
277 if (userResponse !== "Download now") return dest;
280 const release = await fetchRelease(config.package.releaseTag);
281 const artifact = release.assets.find(artifact => artifact.name === binaryName);
282 assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
284 await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
286 // Patching executable if that's NixOS.
287 if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) {
288 await patchelf(dest);
291 await state.updateServerVersion(config.package.version);