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 a LanguageClient autogenerated from lsprotocol type definitions #328

Merged
merged 6 commits into from
May 30, 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@ and this project adheres to [Semantic Versioning][semver].

## [Unreleased]
### Added

- 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])

### Changed
### Fixed

- `pygls` no longer overrides the event loop for the current thread when given an explicit loop to use. ([#334])

[#328]: https://github.com/openlawlibrary/pygls/issues/328
[#334]: https://github.com/openlawlibrary/pygls/issues/334


Expand Down
82 changes: 82 additions & 0 deletions examples/servers/code_actions.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 pygls.server import LanguageServer
from lsprotocol.types import (
TEXT_DOCUMENT_CODE_ACTION,
CodeAction,
CodeActionKind,
CodeActionOptions,
CodeActionParams,
Position,
Range,
TextEdit,
WorkspaceEdit,
)


ADDITION = re.compile(r"^\s*(\d+)\s*\+\s*(\d+)\s*=")
server = LanguageServer("code-action-server", "v0.1")


@server.feature(
TEXT_DOCUMENT_CODE_ACTION,
CodeActionOptions(
code_action_kinds=[CodeActionKind.QuickFix]
)
)
def code_actions(params: CodeActionParams):
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 idx, line in enumerate(lines):

match = ADDITION.match(line)
if match is not None:

range_ = Range(
start=Position(line=start_line + idx, character=0),
end=Position(line=start_line + idx, character=len(line)-1)
)

left = int(match.group(1))
right = int(match.group(2))
answer = left + right

text_edit = TextEdit(
range=range_, new_text=f"{line.strip()} {answer}!"
)

action = CodeAction(
title=f"Evaluate '{match.group(0)}'",
kind=CodeActionKind.QuickFix,
edit=WorkspaceEdit(
changes={document_uri: [text_edit]}
)
)
items.append(action)

return items


if __name__ == "__main__":
server.start_io()
7 changes: 7 additions & 0 deletions examples/workspace/sums.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
1 + 1 =


2 + 3 =


6 + 6 =
115 changes: 115 additions & 0 deletions pygls/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
############################################################################
# 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 asyncio
import logging
import re
from threading import Event
from typing import Callable
from typing import List
from typing import Optional
from typing import Type

from cattrs import Converter

from pygls.protocol import JsonRPCProtocol, default_converter


logger = logging.getLogger(__name__)


async def aio_readline(stop_event, reader, message_handler):

CONTENT_LENGTH_PATTERN = re.compile(rb'^Content-Length: (\d+)\r\n$')

# Initialize message buffer
message = []
content_length = 0

while not stop_event.is_set():
# Read a header line
header = await reader.readline()
if not header:
break
message.append(header)

# Extract content length if possible
if not content_length:
match = CONTENT_LENGTH_PATTERN.fullmatch(header)
if match:
content_length = int(match.group(1))
logger.debug('Content length: %s', content_length)

# Check if all headers have been read (as indicated by an empty line \r\n)
if content_length and not header.strip():

# Read body
body = await reader.read(content_length)
if not body:
break
message.append(body)

# Pass message to protocol
message_handler(b''.join(message))

# Reset the buffer
message = []
content_length = 0


class Client:
"""Base JSON-RPC client."""

def __init__(
self,
protocol_cls: Type[JsonRPCProtocol] = JsonRPCProtocol,
converter_factory: Callable[[], Converter] = default_converter,
):

self.protocol = protocol_cls(self, converter_factory())

self._server: Optional[asyncio.subprocess.Process] = None
self._stop_event = Event()
self._async_tasks: List[asyncio.Task] = []

async def start_io(self, cmd: str, *args, **kwargs):
"""Start the given server and communicate with it over stdio."""

server = await asyncio.create_subprocess_exec(
cmd,
*args,
stdout=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
**kwargs,
)

self.protocol.connection_made(server.stdin) # type: ignore
connection = asyncio.create_task(
aio_readline(
self._stop_event,
server.stdout,
self.protocol.data_received
)
)
self._server = server
self._async_tasks.append(connection)

async def stop(self):
self._stop_event.set()

if len(self._async_tasks) > 0:
await asyncio.gather(*self._async_tasks)
Loading