1 import * as lc from 'vscode-languageclient/node';
2 import * as vscode from 'vscode';
3 import * as ra from '../src/lsp_ext';
4 import * as Is from 'vscode-languageclient/lib/common/utils/is';
5 import { assert } from './util';
6 import { WorkspaceEdit } from 'vscode';
9 [name: string]: string;
12 function renderCommand(cmd: ra.CommandLink) {
13 return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip}')`;
16 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
17 const text = actions.map(group =>
18 (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
21 const result = new vscode.MarkdownString(text);
22 result.isTrusted = true;
26 export function createClient(serverPath: string, cwd: string, extraEnv: Env): lc.LanguageClient {
27 // '.' Is the fallback if no folder is open
28 // TODO?: Workspace folders support Uri's (eg: file://test.txt).
29 // It might be a good idea to test if the uri points to a file.
31 const newEnv = Object.assign({}, process.env);
32 Object.assign(newEnv, extraEnv);
34 const run: lc.Executable = {
36 options: { cwd, env: newEnv },
38 const serverOptions: lc.ServerOptions = {
42 const traceOutputChannel = vscode.window.createOutputChannel(
43 'Rust Analyzer Language Server Trace',
46 const clientOptions: lc.LanguageClientOptions = {
47 documentSelector: [{ scheme: 'file', language: 'rust' }],
48 initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
49 diagnosticCollectionName: "rustc",
52 async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
53 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
55 const hover = client.protocol2CodeConverter.asHover(result);
57 const actions = (<any>result).actions;
59 hover.contents.push(renderHoverActions(actions));
65 client.handleFailedRequest(lc.HoverRequest.type, token, error, null);
66 return Promise.resolve(null);
69 // Using custom handling of CodeActions to support action groups and snippet edits.
70 // Note that this means we have to re-implement lazy edit resolving ourselves as well.
71 async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
72 const params: lc.CodeActionParams = {
73 textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
74 range: client.code2ProtocolConverter.asRange(range),
75 context: client.code2ProtocolConverter.asCodeActionContext(context)
77 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
78 if (values === null) return undefined;
79 const result: (vscode.CodeAction | vscode.Command)[] = [];
80 const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
81 for (const item of values) {
82 // In our case we expect to get code edits only from diagnostics
83 if (lc.CodeAction.is(item)) {
84 assert(!item.command, "We don't expect to receive commands in CodeActions");
85 const action = client.protocol2CodeConverter.asCodeAction(item);
89 assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
90 const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
91 const action = new vscode.CodeAction(item.title, kind);
92 const group = (item as any).group;
94 command: "rust-analyzer.resolveCodeAction",
99 // Set a dummy edit, so that VS Code doesn't try to resolve this.
100 action.edit = new WorkspaceEdit();
103 let entry = groups.get(group);
105 entry = { index: result.length, items: [] };
106 groups.set(group, entry);
109 entry.items.push(action);
114 for (const [group, { index, items }] of groups) {
115 if (items.length === 1) {
116 result[index] = items[0];
118 const action = new vscode.CodeAction(group);
119 action.kind = items[0].kind;
121 command: "rust-analyzer.applyActionGroup",
123 arguments: [items.map((item) => {
124 return { label: item.title, arguments: item.command!.arguments![0] };
128 // Set a dummy edit, so that VS Code doesn't try to resolve this.
129 action.edit = new WorkspaceEdit();
131 result[index] = action;
136 (_error) => undefined
143 const client = new lc.LanguageClient(
145 'Rust Analyzer Language Server',
150 // To turn on all proposed features use: client.registerProposedFeatures();
151 client.registerFeature(new ExperimentalFeatures());
156 class ExperimentalFeatures implements lc.StaticFeature {
157 fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
158 const caps: any = capabilities.experimental ?? {};
159 caps.snippetTextEdit = true;
160 caps.codeActionGroup = true;
161 caps.hoverActions = true;
162 caps.serverStatusNotification = true;
163 capabilities.experimental = caps;
165 initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
171 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
172 const candidate: lc.CodeAction = value;
173 return candidate && Is.string(candidate.title) &&
174 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
175 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
176 (candidate.edit === void 0 && candidate.command === void 0);