Skip to content
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

Add inlay hint support #342

Merged
merged 2 commits into from
Jun 23, 2023
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning][semver].
- Add `LanguageClient` with LSP methods autogenerated from type annotations in `lsprotocol` ([#328])
- Add base JSON-RPC `Client` with support for running servers in a subprocess and communicating over stdio. ([#328])
- Support work done progress cancel ([#253])
- Add support for `textDocument/inlayHint` and `inlayHint/resolve` requests ([#342])

### Changed
### Fixed
Expand All @@ -22,6 +23,7 @@ and this project adheres to [Semantic Versioning][semver].
[#334]: https://github.com/openlawlibrary/pygls/issues/334
[#338]: https://github.com/openlawlibrary/pygls/discussions/338
[#253]: https://github.com/openlawlibrary/pygls/pull/253
[#342]: https://github.com/openlawlibrary/pygls/pull/342


## [1.0.2] - May 15th, 2023
Expand Down
82 changes: 82 additions & 0 deletions examples/servers/inlay_hints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
############################################################################
# Copyright(c) Open Law Library. All rights reserved. #
# See ThirdPartyNotices.txt in the project root for additional notices. #
# #
# 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 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
import re
from typing import Optional

from pygls.server import LanguageServer
from lsprotocol.types import (
INLAY_HINT_RESOLVE,
TEXT_DOCUMENT_INLAY_HINT,
InlayHint,
InlayHintKind,
InlayHintParams,
Position,
)

NUMBER = re.compile(r"\d+")
server = LanguageServer("inlay-hint-server", "v0.1")


def parse_int(chars: str) -> Optional[int]:
try:
return int(chars)
except Exception:
return None


@server.feature(TEXT_DOCUMENT_INLAY_HINT)
def inlay_hints(params: InlayHintParams):
items = []
document_uri = params.text_document.uri
document = server.workspace.get_document(document_uri)

start_line = params.range.start.line
end_line = params.range.end.line

lines = document.lines[start_line : end_line + 1]
for lineno, line in enumerate(lines):
for match in NUMBER.finditer(line):
if not match:
continue

number = parse_int(match.group(0))
if number is None:
continue

binary_num = bin(number).split('b')[1]
items.append(
InlayHint(
label=f":{binary_num}",
kind=InlayHintKind.Type,
padding_left=False,
padding_right=True,
position=Position(line=lineno, character=match.end()),
)
)

return items


@server.feature(INLAY_HINT_RESOLVE)
def inlay_hint_resolve(hint: InlayHint):
n = int(hint.label[1:], 2)
hint.tooltip = f"Binary representation of the number: {n}"
return hint


if __name__ == "__main__":
server.start_io()
14 changes: 11 additions & 3 deletions pygls/capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
from typing import Any

from lsprotocol.types import (
TEXT_DOCUMENT_CODE_ACTION, TEXT_DOCUMENT_CODE_LENS,
INLAY_HINT_RESOLVE, TEXT_DOCUMENT_CODE_ACTION, TEXT_DOCUMENT_CODE_LENS,
TEXT_DOCUMENT_COMPLETION, TEXT_DOCUMENT_DECLARATION,
TEXT_DOCUMENT_DEFINITION, TEXT_DOCUMENT_DOCUMENT_COLOR,
TEXT_DOCUMENT_DOCUMENT_HIGHLIGHT, TEXT_DOCUMENT_DOCUMENT_LINK,
TEXT_DOCUMENT_DOCUMENT_SYMBOL, TEXT_DOCUMENT_FOLDING_RANGE,
TEXT_DOCUMENT_FORMATTING, TEXT_DOCUMENT_HOVER,
TEXT_DOCUMENT_IMPLEMENTATION, TEXT_DOCUMENT_ON_TYPE_FORMATTING,
TEXT_DOCUMENT_IMPLEMENTATION, TEXT_DOCUMENT_INLAY_HINT, TEXT_DOCUMENT_ON_TYPE_FORMATTING,
TEXT_DOCUMENT_RANGE_FORMATTING, TEXT_DOCUMENT_REFERENCES,
TEXT_DOCUMENT_RENAME, TEXT_DOCUMENT_SELECTION_RANGE,
TEXT_DOCUMENT_SIGNATURE_HELP, TEXT_DOCUMENT_PREPARE_CALL_HIERARCHY,
Expand All @@ -36,7 +36,7 @@
TEXT_DOCUMENT_TYPE_DEFINITION, WORKSPACE_DID_CREATE_FILES,
WORKSPACE_DID_DELETE_FILES, WORKSPACE_DID_RENAME_FILES,
WORKSPACE_SYMBOL, WORKSPACE_WILL_CREATE_FILES,
WORKSPACE_WILL_DELETE_FILES, WORKSPACE_WILL_RENAME_FILES
WORKSPACE_WILL_DELETE_FILES, WORKSPACE_WILL_RENAME_FILES, InlayHintOptions
)
from lsprotocol.types import (
ClientCapabilities, CodeLensOptions, CompletionOptions,
Expand Down Expand Up @@ -164,6 +164,13 @@ def _with_type_definition(self):
self.server_cap.type_definition_provider = value
return self

def _with_inlay_hints(self):
value = self._provider_options(TEXT_DOCUMENT_INLAY_HINT, default=InlayHintOptions())
if value is not None:
value.resolve_provider = INLAY_HINT_RESOLVE in self.features
self.server_cap.inlay_hint_provider = value
return self

def _with_implementation(self):
value = self._provider_options(
TEXT_DOCUMENT_IMPLEMENTATION, default=ImplementationOptions()
Expand Down Expand Up @@ -358,6 +365,7 @@ def build(self):
._with_declaration()
._with_definition()
._with_type_definition()
._with_inlay_hints()
._with_implementation()
._with_references()
._with_document_highlight()
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ python_requires = >=3.7,<4
packages = find:
zip_safe = False
install_requires =
lsprotocol
lsprotocol==2023.0.0a2
typeguard>=3,<4
include_package_data = True
tests_require =
Expand Down
91 changes: 91 additions & 0 deletions tests/lsp/test_inlay_hints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
############################################################################
# Copyright(c) Open Law Library. All rights reserved. #
# See ThirdPartyNotices.txt in the project root for additional notices. #
# #
# 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 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
import sys

import pytest
import pytest_asyncio
from lsprotocol.types import (
ClientCapabilities,
InlayHint,
InlayHintParams,
InitializeParams,
Position,
Range,
TextDocumentIdentifier,
)

import pygls.uris as uri
from pygls import IS_PYODIDE
from pygls.lsp.client import LanguageClient


@pytest_asyncio.fixture()
async def client(server_dir):
"""Setup and teardown the client."""

server_py = server_dir / "inlay_hints.py"

client = LanguageClient("pygls-test-client", "0.1")
await client.start_io(sys.executable, str(server_py))

yield client

await client.shutdown_async(None)
client.exit(None)

await client.stop()


@pytest.mark.skipif(IS_PYODIDE, reason="subprocesses are not available in pyodide.")
async def test_code_actions(client: LanguageClient, workspace_dir):
"""Ensure that the example code action server is working as expected."""

response = await client.initialize_async(
InitializeParams(
capabilities=ClientCapabilities(),
root_uri=uri.from_fs_path(str(workspace_dir)),
)
)
assert response is not None

inlay_hint_provider = response.capabilities.inlay_hint_provider
assert inlay_hint_provider.resolve_provider is True

test_uri = uri.from_fs_path(str(workspace_dir / "sums.txt"))
assert test_uri is not None

response = await client.text_document_inlay_hint_async(
InlayHintParams(
text_document=TextDocumentIdentifier(uri=test_uri),
range=Range(
start=Position(line=3, character=0),
end=Position(line=4, character=0),
),
)
)

assert len(response) == 2
two, three = response[0], response[1]

assert two.label == ":10"
assert two.tooltip is None

assert three.label == ":11"
assert three.tooltip is None

resolved = await client.inlay_hint_resolve_async(three)
assert resolved.tooltip == "Binary representation of the number: 3"
35 changes: 35 additions & 0 deletions tests/test_feature_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@ def server_capabilities(**kwargs):
)
),
),
(
lsp.TEXT_DOCUMENT_INLAY_HINT,
None,
lsp.ClientCapabilities(),
server_capabilities(
inlay_hint_provider=lsp.InlayHintOptions(resolve_provider=False),
)
),
(
lsp.WORKSPACE_WILL_CREATE_FILES,
lsp.FileOperationRegistrationOptions(
Expand Down Expand Up @@ -615,3 +623,30 @@ def _():
).build()

assert expected == actual


def test_register_inlay_hint_resolve(
feature_manager: FeatureManager,
):

@feature_manager.feature(lsp.TEXT_DOCUMENT_INLAY_HINT)
def _():
pass

@feature_manager.feature(lsp.INLAY_HINT_RESOLVE)
def _():
pass

expected = server_capabilities(
inlay_hint_provider=lsp.InlayHintOptions(resolve_provider=True),
)

actual = ServerCapabilitiesBuilder(
lsp.ClientCapabilities(),
feature_manager.features.keys(),
feature_manager.feature_options,
[],
None,
).build()

assert expected == actual