]> git.lizzy.rs Git - rust.git/blob - editors/code/src/main.ts
Merge pull request #4382 from woody77/json_cfgs
[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('applyActionGroup', commands.applyActionGroup);
102
103     ctx.pushCleanup(activateTaskProvider(workspaceFolder));
104
105     activateStatusDisplay(ctx);
106
107     activateInlayHints(ctx);
108
109     vscode.workspace.onDidChangeConfiguration(
110         _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
111         null,
112         ctx.subscriptions,
113     );
114 }
115
116 export async function deactivate() {
117     setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
118     await ctx?.client.stop();
119     ctx = undefined;
120 }
121
122 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
123     await fs.mkdir(config.globalStoragePath, { recursive: true });
124
125     await bootstrapExtension(config, state);
126     const path = await bootstrapServer(config, state);
127
128     return path;
129 }
130
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`
138             );
139         }
140         return;
141     };
142
143     const lastCheck = state.lastCheck;
144     const now = Date.now();
145
146     const anHour = 60 * 60 * 1000;
147     const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
148
149     if (!shouldDownloadNightly) return;
150
151     const release = await fetchRelease("nightly").catch((e) => {
152         log.error(e);
153         if (state.releaseId === undefined) { // Show error only for the initial download
154             vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
155         }
156         return undefined;
157     });
158     if (release === undefined || release.id === state.releaseId) return;
159
160     const userResponse = await vscode.window.showInformationMessage(
161         "New version of rust-analyzer (nightly) is available (requires reload).",
162         "Update"
163     );
164     if (userResponse !== "Update") return;
165
166     const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
167     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
168
169     const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
170     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
171
172     await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
173     await fs.unlink(dest);
174
175     await state.updateReleaseId(release.id);
176     await state.updateLastCheck(now);
177     await vscode.commands.executeCommand("workbench.action.reloadWindow");
178 }
179
180 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
181     const path = await getServer(config, state);
182     if (!path) {
183         throw new Error(
184             "Rust Analyzer Language Server is not available. " +
185             "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
186         );
187     }
188
189     log.debug("Using server binary at", path);
190
191     if (!isValidExecutable(path)) {
192         throw new Error(`Failed to execute ${path} --version`);
193     }
194
195     return path;
196 }
197
198 async function patchelf(dest: PathLike): Promise<void> {
199     await vscode.window.withProgress(
200         {
201             location: vscode.ProgressLocation.Notification,
202             title: "Patching rust-analyzer for NixOS"
203         },
204         async (progress, _) => {
205             const expression = `
206             {src, pkgs ? import <nixpkgs> {}}:
207                 pkgs.stdenv.mkDerivation {
208                     name = "rust-analyzer";
209                     inherit src;
210                     phases = [ "installPhase" "fixupPhase" ];
211                     installPhase = "cp $src $out";
212                     fixupPhase = ''
213                     chmod 755 $out
214                     patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
215                     '';
216                 }
217             `;
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) => {
224                         if (err != null) {
225                             reject(Error(stderr));
226                         } else {
227                             resolve(stdout);
228                         }
229                     });
230                 handle.stdin?.write(expression);
231                 handle.stdin?.end();
232             });
233             await fs.unlink(origFile);
234         }
235     );
236 }
237
238 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
239     const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
240     if (explicitPath) {
241         if (explicitPath.startsWith("~/")) {
242             return os.homedir() + explicitPath.slice("~".length);
243         }
244         return explicitPath;
245     };
246     if (config.package.releaseTag === null) return "rust-analyzer";
247
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";
253     }
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 " +
261             "will consider it."
262         );
263         return undefined;
264     }
265
266     const dest = path.join(config.globalStoragePath, binaryName);
267     const exists = await fs.stat(dest).then(() => true, () => false);
268     if (!exists) {
269         await state.updateServerVersion(undefined);
270     }
271
272     if (state.serverVersion === config.package.version) return dest;
273
274     if (config.askBeforeDownload) {
275         const userResponse = await vscode.window.showInformationMessage(
276             `Language server version ${config.package.version} for rust-analyzer is not installed.`,
277             "Download now"
278         );
279         if (userResponse !== "Download now") return dest;
280     }
281
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)}`);
285
286     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
287
288     // Patching executable if that's NixOS.
289     if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) {
290         await patchelf(dest);
291     }
292
293     await state.updateServerVersion(config.package.version);
294     return dest;
295 }