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