From 077592a12fd982de3e69572a4c738dd4468617f9 Mon Sep 17 00:00:00 2001 From: Phil Ellison Date: Mon, 28 Dec 2020 18:29:58 +0000 Subject: Initial implementation of view-hir command --- editors/code/src/commands.ts | 69 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) (limited to 'editors/code/src/commands.ts') diff --git a/editors/code/src/commands.ts b/editors/code/src/commands.ts index 9d4823a34..21b0c27f3 100644 --- a/editors/code/src/commands.ts +++ b/editors/code/src/commands.ts @@ -340,6 +340,75 @@ export function syntaxTree(ctx: Ctx): Cmd { }; } +// Opens the virtual file that will show hir +// +// The contents of the file come from the `TextDocumentContentProvider` +export function viewHir(ctx: Ctx): Cmd { + const tdcp = new class implements vscode.TextDocumentContentProvider { + readonly uri = vscode.Uri.parse('rust-analyzer://viewHir/hir.txt'); + readonly eventEmitter = new vscode.EventEmitter(); + constructor() { + vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); + vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions); + } + + private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) { + if (isRustDocument(event.document)) { + // We need to order this after language server updates, but there's no API for that. + // Hence, good old sleep(). + void sleep(10).then(() => this.eventEmitter.fire(this.uri)); + } + } + private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) { + if (editor && isRustEditor(editor)) { + this.eventEmitter.fire(this.uri); + } + } + + provideTextDocumentContent(_uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult { + const rustEditor = ctx.activeRustEditor; + const client = ctx.client; + if (!rustEditor || !client) return ''; + + const params = { + textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(rustEditor.document), + position: client.code2ProtocolConverter.asPosition( + rustEditor.selection.active, + ), + }; + return client.sendRequest(ra.viewHir, params, ct); + } + + get onDidChange(): vscode.Event { + return this.eventEmitter.event; + } + }; + + void new AstInspector(ctx); + + ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider('rust-analyzer', tdcp)); + ctx.pushCleanup(vscode.languages.setLanguageConfiguration("ra_syntax_tree", { + brackets: [["[", ")"]], + })); + + return async () => { + const editor = vscode.window.activeTextEditor; + const rangeEnabled = !!editor && !editor.selection.isEmpty; + + const uri = rangeEnabled + ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`) + : tdcp.uri; + + const document = await vscode.workspace.openTextDocument(uri); + + tdcp.eventEmitter.fire(uri); + + void await vscode.window.showTextDocument(document, { + viewColumn: vscode.ViewColumn.Two, + preserveFocus: true + }); + }; +} // Opens the virtual file that will show the syntax tree // -- cgit v1.2.3