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