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