]> git.lizzy.rs Git - rust.git/blob - editors/code/src/main.ts
16a94fceb1bc80f363aa23a97f1d6ca2782dbb1e
[rust.git] / editors / code / src / main.ts
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";
5
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';
16
17 let ctx: Ctx | undefined;
18
19 const RUST_PROJECT_CONTEXT_NAME = "inRustProject";
20
21 export async function activate(context: vscode.ExtensionContext) {
22     // Register a "dumb" onEnter command for the case where server fails to
23     // start.
24     //
25     // FIXME: refactor command registration code such that commands are
26     // **always** registered, even if the server does not start. Use API like
27     // this perhaps?
28     //
29     // ```TypeScript
30     // registerCommand(
31     //    factory: (Ctx) => ((Ctx) => any),
32     //    fallback: () => any = () => vscode.window.showErrorMessage(
33     //        "rust-analyzer is not available"
34     //    ),
35     // )
36     const defaultOnEnter = vscode.commands.registerCommand(
37         'rust-analyzer.onEnter',
38         () => vscode.commands.executeCommand('default:type', { text: '\n' }),
39     );
40     context.subscriptions.push(defaultOnEnter);
41
42     const config = new Config(context);
43     const state = new PersistentState(context.globalState);
44     const serverPath = await bootstrap(config, state);
45
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);
50         throw new Error(err);
51     }
52
53     // Note: we try to start the server before we activate type hints so that it
54     // registers its `onDidChangeDocument` handler before us.
55     //
56     // This a horribly, horribly wrong way to deal with this problem.
57     ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath);
58
59     setContextValue(RUST_PROJECT_CONTEXT_NAME, true);
60
61     // Commands which invokes manually via command palette, shortcut, etc.
62
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...');
66         await deactivate();
67         while (context.subscriptions.length > 0) {
68             try {
69                 context.subscriptions.pop()!.dispose();
70             } catch (err) {
71                 log.error("Dispose error:", err);
72             }
73         }
74         await activate(context).catch(log.error);
75     });
76
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);
87
88     defaultOnEnter.dispose();
89     ctx.registerCommand('onEnter', commands.onEnter);
90
91     ctx.registerCommand('ssr', commands.ssr);
92     ctx.registerCommand('serverVersion', commands.serverVersion);
93     ctx.registerCommand('toggleInlayHints', commands.toggleInlayHints);
94
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);
102
103     ctx.pushCleanup(activateTaskProvider(workspaceFolder));
104
105     activateInlayHints(ctx);
106
107     vscode.workspace.onDidChangeConfiguration(
108         _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
109         null,
110         ctx.subscriptions,
111     );
112 }
113
114 export async function deactivate() {
115     setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
116     await ctx?.client.stop();
117     ctx = undefined;
118 }
119
120 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
121     await fs.mkdir(config.globalStoragePath, { recursive: true });
122
123     await bootstrapExtension(config, state);
124     const path = await bootstrapServer(config, state);
125
126     return path;
127 }
128
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`
136             );
137         }
138         return;
139     };
140
141     const lastCheck = state.lastCheck;
142     const now = Date.now();
143
144     const anHour = 60 * 60 * 1000;
145     const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
146
147     if (!shouldDownloadNightly) return;
148
149     const release = await fetchRelease("nightly").catch((e) => {
150         log.error(e);
151         if (state.releaseId === undefined) { // Show error only for the initial download
152             vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
153         }
154         return undefined;
155     });
156     if (release === undefined || release.id === state.releaseId) return;
157
158     const userResponse = await vscode.window.showInformationMessage(
159         "New version of rust-analyzer (nightly) is available (requires reload).",
160         "Update"
161     );
162     if (userResponse !== "Update") return;
163
164     const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
165     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
166
167     const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
168     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
169
170     await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
171     await fs.unlink(dest);
172
173     await state.updateReleaseId(release.id);
174     await state.updateLastCheck(now);
175     await vscode.commands.executeCommand("workbench.action.reloadWindow");
176 }
177
178 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
179     const path = await getServer(config, state);
180     if (!path) {
181         throw new Error(
182             "Rust Analyzer Language Server is not available. " +
183             "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
184         );
185     }
186
187     log.debug("Using server binary at", path);
188
189     if (!isValidExecutable(path)) {
190         throw new Error(`Failed to execute ${path} --version`);
191     }
192
193     return path;
194 }
195
196 async function patchelf(dest: PathLike): Promise<void> {
197     await vscode.window.withProgress(
198         {
199             location: vscode.ProgressLocation.Notification,
200             title: "Patching rust-analyzer for NixOS"
201         },
202         async (progress, _) => {
203             const expression = `
204             {src, pkgs ? import <nixpkgs> {}}:
205                 pkgs.stdenv.mkDerivation {
206                     name = "rust-analyzer";
207                     inherit src;
208                     phases = [ "installPhase" "fixupPhase" ];
209                     installPhase = "cp $src $out";
210                     fixupPhase = ''
211                     chmod 755 $out
212                     patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
213                     '';
214                 }
215             `;
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) => {
222                         if (err != null) {
223                             reject(Error(stderr));
224                         } else {
225                             resolve(stdout);
226                         }
227                     });
228                 handle.stdin?.write(expression);
229                 handle.stdin?.end();
230             });
231             await fs.unlink(origFile);
232         }
233     );
234 }
235
236 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
237     const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
238     if (explicitPath) {
239         if (explicitPath.startsWith("~/")) {
240             return os.homedir() + explicitPath.slice("~".length);
241         }
242         return explicitPath;
243     };
244     if (config.package.releaseTag === null) return "rust-analyzer";
245
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";
251     }
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 " +
259             "will consider it."
260         );
261         return undefined;
262     }
263
264     const dest = path.join(config.globalStoragePath, binaryName);
265     const exists = await fs.stat(dest).then(() => true, () => false);
266     if (!exists) {
267         await state.updateServerVersion(undefined);
268     }
269
270     if (state.serverVersion === config.package.version) return dest;
271
272     if (config.askBeforeDownload) {
273         const userResponse = await vscode.window.showInformationMessage(
274             `Language server version ${config.package.version} for rust-analyzer is not installed.`,
275             "Download now"
276         );
277         if (userResponse !== "Download now") return dest;
278     }
279
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)}`);
283
284     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
285
286     // Patching executable if that's NixOS.
287     if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) {
288         await patchelf(dest);
289     }
290
291     await state.updateServerVersion(config.package.version);
292     return dest;
293 }