-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathctx.ts
535 lines (483 loc) · 19.5 KB
/
ctx.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import * as vscode from "vscode";
import * as lc from "vscode-languageclient/node";
import * as ra from "./lsp_ext";
import { Config, prepareVSCodeConfig } from "./config";
import { createClient } from "./client";
import {
isDocumentInWorkspace,
isRustDocument,
isRustEditor,
LazyOutputChannel,
log,
type RustEditor,
} from "./util";
import type { ServerStatusParams } from "./lsp_ext";
import {
type Dependency,
type DependencyFile,
RustDependenciesProvider,
type DependencyId,
} from "./dependencies_provider";
import { execRevealDependency } from "./commands";
import { PersistentState } from "./persistent_state";
import { bootstrap } from "./bootstrap";
import type { RustAnalyzerExtensionApi } from "./main";
import type { JsonProject } from "./rust_project";
import { prepareTestExplorer } from "./test_explorer";
import { spawn } from "node:child_process";
import { text } from "node:stream/consumers";
// We only support local folders, not eg. Live Share (`vlsl:` scheme), so don't activate if
// only those are in use. We use "Empty" to represent these scenarios
// (r-a still somewhat works with Live Share, because commands are tunneled to the host)
export type Workspace =
| { kind: "Empty" }
| {
kind: "Workspace Folder";
}
| {
kind: "Detached Files";
files: vscode.TextDocument[];
};
export function fetchWorkspace(): Workspace {
const folders = (vscode.workspace.workspaceFolders || []).filter(
(folder) => folder.uri.scheme === "file",
);
const rustDocuments = vscode.workspace.textDocuments.filter((document) =>
isRustDocument(document),
);
return folders.length === 0
? rustDocuments.length === 0
? { kind: "Empty" }
: {
kind: "Detached Files",
files: rustDocuments,
}
: { kind: "Workspace Folder" };
}
export type CommandFactory = {
enabled: (ctx: CtxInit) => Cmd;
disabled?: (ctx: Ctx) => Cmd;
};
export type CtxInit = Ctx & {
readonly client: lc.LanguageClient;
};
export class Ctx implements RustAnalyzerExtensionApi {
readonly statusBar: vscode.StatusBarItem;
config: Config;
readonly workspace: Workspace;
readonly version: string;
private _client: lc.LanguageClient | undefined;
private _serverPath: string | undefined;
private traceOutputChannel: vscode.OutputChannel | undefined;
private testController: vscode.TestController | undefined;
private outputChannel: vscode.OutputChannel | undefined;
private clientSubscriptions: Disposable[];
private state: PersistentState;
private commandFactories: Record<string, CommandFactory>;
private commandDisposables: Disposable[];
private unlinkedFiles: vscode.Uri[];
private _dependencies: RustDependenciesProvider | undefined;
private _treeView: vscode.TreeView<Dependency | DependencyFile | DependencyId> | undefined;
private lastStatus: ServerStatusParams | { health: "stopped" } = { health: "stopped" };
private _serverVersion: string;
get serverPath(): string | undefined {
return this._serverPath;
}
get serverVersion(): string | undefined {
return this._serverVersion;
}
get client() {
return this._client;
}
get treeView() {
return this._treeView;
}
get dependencies() {
return this._dependencies;
}
constructor(
readonly extCtx: vscode.ExtensionContext,
commandFactories: Record<string, CommandFactory>,
workspace: Workspace,
) {
extCtx.subscriptions.push(this);
this.version = extCtx.extension.packageJSON.version ?? "<unknown>";
this._serverVersion = "<not running>";
this.config = new Config(extCtx);
this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
if (this.config.testExplorer) {
this.testController = vscode.tests.createTestController(
"rustAnalyzerTestController",
"Rust Analyzer test controller",
);
}
this.workspace = workspace;
this.clientSubscriptions = [];
this.commandDisposables = [];
this.commandFactories = commandFactories;
this.unlinkedFiles = [];
this.state = new PersistentState(extCtx.globalState);
this.updateCommands("disable");
this.setServerStatus({
health: "stopped",
});
}
dispose() {
this.config.dispose();
this.statusBar.dispose();
this.testController?.dispose();
void this.disposeClient();
this.commandDisposables.forEach((disposable) => disposable.dispose());
}
async onWorkspaceFolderChanges() {
const workspace = fetchWorkspace();
if (workspace.kind === "Detached Files" && this.workspace.kind === "Detached Files") {
if (workspace.files !== this.workspace.files) {
if (this.client?.isRunning()) {
// Ideally we wouldn't need to tear down the server here, but currently detached files
// are only specified at server start
await this.stopAndDispose();
await this.start();
}
return;
}
}
if (workspace.kind === "Workspace Folder" && this.workspace.kind === "Workspace Folder") {
return;
}
if (workspace.kind === "Empty") {
await this.stopAndDispose();
return;
}
if (this.client?.isRunning()) {
await this.restart();
}
}
private async getOrCreateClient() {
if (this.workspace.kind === "Empty") {
return;
}
if (!this.traceOutputChannel) {
this.traceOutputChannel = new LazyOutputChannel("Rust Analyzer Language Server Trace");
this.pushExtCleanup(this.traceOutputChannel);
}
if (!this.outputChannel) {
this.outputChannel = vscode.window.createOutputChannel("Rust Analyzer Language Server");
this.pushExtCleanup(this.outputChannel);
}
if (!this._client) {
this._serverPath = await bootstrap(this.extCtx, this.config, this.state).catch(
(err) => {
let message = "bootstrap error. ";
message +=
'See the logs in "OUTPUT > Rust Analyzer Client" (should open automatically). ';
message +=
'To enable verbose logs use { "rust-analyzer.trace.extension": true }';
log.error("Bootstrap error", err);
throw new Error(message);
},
);
text(spawn(this._serverPath, ["--version"]).stdout.setEncoding("utf-8")).then(
(data) => {
const prefix = `rust-analyzer `;
this._serverVersion = data
.slice(data.startsWith(prefix) ? prefix.length : 0)
.trim();
this.refreshServerStatus();
},
(_) => {
this._serverVersion = "<unknown>";
this.refreshServerStatus();
},
);
const newEnv = Object.assign({}, process.env, this.config.serverExtraEnv);
const run: lc.Executable = {
command: this._serverPath,
options: { env: newEnv },
};
const serverOptions = {
run,
debug: run,
};
let rawInitializationOptions = vscode.workspace.getConfiguration("rust-analyzer");
if (this.config.discoverProjectRunner) {
const command = `${this.config.discoverProjectRunner}.discoverWorkspaceCommand`;
log.info(`running command: ${command}`);
const uris = vscode.workspace.textDocuments
.filter(isRustDocument)
.map((document) => document.uri);
const projects: JsonProject[] = await vscode.commands.executeCommand(command, uris);
this.setWorkspaces(projects);
}
if (this.workspace.kind === "Detached Files") {
rawInitializationOptions = {
detachedFiles: this.workspace.files.map((file) => file.uri.fsPath),
...rawInitializationOptions,
};
}
const initializationOptions = prepareVSCodeConfig(
rawInitializationOptions,
(key, obj) => {
// we only want to set discovered workspaces on the right key
// and if a workspace has been discovered.
if (key === "linkedProjects" && this.config.discoveredWorkspaces.length > 0) {
obj["linkedProjects"] = this.config.discoveredWorkspaces;
}
},
);
this._client = await createClient(
this.traceOutputChannel,
this.outputChannel,
initializationOptions,
serverOptions,
this.config,
this.unlinkedFiles,
);
this.pushClientCleanup(
this._client.onNotification(ra.serverStatus, (params) =>
this.setServerStatus(params),
),
);
this.pushClientCleanup(
this._client.onNotification(ra.openServerLogs, () => {
this.outputChannel!.show();
}),
);
this.pushClientCleanup(
this._client.onNotification(ra.unindexedProject, async (params) => {
if (this.config.discoverProjectRunner) {
const command = `${this.config.discoverProjectRunner}.discoverWorkspaceCommand`;
log.info(`running command: ${command}`);
const uris = params.textDocuments.map((doc) =>
vscode.Uri.parse(doc.uri, true),
);
const projects: JsonProject[] = await vscode.commands.executeCommand(
command,
uris,
);
this.setWorkspaces(projects);
await this.notifyRustAnalyzer();
}
}),
);
}
return this._client;
}
async start() {
log.info("Starting language client");
const client = await this.getOrCreateClient();
if (!client) {
return;
}
await client.start();
this.updateCommands();
if (this.testController) {
prepareTestExplorer(this, this.testController, client);
}
if (this.config.showDependenciesExplorer) {
this.prepareTreeDependenciesView(client);
}
}
private prepareTreeDependenciesView(client: lc.LanguageClient) {
const ctxInit: CtxInit = {
...this,
client: client,
};
this._dependencies = new RustDependenciesProvider(ctxInit);
this._treeView = vscode.window.createTreeView("rustDependencies", {
treeDataProvider: this._dependencies,
showCollapseAll: true,
});
this.pushExtCleanup(this._treeView);
vscode.window.onDidChangeActiveTextEditor(async (e) => {
// we should skip documents that belong to the current workspace
if (this.shouldRevealDependency(e)) {
try {
await execRevealDependency(e);
} catch (reason) {
await vscode.window.showErrorMessage(`Dependency error: ${reason}`);
}
}
});
this.treeView?.onDidChangeVisibility(async (e) => {
if (e.visible) {
const activeEditor = vscode.window.activeTextEditor;
if (this.shouldRevealDependency(activeEditor)) {
try {
await execRevealDependency(activeEditor);
} catch (reason) {
await vscode.window.showErrorMessage(`Dependency error: ${reason}`);
}
}
}
});
}
private shouldRevealDependency(e: vscode.TextEditor | undefined): e is RustEditor {
return (
e !== undefined &&
isRustEditor(e) &&
!isDocumentInWorkspace(e.document) &&
(this.treeView?.visible || false)
);
}
async restart() {
// FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
await this.stopAndDispose();
await this.start();
}
async stop() {
if (!this._client) {
return;
}
log.info("Stopping language client");
this.updateCommands("disable");
await this._client.stop();
}
async stopAndDispose() {
if (!this._client) {
return;
}
log.info("Disposing language client");
this.updateCommands("disable");
await this.disposeClient();
}
private async disposeClient() {
this.clientSubscriptions?.forEach((disposable) => disposable.dispose());
this.clientSubscriptions = [];
await this._client?.dispose();
this._serverPath = undefined;
this._client = undefined;
}
get activeRustEditor(): RustEditor | undefined {
const editor = vscode.window.activeTextEditor;
return editor && isRustEditor(editor) ? editor : undefined;
}
get extensionPath(): string {
return this.extCtx.extensionPath;
}
get subscriptions(): Disposable[] {
return this.extCtx.subscriptions;
}
setWorkspaces(workspaces: JsonProject[]) {
this.config.discoveredWorkspaces = workspaces;
}
async notifyRustAnalyzer(): Promise<void> {
// this is a workaround to avoid needing writing the `rust-project.json` into
// a workspace-level VS Code-specific settings folder. We'd like to keep the
// `rust-project.json` entirely in-memory.
await this.client?.sendNotification(lc.DidChangeConfigurationNotification.type, {
settings: "",
});
}
private updateCommands(forceDisable?: "disable") {
this.commandDisposables.forEach((disposable) => disposable.dispose());
this.commandDisposables = [];
const clientRunning = (!forceDisable && this._client?.isRunning()) ?? false;
const isClientRunning = function (_ctx: Ctx): _ctx is CtxInit {
return clientRunning;
};
for (const [name, factory] of Object.entries(this.commandFactories)) {
const fullName = `rust-analyzer.${name}`;
let callback;
if (isClientRunning(this)) {
// we asserted that `client` is defined
callback = factory.enabled(this);
} else if (factory.disabled) {
callback = factory.disabled(this);
} else {
callback = () =>
vscode.window.showErrorMessage(
`command ${fullName} failed: rust-analyzer server is not running`,
);
}
this.commandDisposables.push(vscode.commands.registerCommand(fullName, callback));
}
}
setServerStatus(status: ServerStatusParams | { health: "stopped" }) {
this.lastStatus = status;
this.updateStatusBarItem();
}
refreshServerStatus() {
this.updateStatusBarItem();
}
private updateStatusBarItem() {
let icon = "";
const status = this.lastStatus;
const statusBar = this.statusBar;
statusBar.show();
statusBar.tooltip = new vscode.MarkdownString("", true);
statusBar.tooltip.isTrusted = true;
switch (status.health) {
case "ok":
statusBar.color = undefined;
statusBar.backgroundColor = undefined;
if (this.config.statusBarClickAction === "stopServer") {
statusBar.command = "rust-analyzer.stopServer";
} else {
statusBar.command = "rust-analyzer.openLogs";
}
this.dependencies?.refresh();
break;
case "warning":
statusBar.color = new vscode.ThemeColor("statusBarItem.warningForeground");
statusBar.backgroundColor = new vscode.ThemeColor(
"statusBarItem.warningBackground",
);
statusBar.command = "rust-analyzer.openLogs";
icon = "$(warning) ";
break;
case "error":
statusBar.color = new vscode.ThemeColor("statusBarItem.errorForeground");
statusBar.backgroundColor = new vscode.ThemeColor("statusBarItem.errorBackground");
statusBar.command = "rust-analyzer.openLogs";
icon = "$(error) ";
break;
case "stopped":
statusBar.tooltip.appendText("Server is stopped");
statusBar.tooltip.appendMarkdown(
"\n\n[Start server](command:rust-analyzer.startServer)",
);
statusBar.color = new vscode.ThemeColor("statusBarItem.warningForeground");
statusBar.backgroundColor = new vscode.ThemeColor(
"statusBarItem.warningBackground",
);
statusBar.command = "rust-analyzer.startServer";
statusBar.text = "$(stop-circle) rust-analyzer";
return;
}
if (status.message) {
statusBar.tooltip.appendText(status.message);
}
if (statusBar.tooltip.value) {
statusBar.tooltip.appendMarkdown("\n\n---\n\n");
}
const toggleCheckOnSave = this.config.checkOnSave ? "Disable" : "Enable";
statusBar.tooltip.appendMarkdown(
`[Extension Info](command:analyzer.serverVersion "Show version and server binary info"): Version ${this.version}, Server Version ${this._serverVersion}` +
"\n\n---\n\n" +
'[$(terminal) Open Logs](command:rust-analyzer.openLogs "Open the server logs")' +
"\n\n" +
`[$(settings) ${toggleCheckOnSave} Check on Save](command:rust-analyzer.toggleCheckOnSave "Temporarily ${toggleCheckOnSave.toLowerCase()} check on save functionality")` +
"\n\n" +
'[$(refresh) Reload Workspace](command:rust-analyzer.reloadWorkspace "Reload and rediscover workspaces")' +
"\n\n" +
'[$(symbol-property) Rebuild Build Dependencies](command:rust-analyzer.rebuildProcMacros "Rebuild build scripts and proc-macros")' +
"\n\n" +
'[$(stop-circle) Stop server](command:rust-analyzer.stopServer "Stop the server")' +
"\n\n" +
'[$(debug-restart) Restart server](command:rust-analyzer.restartServer "Restart the server")',
);
if (!status.quiescent) icon = "$(loading~spin) ";
statusBar.text = `${icon}rust-analyzer`;
}
pushExtCleanup(d: Disposable) {
this.extCtx.subscriptions.push(d);
}
pushClientCleanup(d: Disposable) {
this.clientSubscriptions.push(d);
}
}
export interface Disposable {
dispose(): void;
}
export type Cmd = (...args: any[]) => unknown;