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, DocumentSemanticsTokensSignature } from 'vscode-languageclient/lib/semanticTokens.proposed';
8 import { assert } from './util';
10 function toTrusted(obj: vscode.MarkedString): vscode.MarkedString {
11 const md = <vscode.MarkdownString>obj;
12 if (md && md.value.includes("```rust")) {
19 function renderCommand(cmd: CommandLink) {
20 return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
23 function renderHoverActions(actions: CommandLinkGroup[]): vscode.MarkdownString {
24 const text = actions.map(group =>
25 (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
28 const result = new vscode.MarkdownString(text);
29 result.isTrusted = true;
33 export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
34 // '.' Is the fallback if no folder is open
35 // TODO?: Workspace folders support Uri's (eg: file://test.txt).
36 // It might be a good idea to test if the uri points to a file.
38 const run: lc.Executable = {
42 const serverOptions: lc.ServerOptions = {
46 const traceOutputChannel = vscode.window.createOutputChannel(
47 'Rust Analyzer Language Server Trace',
50 const clientOptions: lc.LanguageClientOptions = {
51 documentSelector: [{ scheme: 'file', language: 'rust' }],
52 initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
55 // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
56 async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature) {
57 const res = await next(document, token);
58 if (res === undefined) throw new Error('busy');
61 async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
62 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
64 const hover = client.protocol2CodeConverter.asHover(result);
66 // Workaround to support command links (trusted vscode.MarkdownString) in hovers
67 // https://github.com/microsoft/vscode/issues/33577
68 hover.contents = hover.contents.map(toTrusted);
70 const actions = (<any>result).actions;
72 hover.contents.push(renderHoverActions(actions));
78 client.logFailedRequest(lc.HoverRequest.type, error);
79 return Promise.resolve(null);
82 // Using custom handling of CodeActions where each code action is resloved lazily
83 // That's why we are not waiting for any command or edits
84 async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
85 const params: lc.CodeActionParams = {
86 textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
87 range: client.code2ProtocolConverter.asRange(range),
88 context: client.code2ProtocolConverter.asCodeActionContext(context)
90 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
91 if (values === null) return undefined;
92 const result: (vscode.CodeAction | vscode.Command)[] = [];
93 const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
94 for (const item of values) {
95 // In our case we expect to get code edits only from diagnostics
96 if (lc.CodeAction.is(item)) {
97 assert(!item.command, "We don't expect to receive commands in CodeActions");
98 const action = client.protocol2CodeConverter.asCodeAction(item);
102 assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
103 const action = new vscode.CodeAction(item.title);
104 const group = (item as any).group;
105 const id = (item as any).id;
106 const resolveParams: ra.ResolveCodeActionParams = {
108 codeActionParams: params
111 command: "rust-analyzer.resolveCodeAction",
113 arguments: [resolveParams],
116 let entry = groups.get(group);
118 entry = { index: result.length, items: [] };
119 groups.set(group, entry);
122 entry.items.push(action);
127 for (const [group, { index, items }] of groups) {
128 if (items.length === 1) {
129 result[index] = items[0];
131 const action = new vscode.CodeAction(group);
133 command: "rust-analyzer.applyActionGroup",
135 arguments: [items.map((item) => {
136 return { label: item.title, arguments: item.command!!.arguments!![0] };
139 result[index] = action;
144 (_error) => undefined
151 const client = new lc.LanguageClient(
153 'Rust Analyzer Language Server',
158 // To turn on all proposed features use: client.registerProposedFeatures();
159 // Here we want to enable CallHierarchyFeature and SemanticTokensFeature
160 // since they are available on stable.
161 // Note that while these features are stable in vscode their LSP protocol
162 // implementations are still in the "proposed" category for 3.16.
163 client.registerFeature(new CallHierarchyFeature(client));
164 client.registerFeature(new SemanticTokensFeature(client));
165 client.registerFeature(new ExperimentalFeatures());
170 class ExperimentalFeatures implements lc.StaticFeature {
171 fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
172 const caps: any = capabilities.experimental ?? {};
173 caps.snippetTextEdit = true;
174 caps.codeActionGroup = true;
175 caps.resolveCodeAction = true;
176 caps.hoverActions = true;
177 capabilities.experimental = caps;
179 initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
183 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
184 const candidate: lc.CodeAction = value;
185 return candidate && Is.string(candidate.title) &&
186 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
187 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
188 (candidate.edit === void 0 && candidate.command === void 0);