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';
10 [name: string]: string;
13 function renderCommand(cmd: ra.CommandLink) {
14 return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
17 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
18 const text = actions.map(group =>
19 (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
22 const result = new vscode.MarkdownString(text);
23 result.isTrusted = true;
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');
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.
39 const newEnv = Object.assign({}, process.env);
40 Object.assign(newEnv, extraEnv);
42 const run: lc.Executable = {
44 options: { cwd, env: newEnv },
46 const serverOptions: lc.ServerOptions = {
50 const traceOutputChannel = vscode.window.createOutputChannel(
51 'Rust Analyzer Language Server Trace',
54 const clientOptions: lc.LanguageClientOptions = {
55 documentSelector: [{ scheme: 'file', language: 'rust' }],
56 initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
57 diagnosticCollectionName: "rustc",
60 provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
61 return semanticHighlightingWorkaround(next, document, token);
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);
66 provideDocumentRangeSemanticTokens(document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken, next: DocumentRangeSemanticTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
67 return semanticHighlightingWorkaround(next, document, range, token);
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(
72 const hover = client.protocol2CodeConverter.asHover(result);
74 const actions = (<any>result).actions;
76 hover.contents.push(renderHoverActions(actions));
82 client.handleFailedRequest(lc.HoverRequest.type, error, null);
83 return Promise.resolve(null);
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)
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);
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;
111 command: "rust-analyzer.resolveCodeAction",
116 // Set a dummy edit, so that VS Code doesn't try to resolve this.
117 action.edit = new WorkspaceEdit();
120 let entry = groups.get(group);
122 entry = { index: result.length, items: [] };
123 groups.set(group, entry);
126 entry.items.push(action);
131 for (const [group, { index, items }] of groups) {
132 if (items.length === 1) {
133 result[index] = items[0];
135 const action = new vscode.CodeAction(group);
136 action.kind = items[0].kind;
138 command: "rust-analyzer.applyActionGroup",
140 arguments: [items.map((item) => {
141 return { label: item.title, arguments: item.command!!.arguments!![0] };
145 // Set a dummy edit, so that VS Code doesn't try to resolve this.
146 action.edit = new WorkspaceEdit();
148 result[index] = action;
153 (_error) => undefined
160 const client = new lc.LanguageClient(
162 'Rust Analyzer Language Server',
167 // To turn on all proposed features use: client.registerProposedFeatures();
168 client.registerFeature(new ExperimentalFeatures());
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;
182 initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
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);