1import * as vscode from 'vscode'
2
3import {Command} from '../../command';
4import {MLIRContext} from '../../mlirContext';
5
6/**
7 * The parameters to the pdll/viewOutput command. These parameters are:
8 * - `uri`: The URI of the file to view.
9 * - `kind`: The kind of the output to generate.
10 */
11type ViewOutputParams = Partial<{uri : string, kind : string}>;
12
13/**
14 * The output of the commands:
15 * - `output`: The output string of the command, e.g. a .mlir PDL string.
16 */
17type ViewOutputResult = Partial<{output : string}>;
18
19/**
20 * A command that displays the output of the current PDLL document.
21 */
22export class ViewPDLLCommand extends Command {
23  constructor(context: MLIRContext) { super('mlir.viewPDLLOutput', context); }
24
25  async execute() {
26    const editor = vscode.window.activeTextEditor;
27    if (editor.document.languageId != 'pdll')
28      return;
29
30    // Check to see if a language client is active for this document.
31    const workspaceFolder =
32        vscode.workspace.getWorkspaceFolder(editor.document.uri);
33    const pdllClient = this.context.getLanguageClient(workspaceFolder, "pdll");
34    if (!pdllClient) {
35      return;
36    }
37
38    // Ask the user for the desired output type.
39    const outputType =
40        await vscode.window.showQuickPick([ 'ast', 'mlir', 'cpp' ]);
41    if (!outputType) {
42      return;
43    }
44
45    // If we have the language client, ask it to try compiling the document.
46    let outputParams: ViewOutputParams = {
47      uri : editor.document.uri.toString(),
48      kind : outputType,
49    };
50    const result: ViewOutputResult|undefined =
51        await pdllClient.sendRequest('pdll/viewOutput', outputParams);
52    if (!result || result.output.length === 0) {
53      return;
54    }
55
56    // Display the output in a new editor.
57    let outputFileType = 'plaintext';
58    if (outputType == 'mlir') {
59      outputFileType = 'mlir';
60    } else if (outputType == 'cpp') {
61      outputFileType = 'cpp';
62    }
63    await vscode.workspace.openTextDocument(
64        {language : outputFileType, content : result.output});
65  }
66}
67