Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat: support textDocument/inlayHint request from 3.17.0 spec #566

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Maintained by a [community of contributors](https://github.com/typescript-langua
- [Inlay hints \(`typescript/inlayHints`\) \(experimental\)](#inlay-hints-typescriptinlayhints-experimental)
- [Callers and callees \(`textDocument/calls`\) \(experimental\)](#callers-and-callees-textdocumentcalls-experimental)
- [Supported Protocol features](#supported-protocol-features)
- [Experimental](#experimental)
- [Development](#development)
- [Build](#build)
- [Test](#test)
Expand Down Expand Up @@ -379,6 +380,8 @@ Most of the time, you'll execute commands with arguments retrieved from another

## Inlay hints (`typescript/inlayHints`) (experimental)

> !!! This implementation is deprecated. Use the spec-compliant `textDocument/inlayHint` request instead. !!!

Supports experimental inline hints.

```ts
Expand Down Expand Up @@ -501,28 +504,32 @@ interface DefinitionSymbol {

## Supported Protocol features

- [x] textDocument/codeAction
- [x] textDocument/completion (incl. `completion/resolve`)
- [x] textDocument/definition
- [x] textDocument/didChange (incremental)
- [x] textDocument/didClose
- [x] textDocument/didOpen
- [x] textDocument/didSave
- [x] textDocument/codeAction
- [x] textDocument/completion (incl. completion/resolve)
- [x] textDocument/definition
- [x] textDocument/documentHighlight
- [x] textDocument/documentSymbol
- [x] textDocument/executeCommand
- [x] textDocument/formatting
- [x] textDocument/rangeFormatting
- [x] textDocument/hover
- [x] textDocument/rename
- [x] textDocument/inlayHint (no support for `inlayHint/resolve` or `workspace/inlayHint/refresh`)
- [x] textDocument/rangeFormatting
- [x] textDocument/references
- [x] textDocument/rename
- [x] textDocument/signatureHelp
- [x] textDocument/calls (experimental)
- [x] typescript/inlayHints (experimental, supported from Typescript v4.4.2)
- [x] workspace/symbol
- [x] workspace/didChangeConfiguration
- [x] workspace/executeCommand

### Experimental

- [x] textDocument/calls (experimental)
- [x] typescript/inlayHints (experimental, supported from Typescript v4.4.2) DEPRECATED (use `textDocument/inlayHint` instead)

## Development

### Build
Expand Down
100 changes: 100 additions & 0 deletions src/features/inlay-hints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2022 TypeFox and others.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*/
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import tsp from 'typescript/lib/protocol.d.js';
import * as lsp from 'vscode-languageserver';
import API from '../utils/api.js';
import type { ConfigurationManager } from '../configuration-manager.js';
import type { LspDocuments } from '../document.js';
import type { TspClient } from '../tsp-client.js';
import type { LspClient } from '../lsp-client.js';
import { CommandTypes } from '../tsp-command-types.js';
import { Position } from '../utils/typeConverters.js';
import { uriToPath } from '../protocol-translation.js';

export class TypeScriptInlayHintsProvider {
public static readonly minVersion = API.v440;

public static async provideInlayHints(
uri: lsp.DocumentUri,
range: lsp.Range,
documents: LspDocuments,
tspClient: TspClient,
lspClient: LspClient,
configurationManager: ConfigurationManager
): Promise<lsp.InlayHint[]> {
if (tspClient.apiVersion.lt(TypeScriptInlayHintsProvider.minVersion)) {
lspClient.showErrorMessage('Inlay Hints request failed. Requires TypeScript 4.4+.');
return [];
}

const file = uriToPath(uri);

if (!file) {
lspClient.showErrorMessage('Inlay Hints request failed. No resource provided.');
return [];
}

const document = documents.get(file);

if (!document) {
lspClient.showErrorMessage('Inlay Hints request failed. File not opened in the editor.');
return [];
}

if (!areInlayHintsEnabledForFile(configurationManager, file)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this check necessary?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Otherwise, even with all inlay hint options disabled, the server would still do expensive processing that takes a significant amount of time. The old implementation suffered from that which I've realized when working on this.

return [];
}

await configurationManager.configureGloballyFromDocument(file);

const start = document.offsetAt(range.start);
const length = document.offsetAt(range.end) - start;

const response = await tspClient.request(CommandTypes.ProvideInlayHints, { file, start, length });
if (response.type !== 'response' || !response.success || !response.body) {
return [];
}

return response.body.map<lsp.InlayHint>(hint => {
const inlayHint = lsp.InlayHint.create(
Position.fromLocation(hint.position),
hint.text,
fromProtocolInlayHintKind(hint.kind));
hint.whitespaceBefore && (inlayHint.paddingLeft = true);
hint.whitespaceAfter && (inlayHint.paddingRight = true);
return inlayHint;
});
}
}

function areInlayHintsEnabledForFile(configurationManager: ConfigurationManager, filename: string) {
const preferences = configurationManager.getPreferences(filename);

// Doesn't need to include `includeInlayVariableTypeHintsWhenTypeMatchesName` as it depends
// on `includeInlayVariableTypeHints` being enabled.
return preferences.includeInlayParameterNameHints === 'literals' ||
preferences.includeInlayParameterNameHints === 'all' ||
preferences.includeInlayEnumMemberValueHints ||
preferences.includeInlayFunctionLikeReturnTypeHints ||
preferences.includeInlayFunctionParameterTypeHints ||
preferences.includeInlayPropertyDeclarationTypeHints ||
preferences.includeInlayVariableTypeHints;
}

function fromProtocolInlayHintKind(kind: tsp.InlayHintKind): lsp.InlayHintKind | undefined {
switch (kind) {
case 'Parameter': return lsp.InlayHintKind.Parameter;
case 'Type': return lsp.InlayHintKind.Type;
case 'Enum': return undefined;
default: return undefined;
}
}
3 changes: 2 additions & 1 deletion src/lsp-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,12 @@ export function createLspConnection(options: IServerOptions): lsp.Connection {
connection.onSignatureHelp(server.signatureHelp.bind(server));
connection.onWorkspaceSymbol(server.workspaceSymbol.bind(server));
connection.onFoldingRanges(server.foldingRanges.bind(server));
connection.languages.inlayHint.on(server.inlayHints.bind(server));

// proposed `textDocument/calls` request
connection.onRequest(lspcalls.CallsRequest.type, server.calls.bind(server));

connection.onRequest(lspinlayHints.type, server.inlayHints.bind(server));
connection.onRequest(lspinlayHints.type, server.inlayHintsLegacy.bind(server));

connection.onRequest(lsp.SemanticTokensRequest.type, server.semanticTokensFull.bind(server));
connection.onRequest(lsp.SemanticTokensRangeRequest.type, server.semanticTokensRange.bind(server));
Expand Down
25 changes: 24 additions & 1 deletion src/lsp-server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1937,7 +1937,30 @@ describe('inlayHints', () => {
`
};
server.didOpenTextDocument({ textDocument: doc });
const { inlayHints } = await server.inlayHints({ textDocument: doc });
const inlayHints = await server.inlayHints({ textDocument: doc, range: lsp.Range.create(0, 0, 4, 0) });
assert.isDefined(inlayHints);
assert.strictEqual(inlayHints!.length, 1);
assert.deepEqual(inlayHints![0], {
label: ': number',
position: { line: 1, character: 29 },
kind: lsp.InlayHintKind.Type,
paddingLeft: true
});
});

it('inlayHints (legacy)', async () => {
const doc = {
uri: uri('module.ts'),
languageId: 'typescript',
version: 1,
text: `
export function foo() {
return 3
}
`
};
server.didOpenTextDocument({ textDocument: doc });
const { inlayHints } = await server.inlayHintsLegacy({ textDocument: doc });
assert.isDefined(inlayHints);
assert.strictEqual(inlayHints.length, 1);
assert.strictEqual(inlayHints[0].text, ': number');
Expand Down
13 changes: 12 additions & 1 deletion src/lsp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { computeCallers, computeCallees } from './calls.js';
import { IServerOptions } from './utils/configuration.js';
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider.js';
import { TypeScriptAutoFixProvider } from './features/fix-all.js';
import { TypeScriptInlayHintsProvider } from './features/inlay-hints.js';
import { SourceDefinitionCommand } from './features/source-definition.js';
import { LspClient } from './lsp-client.js';
import { Position, Range } from './utils/typeConverters.js';
Expand Down Expand Up @@ -291,6 +292,7 @@ export class LspServer {
]
},
hoverProvider: true,
inlayHintProvider: true,
renameProvider: true,
referencesProvider: true,
signatureHelpProvider: {
Expand Down Expand Up @@ -1187,7 +1189,16 @@ export class LspServer {
return callsResult;
}

async inlayHints(params: lspinlayHints.InlayHintsParams): Promise<lspinlayHints.InlayHintsResult> {
async inlayHints(params: lsp.InlayHintParams): Promise<lsp.InlayHint[] | undefined> {
return await TypeScriptInlayHintsProvider.provideInlayHints(
params.textDocument.uri, params.range, this.documents, this.tspClient, this.options.lspClient, this.configurationManager);
}

async inlayHintsLegacy(params: lspinlayHints.InlayHintsParams): Promise<lspinlayHints.InlayHintsResult> {
this.options.lspClient.logMessage({
message: 'Support for experimental "typescript/inlayHints" request is deprecated. Use spec-compliant "textDocument/inlayHint" instead.',
type: lsp.MessageType.Warning
});
const file = uriToPath(params.textDocument.uri);
this.logger.log('inlayHints', params, file);
if (!file) {
Expand Down