]> git.lizzy.rs Git - rust.git/blob - editors/code/src/client.ts
Merge #4729 #4748
[rust.git] / editors / code / src / client.ts
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';
5
6 import { CallHierarchyFeature } from 'vscode-languageclient/lib/callHierarchy.proposed';
7 import { SemanticTokensFeature, DocumentSemanticsTokensSignature } from 'vscode-languageclient/lib/semanticTokens.proposed';
8 import { assert } from './util';
9
10 function renderCommand(cmd: ra.CommandLink) {
11     return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
12 }
13
14 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
15     const text = actions.map(group =>
16         (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
17     ).join('___');
18
19     const result = new vscode.MarkdownString(text);
20     result.isTrusted = true;
21     return result;
22 }
23
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.
28
29     const run: lc.Executable = {
30         command: serverPath,
31         options: { cwd },
32     };
33     const serverOptions: lc.ServerOptions = {
34         run,
35         debug: run,
36     };
37     const traceOutputChannel = vscode.window.createOutputChannel(
38         'Rust Analyzer Language Server Trace',
39     );
40
41     const clientOptions: lc.LanguageClientOptions = {
42         documentSelector: [{ scheme: 'file', language: 'rust' }],
43         initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
44         traceOutputChannel,
45         middleware: {
46             // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
47             async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature) {
48                 const res = await next(document, token);
49                 if (res === undefined) throw new Error('busy');
50                 return res;
51             },
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(
54                     (result) => {
55                         const hover = client.protocol2CodeConverter.asHover(result);
56                         if (hover) {
57                             const actions = (<any>result).actions;
58                             if (actions) {
59                                 hover.contents.push(renderHoverActions(actions));
60                             }
61                         }
62                         return hover;
63                     },
64                     (error) => {
65                         client.logFailedRequest(lc.HoverRequest.type, error);
66                         return Promise.resolve(null);
67                     });
68             },
69             // Using custom handling of CodeActions where each code action is resloved lazily
70             // That's why we are not waiting for any command or edits
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)
76                 };
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);
86                             result.push(action);
87                             continue;
88                         }
89                         assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
90                         const action = new vscode.CodeAction(item.title);
91                         const group = (item as any).group;
92                         const id = (item as any).id;
93                         const resolveParams: ra.ResolveCodeActionParams = {
94                             id: id,
95                             codeActionParams: params
96                         };
97                         action.command = {
98                             command: "rust-analyzer.resolveCodeAction",
99                             title: item.title,
100                             arguments: [resolveParams],
101                         };
102                         if (group) {
103                             let entry = groups.get(group);
104                             if (!entry) {
105                                 entry = { index: result.length, items: [] };
106                                 groups.set(group, entry);
107                                 result.push(action);
108                             }
109                             entry.items.push(action);
110                         } else {
111                             result.push(action);
112                         }
113                     }
114                     for (const [group, { index, items }] of groups) {
115                         if (items.length === 1) {
116                             result[index] = items[0];
117                         } else {
118                             const action = new vscode.CodeAction(group);
119                             action.command = {
120                                 command: "rust-analyzer.applyActionGroup",
121                                 title: "",
122                                 arguments: [items.map((item) => {
123                                     return { label: item.title, arguments: item.command!!.arguments!![0] };
124                                 })],
125                             };
126                             result[index] = action;
127                         }
128                     }
129                     return result;
130                 },
131                     (_error) => undefined
132                 );
133             }
134
135         } as any
136     };
137
138     const client = new lc.LanguageClient(
139         'rust-analyzer',
140         'Rust Analyzer Language Server',
141         serverOptions,
142         clientOptions,
143     );
144
145     // To turn on all proposed features use: client.registerProposedFeatures();
146     // Here we want to enable CallHierarchyFeature and SemanticTokensFeature
147     // since they are available on stable.
148     // Note that while these features are stable in vscode their LSP protocol
149     // implementations are still in the "proposed" category for 3.16.
150     client.registerFeature(new CallHierarchyFeature(client));
151     client.registerFeature(new SemanticTokensFeature(client));
152     client.registerFeature(new ExperimentalFeatures());
153
154     return client;
155 }
156
157 class ExperimentalFeatures implements lc.StaticFeature {
158     fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
159         const caps: any = capabilities.experimental ?? {};
160         caps.snippetTextEdit = true;
161         caps.codeActionGroup = true;
162         caps.resolveCodeAction = true;
163         caps.hoverActions = true;
164         capabilities.experimental = caps;
165     }
166     initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
167     }
168 }
169
170 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
171     const candidate: lc.CodeAction = value;
172     return candidate && Is.string(candidate.title) &&
173         (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
174         (candidate.kind === void 0 || Is.string(candidate.kind)) &&
175         (candidate.edit === void 0 && candidate.command === void 0);
176 }