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