]> git.lizzy.rs Git - rust.git/blob - editors/code/src/main.ts
Merge #3666
[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 } 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 { activateHighlighting } from './highlighting';
11 import { Config, NIGHTLY_TAG } from './config';
12 import { log, assert } from './util';
13 import { PersistentState } from './persistent_state';
14 import { fetchRelease, download } from './net';
15 import { spawnSync } from 'child_process';
16
17 let ctx: Ctx | undefined;
18
19 export async function activate(context: vscode.ExtensionContext) {
20     // Register a "dumb" onEnter command for the case where server fails to
21     // start.
22     //
23     // FIXME: refactor command registration code such that commands are
24     // **always** registered, even if the server does not start. Use API like
25     // this perhaps?
26     //
27     // ```TypeScript
28     // registerCommand(
29     //    factory: (Ctx) => ((Ctx) => any),
30     //    fallback: () => any = () => vscode.window.showErrorMessage(
31     //        "rust-analyzer is not available"
32     //    ),
33     // )
34     const defaultOnEnter = vscode.commands.registerCommand(
35         'rust-analyzer.onEnter',
36         () => vscode.commands.executeCommand('default:type', { text: '\n' }),
37     );
38     context.subscriptions.push(defaultOnEnter);
39
40     const config = new Config(context);
41     const state = new PersistentState(context.globalState);
42     const serverPath = await bootstrap(config, state);
43
44     // Note: we try to start the server before we activate type hints so that it
45     // registers its `onDidChangeDocument` handler before us.
46     //
47     // This a horribly, horribly wrong way to deal with this problem.
48     ctx = await Ctx.create(config, context, serverPath);
49
50     // Commands which invokes manually via command palette, shortcut, etc.
51
52     // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
53     ctx.registerCommand('reload', _ => async () => {
54         void vscode.window.showInformationMessage('Reloading rust-analyzer...');
55         await deactivate();
56         while (context.subscriptions.length > 0) {
57             try {
58                 context.subscriptions.pop()!.dispose();
59             } catch (err) {
60                 log.error("Dispose error:", err);
61             }
62         }
63         await activate(context).catch(log.error);
64     });
65
66     ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
67     ctx.registerCommand('collectGarbage', commands.collectGarbage);
68     ctx.registerCommand('matchingBrace', commands.matchingBrace);
69     ctx.registerCommand('joinLines', commands.joinLines);
70     ctx.registerCommand('parentModule', commands.parentModule);
71     ctx.registerCommand('syntaxTree', commands.syntaxTree);
72     ctx.registerCommand('expandMacro', commands.expandMacro);
73     ctx.registerCommand('run', commands.run);
74
75     defaultOnEnter.dispose();
76     ctx.registerCommand('onEnter', commands.onEnter);
77
78     ctx.registerCommand('ssr', commands.ssr);
79     ctx.registerCommand('serverVersion', commands.serverVersion);
80
81     // Internal commands which are invoked by the server.
82     ctx.registerCommand('runSingle', commands.runSingle);
83     ctx.registerCommand('debugSingle', commands.debugSingle);
84     ctx.registerCommand('showReferences', commands.showReferences);
85     ctx.registerCommand('applySourceChange', commands.applySourceChange);
86     ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
87
88     activateStatusDisplay(ctx);
89
90     if (!ctx.config.highlightingSemanticTokens) {
91         activateHighlighting(ctx);
92     }
93     activateInlayHints(ctx);
94
95     vscode.workspace.onDidChangeConfiguration(
96         _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
97         null,
98         ctx.subscriptions,
99     );
100 }
101
102 export async function deactivate() {
103     await ctx?.client.stop();
104     ctx = undefined;
105 }
106
107 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
108     await fs.mkdir(config.globalStoragePath, { recursive: true });
109
110     await bootstrapExtension(config, state);
111     const path = await bootstrapServer(config, state);
112
113     return path;
114 }
115
116 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
117     if (config.package.releaseTag === null) return;
118     if (config.channel === "stable") {
119         if (config.package.releaseTag === NIGHTLY_TAG) {
120             void vscode.window.showWarningMessage(
121                 `You are running a nightly version of rust-analyzer extension. ` +
122                 `To switch to stable, uninstall the extension and re-install it from the marketplace`
123             );
124         }
125         return;
126     };
127
128     const lastCheck = state.lastCheck;
129     const now = Date.now();
130
131     const anHour = 60 * 60 * 1000;
132     const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
133
134     if (!shouldDownloadNightly) return;
135
136     const release = await fetchRelease("nightly").catch((e) => {
137         log.error(e);
138         if (state.releaseId === undefined) { // Show error only for the initial download
139             vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
140         }
141         return undefined;
142     });
143     if (release === undefined || release.id === state.releaseId) return;
144
145     const userResponse = await vscode.window.showInformationMessage(
146         "New version of rust-analyzer (nightly) is available (requires reload).",
147         "Update"
148     );
149     if (userResponse !== "Update") return;
150
151     const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
152     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
153
154     const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
155     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
156
157     await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
158     await fs.unlink(dest);
159
160     await state.updateReleaseId(release.id);
161     await state.updateLastCheck(now);
162     await vscode.commands.executeCommand("workbench.action.reloadWindow");
163 }
164
165 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
166     const path = await getServer(config, state);
167     if (!path) {
168         throw new Error(
169             "Rust Analyzer Language Server is not available. " +
170             "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
171         );
172     }
173
174     const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
175     log.debug("Checked binary availability via --version", res);
176     log.debug(res, "--version output:", res.output);
177     if (res.status !== 0) {
178         throw new Error(`Failed to execute ${path} --version`);
179     }
180
181     return path;
182 }
183
184 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
185     const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
186     if (explicitPath) {
187         if (explicitPath.startsWith("~/")) {
188             return os.homedir() + explicitPath.slice("~".length);
189         }
190         return explicitPath;
191     };
192     if (config.package.releaseTag === null) return "rust-analyzer";
193
194     let binaryName: string | undefined = undefined;
195     if (process.arch === "x64" || process.arch === "ia32") {
196         if (process.platform === "linux") binaryName = "rust-analyzer-linux";
197         if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
198         if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
199     }
200     if (binaryName === undefined) {
201         vscode.window.showErrorMessage(
202             "Unfortunately we don't ship binaries for your platform yet. " +
203             "You need to manually clone rust-analyzer repository and " +
204             "run `cargo xtask install --server` to build the language server from sources. " +
205             "If you feel that your platform should be supported, please create an issue " +
206             "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
207             "will consider it."
208         );
209         return undefined;
210     }
211
212     const dest = path.join(config.globalStoragePath, binaryName);
213     const exists = await fs.stat(dest).then(() => true, () => false);
214     if (!exists) {
215         await state.updateServerVersion(undefined);
216     }
217
218     if (state.serverVersion === config.package.version) return dest;
219
220     if (config.askBeforeDownload) {
221         const userResponse = await vscode.window.showInformationMessage(
222             `Language server version ${config.package.version} for rust-analyzer is not installed.`,
223             "Download now"
224         );
225         if (userResponse !== "Download now") return dest;
226     }
227
228     const release = await fetchRelease(config.package.releaseTag);
229     const artifact = release.assets.find(artifact => artifact.name === binaryName);
230     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
231
232     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
233     await state.updateServerVersion(config.package.version);
234     return dest;
235 }