Files
rust/editors/code/src/commands/expand_macro.ts

84 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-11-18 02:47:50 +08:00
import * as vscode from 'vscode';
import { Position, TextDocumentIdentifier } from 'vscode-languageclient';
import { Server } from '../server';
2019-11-20 01:06:10 +08:00
export const expandMacroUri = vscode.Uri.parse(
'rust-analyzer://expandMacro/[EXPANSION].rs'
);
2019-11-18 02:47:50 +08:00
2019-11-20 01:06:10 +08:00
export class ExpandMacroContentProvider
implements vscode.TextDocumentContentProvider {
public eventEmitter = new vscode.EventEmitter<vscode.Uri>();
2019-11-18 02:47:50 +08:00
2019-11-20 01:06:10 +08:00
public provideTextDocumentContent(
uri: vscode.Uri
): vscode.ProviderResult<string> {
2019-11-18 02:47:50 +08:00
async function handle() {
2019-11-20 01:06:10 +08:00
const editor = vscode.window.activeTextEditor;
if (editor == null) {
return '';
}
const position = editor.selection.active;
2019-11-18 02:47:50 +08:00
const request: MacroExpandParams = {
2019-11-20 01:06:10 +08:00
textDocument: { uri: editor.document.uri.toString() },
2019-11-18 03:39:11 +08:00
position
2019-11-18 02:47:50 +08:00
};
2019-11-20 01:06:10 +08:00
const expanded = await Server.client.sendRequest<ExpandedMacro>(
2019-11-18 02:47:50 +08:00
'rust-analyzer/expandMacro',
request
);
2019-11-20 01:06:10 +08:00
if (expanded == null) {
return 'Not available';
2019-11-18 02:47:50 +08:00
}
2019-11-20 01:06:10 +08:00
return code_format(expanded);
2019-11-18 03:39:11 +08:00
}
2019-11-18 02:47:50 +08:00
return handle();
}
2019-11-20 01:06:10 +08:00
get onDidChange(): vscode.Event<vscode.Uri> {
return this.eventEmitter.event;
}
}
// Opens the virtual file that will show the syntax tree
//
// The contents of the file come from the `TextDocumentContentProvider`
export function createHandle(provider: ExpandMacroContentProvider) {
return async () => {
const uri = expandMacroUri;
const document = await vscode.workspace.openTextDocument(uri);
provider.eventEmitter.fire(uri);
return vscode.window.showTextDocument(
document,
vscode.ViewColumn.Two,
true
);
};
2019-11-18 02:47:50 +08:00
}
interface MacroExpandParams {
textDocument: TextDocumentIdentifier;
position: Position;
}
2019-11-20 01:06:10 +08:00
interface ExpandedMacro {
name: string;
expansion: string;
}
function code_format(expanded: ExpandedMacro): string {
let result = `// Recursive expansion of ${expanded.name}! macro\n`;
2019-11-20 01:22:28 +08:00
result += '// ' + '='.repeat(result.length - 3);
2019-11-20 01:06:10 +08:00
result += '\n\n';
result += expanded.expansion;
return result;
}