]> git.lizzy.rs Git - rust.git/blob - editors/code/src/client.ts
Merge #6488
[rust.git] / editors / code / src / client.ts
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 { DocumentSemanticsTokensSignature, DocumentSemanticsTokensEditsSignature, DocumentRangeSemanticTokensSignature } from 'vscode-languageclient/lib/common/semanticTokens';
6 import { assert } from './util';
7
8 function renderCommand(cmd: ra.CommandLink) {
9     return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
10 }
11
12 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
13     const text = actions.map(group =>
14         (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
15     ).join('___');
16
17     const result = new vscode.MarkdownString(text);
18     result.isTrusted = true;
19     return result;
20 }
21
22 // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
23 async function semanticHighlightingWorkaround<R, F extends (...args: any[]) => vscode.ProviderResult<R>>(next: F, ...args: Parameters<F>): Promise<R> {
24     const res = await next(...args);
25     if (res == null) throw new Error('busy');
26     return res;
27 }
28
29 export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
30     // '.' Is the fallback if no folder is open
31     // TODO?: Workspace folders support Uri's (eg: file://test.txt).
32     // It might be a good idea to test if the uri points to a file.
33
34     const run: lc.Executable = {
35         command: serverPath,
36         options: { cwd },
37     };
38     const serverOptions: lc.ServerOptions = {
39         run,
40         debug: run,
41     };
42     const traceOutputChannel = vscode.window.createOutputChannel(
43         'Rust Analyzer Language Server Trace',
44     );
45
46     const clientOptions: lc.LanguageClientOptions = {
47         documentSelector: [{ scheme: 'file', language: 'rust' }],
48         initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
49         diagnosticCollectionName: "rustc",
50         traceOutputChannel,
51         middleware: {
52             provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
53                 return semanticHighlightingWorkaround(next, document, token);
54             },
55             provideDocumentSemanticTokensEdits(document: vscode.TextDocument, previousResultId: string, token: vscode.CancellationToken, next: DocumentSemanticsTokensEditsSignature): vscode.ProviderResult<vscode.SemanticTokensEdits | vscode.SemanticTokens> {
56                 return semanticHighlightingWorkaround(next, document, previousResultId, token);
57             },
58             provideDocumentRangeSemanticTokens(document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken, next: DocumentRangeSemanticTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
59                 return semanticHighlightingWorkaround(next, document, range, token);
60             },
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(
63                     (result) => {
64                         const hover = client.protocol2CodeConverter.asHover(result);
65                         if (hover) {
66                             const actions = (<any>result).actions;
67                             if (actions) {
68                                 hover.contents.push(renderHoverActions(actions));
69                             }
70                         }
71                         return hover;
72                     },
73                     (error) => {
74                         client.handleFailedRequest(lc.HoverRequest.type, error, null);
75                         return Promise.resolve(null);
76                     });
77             },
78             // Using custom handling of CodeActions where each code action is resolved lazily
79             // That's why we are not waiting for any command or edits
80             async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
81                 const params: lc.CodeActionParams = {
82                     textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
83                     range: client.code2ProtocolConverter.asRange(range),
84                     context: client.code2ProtocolConverter.asCodeActionContext(context)
85                 };
86                 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
87                     if (values === null) return undefined;
88                     const result: (vscode.CodeAction | vscode.Command)[] = [];
89                     const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
90                     for (const item of values) {
91                         // In our case we expect to get code edits only from diagnostics
92                         if (lc.CodeAction.is(item)) {
93                             assert(!item.command, "We don't expect to receive commands in CodeActions");
94                             const action = client.protocol2CodeConverter.asCodeAction(item);
95                             result.push(action);
96                             continue;
97                         }
98                         assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
99                         const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
100                         const action = new vscode.CodeAction(item.title, kind);
101                         const group = (item as any).group;
102                         const id = (item as any).id;
103                         const resolveParams: ra.ResolveCodeActionParams = {
104                             id: id,
105                             codeActionParams: params
106                         };
107                         action.command = {
108                             command: "rust-analyzer.resolveCodeAction",
109                             title: item.title,
110                             arguments: [resolveParams],
111                         };
112                         if (group) {
113                             let entry = groups.get(group);
114                             if (!entry) {
115                                 entry = { index: result.length, items: [] };
116                                 groups.set(group, entry);
117                                 result.push(action);
118                             }
119                             entry.items.push(action);
120                         } else {
121                             result.push(action);
122                         }
123                     }
124                     for (const [group, { index, items }] of groups) {
125                         if (items.length === 1) {
126                             result[index] = items[0];
127                         } else {
128                             const action = new vscode.CodeAction(group);
129                             action.kind = items[0].kind;
130                             action.command = {
131                                 command: "rust-analyzer.applyActionGroup",
132                                 title: "",
133                                 arguments: [items.map((item) => {
134                                     return { label: item.title, arguments: item.command!!.arguments!![0] };
135                                 })],
136                             };
137                             result[index] = action;
138                         }
139                     }
140                     return result;
141                 },
142                     (_error) => undefined
143                 );
144             }
145
146         }
147     };
148
149     const client = new lc.LanguageClient(
150         'rust-analyzer',
151         'Rust Analyzer Language Server',
152         serverOptions,
153         clientOptions,
154     );
155
156     // To turn on all proposed features use: client.registerProposedFeatures();
157     client.registerFeature(new ExperimentalFeatures());
158
159     return client;
160 }
161
162 class ExperimentalFeatures implements lc.StaticFeature {
163     fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
164         const caps: any = capabilities.experimental ?? {};
165         caps.snippetTextEdit = true;
166         caps.codeActionGroup = true;
167         caps.resolveCodeAction = true;
168         caps.hoverActions = true;
169         caps.statusNotification = true;
170         capabilities.experimental = caps;
171     }
172     initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
173     }
174 }
175
176 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
177     const candidate: lc.CodeAction = value;
178     return candidate && Is.string(candidate.title) &&
179         (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
180         (candidate.kind === void 0 || Is.string(candidate.kind)) &&
181         (candidate.edit === void 0 && candidate.command === void 0);
182 }