]> git.lizzy.rs Git - rust.git/blob - editors/code/src/client.ts
Merge #5473
[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         diagnosticCollectionName: "rustc",
45         traceOutputChannel,
46         middleware: {
47             // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
48             async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature) {
49                 const res = await next(document, token);
50                 if (res === undefined) throw new Error('busy');
51                 return res;
52             },
53             async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
54                 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
55                     (result) => {
56                         const hover = client.protocol2CodeConverter.asHover(result);
57                         if (hover) {
58                             const actions = (<any>result).actions;
59                             if (actions) {
60                                 hover.contents.push(renderHoverActions(actions));
61                             }
62                         }
63                         return hover;
64                     },
65                     (error) => {
66                         client.logFailedRequest(lc.HoverRequest.type, error);
67                         return Promise.resolve(null);
68                     });
69             },
70             // Using custom handling of CodeActions where each code action is resolved lazily
71             // That's why we are not waiting for any command or edits
72             async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
73                 const params: lc.CodeActionParams = {
74                     textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
75                     range: client.code2ProtocolConverter.asRange(range),
76                     context: client.code2ProtocolConverter.asCodeActionContext(context)
77                 };
78                 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
79                     if (values === null) return undefined;
80                     const result: (vscode.CodeAction | vscode.Command)[] = [];
81                     const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
82                     for (const item of values) {
83                         // In our case we expect to get code edits only from diagnostics
84                         if (lc.CodeAction.is(item)) {
85                             assert(!item.command, "We don't expect to receive commands in CodeActions");
86                             const action = client.protocol2CodeConverter.asCodeAction(item);
87                             result.push(action);
88                             continue;
89                         }
90                         assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
91                         const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
92                         const action = new vscode.CodeAction(item.title, kind);
93                         const group = (item as any).group;
94                         const id = (item as any).id;
95                         const resolveParams: ra.ResolveCodeActionParams = {
96                             id: id,
97                             codeActionParams: params
98                         };
99                         action.command = {
100                             command: "rust-analyzer.resolveCodeAction",
101                             title: item.title,
102                             arguments: [resolveParams],
103                         };
104                         if (group) {
105                             let entry = groups.get(group);
106                             if (!entry) {
107                                 entry = { index: result.length, items: [] };
108                                 groups.set(group, entry);
109                                 result.push(action);
110                             }
111                             entry.items.push(action);
112                         } else {
113                             result.push(action);
114                         }
115                     }
116                     for (const [group, { index, items }] of groups) {
117                         if (items.length === 1) {
118                             result[index] = items[0];
119                         } else {
120                             const action = new vscode.CodeAction(group);
121                             action.kind = items[0].kind;
122                             action.command = {
123                                 command: "rust-analyzer.applyActionGroup",
124                                 title: "",
125                                 arguments: [items.map((item) => {
126                                     return { label: item.title, arguments: item.command!!.arguments!![0] };
127                                 })],
128                             };
129                             result[index] = action;
130                         }
131                     }
132                     return result;
133                 },
134                     (_error) => undefined
135                 );
136             }
137
138         } as any
139     };
140
141     const client = new lc.LanguageClient(
142         'rust-analyzer',
143         'Rust Analyzer Language Server',
144         serverOptions,
145         clientOptions,
146     );
147
148     // To turn on all proposed features use: client.registerProposedFeatures();
149     // Here we want to enable CallHierarchyFeature and SemanticTokensFeature
150     // since they are available on stable.
151     // Note that while these features are stable in vscode their LSP protocol
152     // implementations are still in the "proposed" category for 3.16.
153     client.registerFeature(new CallHierarchyFeature(client));
154     client.registerFeature(new SemanticTokensFeature(client));
155     client.registerFeature(new ExperimentalFeatures());
156
157     return client;
158 }
159
160 class ExperimentalFeatures implements lc.StaticFeature {
161     fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
162         const caps: any = capabilities.experimental ?? {};
163         caps.snippetTextEdit = true;
164         caps.codeActionGroup = true;
165         caps.resolveCodeAction = true;
166         caps.hoverActions = true;
167         caps.statusNotification = true;
168         capabilities.experimental = caps;
169     }
170     initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
171     }
172 }
173
174 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
175     const candidate: lc.CodeAction = value;
176     return candidate && Is.string(candidate.title) &&
177         (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
178         (candidate.kind === void 0 || Is.string(candidate.kind)) &&
179         (candidate.edit === void 0 && candidate.command === void 0);
180 }