1 import * as lc from 'vscode-languageclient';
2 import * as vscode from 'vscode';
3 import * as ra from '../src/lsp_ext';
4 import * as Is from 'vscode-languageclient/lib/utils/is';
6 import { CallHierarchyFeature } from 'vscode-languageclient/lib/callHierarchy.proposed';
7 import { SemanticTokensFeature } from 'vscode-languageclient/lib/semanticTokens.proposed';
8 import { assert } from './util';
10 function renderCommand(cmd: ra.CommandLink) {
11 return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
14 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
15 const text = actions.map(group =>
16 (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
19 const result = new vscode.MarkdownString(text);
20 result.isTrusted = true;
24 export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
25 // '.' Is the fallback if no folder is open
26 // TODO?: Workspace folders support Uri's (eg: file://test.txt).
27 // It might be a good idea to test if the uri points to a file.
29 const run: lc.Executable = {
33 const serverOptions: lc.ServerOptions = {
37 const traceOutputChannel = vscode.window.createOutputChannel(
38 'Rust Analyzer Language Server Trace',
41 const clientOptions: lc.LanguageClientOptions = {
42 documentSelector: [{ scheme: 'file', language: 'rust' }],
43 initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
44 diagnosticCollectionName: "rustc",
47 async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
48 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
50 const hover = client.protocol2CodeConverter.asHover(result);
52 const actions = (<any>result).actions;
54 hover.contents.push(renderHoverActions(actions));
60 client.logFailedRequest(lc.HoverRequest.type, error);
61 return Promise.resolve(null);
64 // Using custom handling of CodeActions where each code action is resolved lazily
65 // That's why we are not waiting for any command or edits
66 async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
67 const params: lc.CodeActionParams = {
68 textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
69 range: client.code2ProtocolConverter.asRange(range),
70 context: client.code2ProtocolConverter.asCodeActionContext(context)
72 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
73 if (values === null) return undefined;
74 const result: (vscode.CodeAction | vscode.Command)[] = [];
75 const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
76 for (const item of values) {
77 // In our case we expect to get code edits only from diagnostics
78 if (lc.CodeAction.is(item)) {
79 assert(!item.command, "We don't expect to receive commands in CodeActions");
80 const action = client.protocol2CodeConverter.asCodeAction(item);
84 assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
85 const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
86 const action = new vscode.CodeAction(item.title, kind);
87 const group = (item as any).group;
88 const id = (item as any).id;
89 const resolveParams: ra.ResolveCodeActionParams = {
91 codeActionParams: params
94 command: "rust-analyzer.resolveCodeAction",
96 arguments: [resolveParams],
99 let entry = groups.get(group);
101 entry = { index: result.length, items: [] };
102 groups.set(group, entry);
105 entry.items.push(action);
110 for (const [group, { index, items }] of groups) {
111 if (items.length === 1) {
112 result[index] = items[0];
114 const action = new vscode.CodeAction(group);
115 action.kind = items[0].kind;
117 command: "rust-analyzer.applyActionGroup",
119 arguments: [items.map((item) => {
120 return { label: item.title, arguments: item.command!!.arguments!![0] };
123 result[index] = action;
128 (_error) => undefined
135 const client = new lc.LanguageClient(
137 'Rust Analyzer Language Server',
142 // To turn on all proposed features use: client.registerProposedFeatures();
143 // Here we want to enable CallHierarchyFeature and SemanticTokensFeature
144 // since they are available on stable.
145 // Note that while these features are stable in vscode their LSP protocol
146 // implementations are still in the "proposed" category for 3.16.
147 client.registerFeature(new CallHierarchyFeature(client));
148 client.registerFeature(new SemanticTokensFeature(client));
149 client.registerFeature(new ExperimentalFeatures());
154 class ExperimentalFeatures implements lc.StaticFeature {
155 fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
156 const caps: any = capabilities.experimental ?? {};
157 caps.snippetTextEdit = true;
158 caps.codeActionGroup = true;
159 caps.resolveCodeAction = true;
160 caps.hoverActions = true;
161 caps.statusNotification = true;
162 capabilities.experimental = caps;
164 initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
168 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
169 const candidate: lc.CodeAction = value;
170 return candidate && Is.string(candidate.title) &&
171 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
172 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
173 (candidate.edit === void 0 && candidate.command === void 0);