]> git.lizzy.rs Git - rust.git/blob - editors/code/src/client.ts
beta version for folder rename
[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 workspace:lc.WorkspaceMiddleware = {
55         willRenameFiles:function<P extends vscode.FileRenameEvent,R extends Thenable<vscode.WorkspaceEdit | null | undefined>>(this: void, data: P, next:(data: P) => R ){
56             // why add this function rather than default:
57             // 1. change `url` parameter to happy format for url crate. (folder should end with '/')
58             // 2. filter some change in here.
59             //     2.1 rename from or to `mod.rs` should be special. 
60             //     2.2 not all folder change should be cared, only those have files with ".rs" postfix.
61             return next(data);
62         }
63     }
64
65     const clientOptions: lc.LanguageClientOptions = {
66         documentSelector: [{ scheme: 'file', language: 'rust' }],
67         initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
68         diagnosticCollectionName: "rustc",
69         traceOutputChannel,
70         middleware: {
71             workspace,
72             provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
73                 return semanticHighlightingWorkaround(next, document, token);
74             },
75             provideDocumentSemanticTokensEdits(document: vscode.TextDocument, previousResultId: string, token: vscode.CancellationToken, next: DocumentSemanticsTokensEditsSignature): vscode.ProviderResult<vscode.SemanticTokensEdits | vscode.SemanticTokens> {
76                 return semanticHighlightingWorkaround(next, document, previousResultId, token);
77             },
78             provideDocumentRangeSemanticTokens(document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken, next: DocumentRangeSemanticTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
79                 return semanticHighlightingWorkaround(next, document, range, token);
80             },
81             async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
82                 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
83                     (result) => {
84                         const hover = client.protocol2CodeConverter.asHover(result);
85                         if (hover) {
86                             const actions = (<any>result).actions;
87                             if (actions) {
88                                 hover.contents.push(renderHoverActions(actions));
89                             }
90                         }
91                         return hover;
92                     },
93                     (error) => {
94                         client.handleFailedRequest(lc.HoverRequest.type, error, null);
95                         return Promise.resolve(null);
96                     });
97             },
98             // Using custom handling of CodeActions to support action groups and snippet edits.
99             // Note that this means we have to re-implement lazy edit resolving ourselves as well.
100             async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
101                 const params: lc.CodeActionParams = {
102                     textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
103                     range: client.code2ProtocolConverter.asRange(range),
104                     context: client.code2ProtocolConverter.asCodeActionContext(context)
105                 };
106                 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
107                     if (values === null) return undefined;
108                     const result: (vscode.CodeAction | vscode.Command)[] = [];
109                     const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
110                     for (const item of values) {
111                         // In our case we expect to get code edits only from diagnostics
112                         if (lc.CodeAction.is(item)) {
113                             assert(!item.command, "We don't expect to receive commands in CodeActions");
114                             const action = client.protocol2CodeConverter.asCodeAction(item);
115                             result.push(action);
116                             continue;
117                         }
118                         assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
119                         const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
120                         const action = new vscode.CodeAction(item.title, kind);
121                         const group = (item as any).group;
122                         action.command = {
123                             command: "rust-analyzer.resolveCodeAction",
124                             title: item.title,
125                             arguments: [item],
126                         };
127
128                         // Set a dummy edit, so that VS Code doesn't try to resolve this.
129                         action.edit = new WorkspaceEdit();
130
131                         if (group) {
132                             let entry = groups.get(group);
133                             if (!entry) {
134                                 entry = { index: result.length, items: [] };
135                                 groups.set(group, entry);
136                                 result.push(action);
137                             }
138                             entry.items.push(action);
139                         } else {
140                             result.push(action);
141                         }
142                     }
143                     for (const [group, { index, items }] of groups) {
144                         if (items.length === 1) {
145                             result[index] = items[0];
146                         } else {
147                             const action = new vscode.CodeAction(group);
148                             action.kind = items[0].kind;
149                             action.command = {
150                                 command: "rust-analyzer.applyActionGroup",
151                                 title: "",
152                                 arguments: [items.map((item) => {
153                                     return { label: item.title, arguments: item.command!!.arguments!![0] };
154                                 })],
155                             };
156
157                             // Set a dummy edit, so that VS Code doesn't try to resolve this.
158                             action.edit = new WorkspaceEdit();
159
160                             result[index] = action;
161                         }
162                     }
163                     return result;
164                 },
165                     (_error) => undefined
166                 );
167             }
168
169         }
170     };
171
172     const client = new lc.LanguageClient(
173         'rust-analyzer',
174         'Rust Analyzer Language Server',
175         serverOptions,
176         clientOptions,
177     );
178
179     // To turn on all proposed features use: client.registerProposedFeatures();
180     client.registerFeature(new ExperimentalFeatures());
181
182     return client;
183 }
184
185 class ExperimentalFeatures implements lc.StaticFeature {
186     fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
187         const caps: any = capabilities.experimental ?? {};
188         caps.snippetTextEdit = true;
189         caps.codeActionGroup = true;
190         caps.hoverActions = true;
191         caps.statusNotification = true;
192         capabilities.experimental = caps;
193     }
194     initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
195     }
196     dispose(): void {
197     }
198 }
199
200 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
201     const candidate: lc.CodeAction = value;
202     return candidate && Is.string(candidate.title) &&
203         (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
204         (candidate.kind === void 0 || Is.string(candidate.kind)) &&
205         (candidate.edit === void 0 && candidate.command === void 0);
206 }