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