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