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';
9 function renderCommand(cmd: ra.CommandLink) {
10 return `[${cmd.title}](command:${cmd.command}?${encodeURIComponent(JSON.stringify(cmd.arguments))} '${cmd.tooltip!}')`;
13 function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownString {
14 const text = actions.map(group =>
15 (group.title ? (group.title + " ") : "") + group.commands.map(renderCommand).join(' | ')
18 const result = new vscode.MarkdownString(text);
19 result.isTrusted = true;
23 // Workaround for https://github.com/microsoft/vscode-languageserver-node/issues/576
24 async function semanticHighlightingWorkaround<R, F extends (...args: any[]) => vscode.ProviderResult<R>>(next: F, ...args: Parameters<F>): Promise<R> {
25 const res = await next(...args);
26 if (res == null) throw new Error('busy');
30 export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
31 // '.' Is the fallback if no folder is open
32 // TODO?: Workspace folders support Uri's (eg: file://test.txt).
33 // It might be a good idea to test if the uri points to a file.
35 const run: lc.Executable = {
39 const serverOptions: lc.ServerOptions = {
43 const traceOutputChannel = vscode.window.createOutputChannel(
44 'Rust Analyzer Language Server Trace',
47 const clientOptions: lc.LanguageClientOptions = {
48 documentSelector: [{ scheme: 'file', language: 'rust' }],
49 initializationOptions: vscode.workspace.getConfiguration("rust-analyzer"),
50 diagnosticCollectionName: "rustc",
53 provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
54 return semanticHighlightingWorkaround(next, document, token);
56 provideDocumentSemanticTokensEdits(document: vscode.TextDocument, previousResultId: string, token: vscode.CancellationToken, next: DocumentSemanticsTokensEditsSignature): vscode.ProviderResult<vscode.SemanticTokensEdits | vscode.SemanticTokens> {
57 return semanticHighlightingWorkaround(next, document, previousResultId, token);
59 provideDocumentRangeSemanticTokens(document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken, next: DocumentRangeSemanticTokensSignature): vscode.ProviderResult<vscode.SemanticTokens> {
60 return semanticHighlightingWorkaround(next, document, range, token);
62 async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, _next: lc.ProvideHoverSignature) {
63 return client.sendRequest(lc.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(
65 const hover = client.protocol2CodeConverter.asHover(result);
67 const actions = (<any>result).actions;
69 hover.contents.push(renderHoverActions(actions));
75 client.handleFailedRequest(lc.HoverRequest.type, error, null);
76 return Promise.resolve(null);
79 // Using custom handling of CodeActions to support action groups and snippet edits.
80 // Note that this means we have to re-implement lazy edit resolving ourselves as well.
81 async provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken, _next: lc.ProvideCodeActionsSignature) {
82 const params: lc.CodeActionParams = {
83 textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
84 range: client.code2ProtocolConverter.asRange(range),
85 context: client.code2ProtocolConverter.asCodeActionContext(context)
87 return client.sendRequest(lc.CodeActionRequest.type, params, token).then((values) => {
88 if (values === null) return undefined;
89 const result: (vscode.CodeAction | vscode.Command)[] = [];
90 const groups = new Map<string, { index: number; items: vscode.CodeAction[] }>();
91 for (const item of values) {
92 // In our case we expect to get code edits only from diagnostics
93 if (lc.CodeAction.is(item)) {
94 assert(!item.command, "We don't expect to receive commands in CodeActions");
95 const action = client.protocol2CodeConverter.asCodeAction(item);
99 assert(isCodeActionWithoutEditsAndCommands(item), "We don't expect edits or commands here");
100 const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
101 const action = new vscode.CodeAction(item.title, kind);
102 const group = (item as any).group;
104 command: "rust-analyzer.resolveCodeAction",
109 // Set a dummy edit, so that VS Code doesn't try to resolve this.
110 action.edit = new WorkspaceEdit();
113 let entry = groups.get(group);
115 entry = { index: result.length, items: [] };
116 groups.set(group, entry);
119 entry.items.push(action);
124 for (const [group, { index, items }] of groups) {
125 if (items.length === 1) {
126 result[index] = items[0];
128 const action = new vscode.CodeAction(group);
129 action.kind = items[0].kind;
131 command: "rust-analyzer.applyActionGroup",
133 arguments: [items.map((item) => {
134 return { label: item.title, arguments: item.command!!.arguments!![0] };
138 // Set a dummy edit, so that VS Code doesn't try to resolve this.
139 action.edit = new WorkspaceEdit();
141 result[index] = action;
146 (_error) => undefined
153 const client = new lc.LanguageClient(
155 'Rust Analyzer Language Server',
160 // To turn on all proposed features use: client.registerProposedFeatures();
161 client.registerFeature(new ExperimentalFeatures());
166 class ExperimentalFeatures implements lc.StaticFeature {
167 fillClientCapabilities(capabilities: lc.ClientCapabilities): void {
168 const caps: any = capabilities.experimental ?? {};
169 caps.snippetTextEdit = true;
170 caps.codeActionGroup = true;
171 caps.hoverActions = true;
172 caps.statusNotification = true;
173 capabilities.experimental = caps;
175 initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {
181 function isCodeActionWithoutEditsAndCommands(value: any): boolean {
182 const candidate: lc.CodeAction = value;
183 return candidate && Is.string(candidate.title) &&
184 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
185 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
186 (candidate.edit === void 0 && candidate.command === void 0);