]> git.lizzy.rs Git - rust.git/blob - editors/code/src/client.ts
Merge remote-tracking branch 'upstream/master' into compute-lazy-assits
[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 export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
11     // '.' Is the fallback if no folder is open
12     // TODO?: Workspace folders support Uri's (eg: file://test.txt).
13     // It might be a good idea to test if the uri points to a file.
14
15     const run: lc.Executable = {
16         command: serverPath,
17         options: { cwd },
18     };
19     const serverOptions: lc.ServerOptions = {
20         run,
21         debug: run,
22     };
23     const traceOutputChannel = vscode.window.createOutputChannel(
24         'Rust Analyzer Language Server Trace',
25     );
26
27     const clientOptions: lc.LanguageClientOptions = {
28         documentSelector: [{ scheme: 'file', language: 'rust' }],
29         initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
30         traceOutputChannel,
31         middleware: {
32             // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
33             async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature) {
34                 const res = await next(document, token);
35                 if (res === undefined) throw new Error('busy');
36                 return res;
37             },
38             // Using custom handling of CodeActions where each code action is resloved lazily
39             // That's why we are not waiting for any command or edits
40             async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
41                 const params: lc.CodeActionParams = {
42                     textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
43                     range: client.code2ProtocolConverter.asRange(range),
44                     context: client.code2ProtocolConverter.asCodeActionContext(context)
45                 };
46                 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
47                     if (values === null) return undefined;
48                     const result: (vscode.CodeAction | vscode.Command)[] = [];
49                     const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
50                     for (const item of values) {
51                         // In our case we expect to get code edits only from diagnostics
52                         if (lc.CodeAction.is(item)) {
53                             assert(!item.command, "We don't expect to receive commands in CodeActions");
54                             const action = client.protocol2CodeConverter.asCodeAction(item);
55                             result.push(action);
56                             continue;
57                         }
58                         assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
59                         const action = new vscode.CodeAction(item.title);
60                         const group = (item as any).group;
61                         const id = (item as any).id;
62                         const resolveParams: ra.ResolveCodeActionParams = {
63                             id: id,
64                             // TODO: delete after discussions if needed
65                             label: item.title,
66                             codeActionParams: params
67                         };
68                         action.command = {
69                             command: "rust-analyzer.resolveCodeAction",
70                             title: item.title,
71                             arguments: [resolveParams],
72                         };
73                         if (group) {
74                             let entry = groups.get(group);
75                             if (!entry) {
76                                 entry = { index: result.length, items: [] };
77                                 groups.set(group, entry);
78                                 result.push(action);
79                             }
80                             entry.items.push(action);
81                         } else {
82                             result.push(action);
83                         }
84                     }
85                     for (const [group, { index, items }] of groups) {
86                         if (items.length === 1) {
87                             result[index] = items[0];
88                         } else {
89                             const action = new vscode.CodeAction(group);
90                             action.command = {
91                                 command: "rust-analyzer.applyActionGroup",
92                                 title: "",
93                                 arguments: [items.map((item) => {
94                                     return { label: item.title, arguments: item.command!!.arguments!![0] };
95                                 })],
96                             };
97                             result[index] = action;
98                         }
99                     }
100                     return result;
101                 },
102                     (_error) => undefined
103                 );
104             }
105
106         } as any
107     };
108
109     const client = new lc.LanguageClient(
110         'rust-analyzer',
111         'Rust Analyzer Language Server',
112         serverOptions,
113         clientOptions,
114     );
115
116     // To turn on all proposed features use: client.registerProposedFeatures();
117     // Here we want to enable CallHierarchyFeature and SemanticTokensFeature
118     // since they are available on stable.
119     // Note that while these features are stable in vscode their LSP protocol
120     // implementations are still in the "proposed" category for 3.16.
121     client.registerFeature(new CallHierarchyFeature(client));
122     client.registerFeature(new SemanticTokensFeature(client));
123     client.registerFeature(new ExperimentalFeatures());
124
125     return client;
126 }
127
128 class ExperimentalFeatures implements lc.StaticFeature {
129     fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
130         const caps: any = capabilities.experimental ?? {};
131         caps.snippetTextEdit = true;
132         caps.codeActionGroup = true;
133         caps.resolveCodeAction = true;
134         capabilities.experimental = caps;
135     }
136     initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
137     }
138 }
139
140 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
141     const candidate: lc.CodeAction = value;
142     return candidate && Is.string(candidate.title) &&
143         (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
144         (candidate.kind === void 0 || Is.string(candidate.kind)) &&
145         (candidate.edit === void 0 && candidate.command === void 0);
146 }