diff --git a/.github/workflows/test-workflow.yaml b/.github/workflows/test-workflow.yaml index d9f26ab..836a142 100644 --- a/.github/workflows/test-workflow.yaml +++ b/.github/workflows/test-workflow.yaml @@ -89,5 +89,66 @@ jobs: pip install -r requirements.txt pip install -e . + - name: Install pinned Pyright for real integration tests + run: | + npm install --prefix "$RUNNER_TEMP/multilspy-pyright" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413 + PYRIGHT_BIN="$RUNNER_TEMP/multilspy-pyright/node_modules/.bin/pyright-langserver" + test -x "$PYRIGHT_BIN" + echo "MULTILSPY_PYRIGHT_TEST_BINARY=$PYRIGHT_BIN" >> "$GITHUB_ENV" + - name: Run tests run: pytest tests/multilspy -v --tb=short + + pyright-windows: + name: Pyright native Windows (Python ${{ matrix.python-version }}) + runs-on: windows-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.12", "3.13", "3.14"] + env: + PYTHONUTF8: "1" + + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Set up Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "20" + + - name: Install Python dependencies + run: | + python -m pip install -r requirements.txt + python -m pip install -e . + + - name: Install pinned Pyright for Windows + shell: pwsh + run: | + $root = Join-Path $env:RUNNER_TEMP "multilspy-pyright" + npm install --prefix $root --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413 + if ($LASTEXITCODE -ne 0) { throw "npm installation failed" } + $binary = Join-Path $root "node_modules/.bin/pyright-langserver.cmd" + if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Pinned Pyright not installed" } + "MULTILSPY_PYRIGHT_TEST_BINARY=$binary" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 + + - name: Test real Pyright, protocol, Unicode and lifecycle on Windows + run: >- + python -m pytest -q + tests/multilspy/test_multilspy_pyright.py + tests/multilspy/test_pyright_adapter_notifications.py + tests/multilspy/test_pyright_process_lifecycle.py + tests/multilspy/test_lsp_result_shapes.py + tests/multilspy/test_path_utils_portability.py + tests/multilspy/test_completion_responses.py + tests/multilspy/test_utf16_buffer_positions.py + tests/multilspy/test_python_completions.py + tests/multilspy/test_sync_startup.py + tests/multilspy/test_sync_file_thread.py + --tb=short diff --git a/README.md b/README.md index d9bc451..cdf407b 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ pip install multilspy | Code Language | Language Server | | --- | --- | | java | Eclipse JDTLS | -| python | jedi-language-server | +| python | jedi-language-server (default) or Pyright | | rust | Rust Analyzer | | csharp | OmniSharp / RazorSharp | | typescript | TypeScriptLanguageServer | @@ -53,6 +53,97 @@ pip install multilspy | cpp | clangd | +For Python, Jedi remains the default language server. To use Pyright instead, +install [Pyright](https://github.com/microsoft/pyright) and explicitly select +the optional backend: + +```python +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + +config = MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary="/absolute/path/to/pyright-langserver", +) +lsp = LanguageServer.create(config, MultilspyLogger(), "/path/to/python/project") +async with lsp.start_server(): + definitions = await lsp.request_definition("module.py", 10, 4) +``` + +The server binary must already be installed; the adapter adds the --stdio +argument and does not download/install Pyright. If server_binary is +omitted, it uses pyright-langserver from PATH. The existing +MultilspyConfig(code_language=Language.PYTHON) continues using Jedi. + +Positions follow LSP: line and column are zero-based and the column counts +UTF-16 code units, so a non-BMP character such as an emoji occupies two columns. +Type checking is configured by the project (pyrightconfig.json or pyproject.toml); +the adapter does not override `typeCheckingMode`. + +The adapter was validated against Pyright 1.1.413 (`pyright-langserver --stdio`). +The table lists what that release advertises to multilspy's read-only client +and how multilspy exposes it: + +| Pyright capability | multilspy access | Coverage | +| --- | --- | --- | +| definition, references, hover, document symbols, workspace symbols | `request_definition`, `request_references`, `request_hover`, `request_document_symbols`, `request_workspace_symbol` | tested against Pyright | +| completion (`isIncomplete` retries), completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright | +| declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy (incoming and outgoing) | `server.send.*` low-level requests | tested against Pyright | +| prepareRename, rename | `server.send.*`; the response is a WorkspaceEdit proposal, multilspy never applies it | proposal shape tested | +| codeAction (quickfix, source.organizeImports) | `server.send.code_action`; available fixes depend on project diagnostics and may propose file edits, including type-stub generation or renames; organize imports uses a command | empty-response fixture tested; no writable quick-fix corpus | +| publishDiagnostics (typeCheckingMode off/basic/standard/strict) | asynchronous `PyrightServer.next_diagnostics()` bounded queue (not exposed by `SyncLanguageServer`) | tested against Pyright | +| workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration acknowledged and ignored | tested with fixtures and against Pyright | +| executeCommand | advertised with an empty command list; `pyright.organizeimports` is disabled by the adapter settings, `pyright.createtypestub` writes files and is not supported | refusal of the server's applyEdit tested | +| implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised to the current client capability profile by Pyright 1.1.413; requests fail with MethodNotFound | unsupported in this profile | + +Real Pyright integration tests require a preinstalled language server. Set +MULTILSPY_PYRIGHT_TEST_BINARY to its absolute executable path before running +pytest on tests/multilspy/test_multilspy_pyright.py. Without this variable +the real-server tests skip; if it is set to a missing/non-executable binary, +the tests fail. The GitHub Actions test workflow installs pinned Pyright +1.1.413 and exercises the real provider on every Python test matrix entry. +Other local unit/fixture tests still run without installing Pyright. +Exact-protocol fixtures and capabilities are version-pinned; when upgrading +Pyright, update and revalidate the expected responses rather than silently +skipping mismatched versions. For third-party import resolution, configure the +project through `pyrightconfig.json` or `[tool.pyright]` in `pyproject.toml`. + +By default, Pyright's `workspace/applyEdit` requests are refused and organize +imports is disabled. To support editor-controlled writes, the embedding client +can register an **async** handler before starting the server: + +```python +# `lsp` is a PyrightServer returned by LanguageServer.create(...). +async def apply_workspace_edit(params): + # Validate affected URIs, ranges, document versions and user permission. + # Handle BOTH `changes` and `documentChanges` (including file operations) + # and apply the edit atomically in YOUR editor/workspace layer. + return {"applied": False, "failureReason": "Not approved"} + +lsp.set_workspace_edit_handler(apply_workspace_edit, timeout_seconds=60) +``` + +When a handler is installed, the adapter advertises workspace `applyEdit` +support and enables Pyright organize-imports commands. The handler's LSP +response reports whether **the client actually applied the edit**. A successful +rename request by itself returns an edit *proposal*; multilspy does not apply +that proposal. It is the caller's responsibility to preview, approve, and +apply the WorkspaceEdit, including document versions and file operations. +If documents are already open, update both the editor's in-memory buffers +and the language server's `didChange` state; writing the disk copy alone leaves +the LSP document snapshot stale. Handler exceptions and timeouts are reported +as unsuccessful edits and never treated as authorization to write. + +**Security boundary:** this opt-in callback is NOT a subprocess sandbox. +In Pyright 1.1.413, `pyright.createtypestub` directly writes `.pyi` files on +the language-server side without calling `workspace/applyEdit`. Other raw +`server.send.execute_command` calls may have similar side effects. Never expose +arbitrary commands to untrusted callers; use OS-level filesystem restrictions +and isolated workspaces for untrusted projects. An embedding application must enforce its own workspace authorization and +process confinement independently of multilspy's generic LSP integration. + ## Usage Example usage: ```python diff --git a/src/multilspy/language_server.py b/src/multilspy/language_server.py index dbf75b5..4663d52 100644 --- a/src/multilspy/language_server.py +++ b/src/multilspy/language_server.py @@ -74,6 +74,14 @@ def create(cls, config: MultilspyConfig, logger: MultilspyLogger, repository_roo :return LanguageServer: A language specific LanguageServer instance. """ if config.code_language == Language.PYTHON: + if config.python_server == "pyright": + from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, + ) + + return PyrightServer(config, logger, repository_root_path) + if config.python_server != "jedi": + raise MultilspyException("Unsupported Python language server") from multilspy.language_servers.jedi_language_server.jedi_server import ( JediServer, ) @@ -425,8 +433,7 @@ async def request_definition( new_item["relativePath"] = PathUtils.get_relative_path(new_item["absolutePath"], self.repository_root_path) ret.append(multilspy_types.Location(new_item)) elif ( - LSPConstants.ORIGIN_SELECTION_RANGE in item - and LSPConstants.TARGET_URI in item + LSPConstants.TARGET_URI in item and LSPConstants.TARGET_RANGE in item and LSPConstants.TARGET_SELECTION_RANGE in item ): @@ -490,6 +497,8 @@ async def request_references( ) ret: List[multilspy_types.Location] = [] + if response is None: + return ret assert isinstance(response, list), f"Unexpected response from Language Server: {response}" for item in response: assert isinstance(item, dict) @@ -539,6 +548,9 @@ async def request_completions( response = {"items": response, "isIncomplete": False} if not response["isIncomplete"]: break + completion_params["context"] = { + "triggerKind": LSPTypes.CompletionTriggerKind.TriggerForIncompleteCompletions + } # TODO: Understand how to appropriately handle `isIncomplete` if response is None or (response["isIncomplete"] and not(allow_incomplete)): @@ -550,26 +562,27 @@ async def request_completions( response: List[LSPTypes.CompletionItem] = response # TODO: Handle the case when the completion is a keyword - items = [item for item in response if item["kind"] != LSPTypes.CompletionItemKind.Keyword] + items = [item for item in response if item.get("kind") != LSPTypes.CompletionItemKind.Keyword] completions_list: List[multilspy_types.CompletionItem] = [] for item in items: - assert "insertText" in item or "textEdit" in item - assert "kind" in item + # LSP CompletionItem requires label; insertText, textEdit, + # and kind are all optional. + kind = item.get("kind", LSPTypes.CompletionItemKind.Text) completion_item = {} if "detail" in item: completion_item["detail"] = item["detail"] if "label" in item: completion_item["completionText"] = item["label"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "insertText" in item: completion_item["completionText"] = item["insertText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "newText" in item["textEdit"]: completion_item["completionText"] = item["textEdit"]["newText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "range" in item["textEdit"]: new_dot_lineno, new_dot_colno = ( completion_params["position"]["line"], @@ -586,7 +599,7 @@ async def request_completions( ) completion_item["completionText"] = item["textEdit"]["newText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "insert" in item["textEdit"]: assert False else: @@ -595,9 +608,13 @@ async def request_completions( completion_item = multilspy_types.CompletionItem(**completion_item) completions_list.append(completion_item) + # Preserve the server's completion ranking while deduplicating. + # Iterating over a set makes suggestions reorder across processes. return [ json.loads(json_repr) - for json_repr in set([json.dumps(item, sort_keys=True) for item in completions_list]) + for json_repr in dict.fromkeys( + json.dumps(item, sort_keys=True) for item in completions_list + ) ] async def request_document_symbols(self, relative_file_path: str) -> Tuple[List[multilspy_types.UnifiedSymbolInformation], Union[List[multilspy_types.TreeRepr], None]]: diff --git a/src/multilspy/language_servers/pyright_language_server/__init__.py b/src/multilspy/language_servers/pyright_language_server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/multilspy/language_servers/pyright_language_server/initialize_params.json b/src/multilspy/language_servers/pyright_language_server/initialize_params.json new file mode 100644 index 0000000..561d68f --- /dev/null +++ b/src/multilspy/language_servers/pyright_language_server/initialize_params.json @@ -0,0 +1,55 @@ +{ + "_description": "Conservative LSP 3.17 capabilities for the Python Pyright language server.", + "processId": "$processId", + "rootPath": "$rootPath", + "rootUri": "$rootUri", + "workspaceFolders": [ + {"name": "$name", "uri": "$uri"} + ], + "clientInfo": {"name": "multilspy"}, + "capabilities": { + "general": { + "positionEncodings": ["utf-16"] + }, + "workspace": { + "applyEdit": false, + "configuration": true, + "workspaceFolders": false, + "symbol": {"dynamicRegistration": false}, + "workspaceEdit": {"documentChanges": true} + }, + "textDocument": { + "definition": {"linkSupport": true}, + "declaration": {"linkSupport": true}, + "typeDefinition": {"linkSupport": true}, + "references": {}, + "hover": {"contentFormat": ["markdown", "plaintext"]}, + "completion": { + "dynamicRegistration": false, + "contextSupport": true, + "completionItem": { + "snippetSupport": false, + "documentationFormat": ["plaintext"] + } + }, + "signatureHelp": { + "dynamicRegistration": false, + "signatureInformation": { + "documentationFormat": ["plaintext"], + "parameterInformation": {"labelOffsetSupport": true} + } + }, + "rename": {"dynamicRegistration": false, "prepareSupport": true}, + "codeAction": { + "dynamicRegistration": false, + "codeActionLiteralSupport": { + "codeActionKind": {"valueSet": ["quickfix", "source.organizeImports"]} + } + }, + "callHierarchy": {"dynamicRegistration": false}, + "documentHighlight": {"dynamicRegistration": false}, + "documentSymbol": {"hierarchicalDocumentSymbolSupport": true}, + "publishDiagnostics": {"relatedInformation": true} + } + } +} diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py new file mode 100644 index 0000000..f683aff --- /dev/null +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -0,0 +1,271 @@ +""" +Provides Python specific instantiation of the LanguageServer class using Pyright. +Contains various configurations and settings specific to Pyright. +""" + +import asyncio +import inspect +import json +import logging +import math +import os +import pathlib +import shutil +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager + +from multilspy.language_server import LanguageServer +from multilspy.lsp_protocol_handler.lsp_types import InitializeParams +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo +from multilspy.multilspy_exceptions import MultilspyException +from multilspy.multilspy_config import MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +class PyrightServer(LanguageServer): + """ + Provides Python specific instantiation of the LanguageServer class using pyright-langserver. + Pyright is opt-in: select it with MultilspyConfig(python_server="pyright"). + The executable must be preinstalled; multilspy does not download it. + """ + + def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str): + """ + Creates a PyrightServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. + """ + executable = config.server_binary or "pyright-langserver" + # npm exposes .cmd shims on Windows; resolve through PATHEXT before + # passing the executable to subprocess (which runs without a shell). + if os.name == "nt": + executable = shutil.which(executable) or executable + super().__init__( + config, + logger, + repository_root_path, + ProcessLaunchInfo(cmd=[executable, "--stdio"], cwd=repository_root_path), + "python", + ) + self._initialize_timeout_seconds = 30 + self._shutdown_timeout_seconds = 10 + # Pyright pushes textDocument/publishDiagnostics asynchronously. Keep a + # bounded queue so callers can read them without unbounded growth. + self.diagnostics: asyncio.Queue = asyncio.Queue(maxsize=64) + self.diagnostics_dropped = False + # Applying an LSP WorkspaceEdit belongs to the embedding client. A + # callback must be installed explicitly before starting the server. + self._workspace_edit_handler: Callable[[dict], Awaitable[dict]] | None = None + self._workspace_edit_timeout_seconds = 30.0 + + def set_workspace_edit_handler( + self, handler: Callable[[dict], Awaitable[dict]] | None, + *, timeout_seconds: float = 30.0, + ) -> None: + """Opt in to processing server-requested workspace edits. + + The callback receives the original ApplyWorkspaceEditParams and must + authorize and apply the proposed edit, returning an LSP response such + as ``{"applied": True}``. No filesystem changes are made by this + adapter. This does NOT restrict commands that write directly on the + Pyright server side; callers must sandbox untrusted server processes. + """ + if self.server_started: + raise MultilspyException("Cannot change workspace edit handler while running") + if handler is not None and not inspect.iscoroutinefunction(handler): + raise TypeError("Workspace edit handler must be an async function or None") + if (not isinstance(timeout_seconds, (int, float)) or + not math.isfinite(timeout_seconds) or timeout_seconds <= 0): + raise ValueError("Workspace edit timeout must be a positive finite number") + self._workspace_edit_handler = handler + self._workspace_edit_timeout_seconds = timeout_seconds + + def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: + """ + Returns the initialize params for the Pyright Language Server. + """ + with open(os.path.join(os.path.dirname(__file__), "initialize_params.json"), "r") as f: + d = json.load(f) + + del d["_description"] + + d["processId"] = os.getpid() + assert d["rootPath"] == "$rootPath" + d["rootPath"] = repository_absolute_path + + assert d["rootUri"] == "$rootUri" + d["rootUri"] = pathlib.Path(repository_absolute_path).as_uri() + + assert d["workspaceFolders"][0]["uri"] == "$uri" + d["workspaceFolders"][0]["uri"] = pathlib.Path(repository_absolute_path).as_uri() + + assert d["workspaceFolders"][0]["name"] == "$name" + d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path) + + # Advertise application support only when an embedding client has + # explicitly supplied a handler that authorizes and applies edits. + d["capabilities"]["workspace"]["applyEdit"] = self._workspace_edit_handler is not None + return d + + async def next_diagnostics(self, timeout: float = 5.0) -> dict: + """ + Returns the next queued textDocument/publishDiagnostics notification, waiting at most `timeout` seconds. + """ + return await asyncio.wait_for(self.diagnostics.get(), timeout) + + @asynccontextmanager + async def start_server(self) -> AsyncIterator["PyrightServer"]: + """ + Starts the Pyright Language Server, waits for the server to be ready and yields the LanguageServer instance. + + Usage: + ``` + async with lsp.start_server(): + # LanguageServer has been initialized and ready to serve requests + await lsp.request_definition(...) + await lsp.request_references(...) + # Shutdown the LanguageServer on exit from scope + # LanguageServer has been shutdown + ``` + """ + if self.server_started: + raise MultilspyException("Pyright language server is already started") + + async def workspace_configuration(params): + # Pyright asks for the "python", "python.analysis" and "pyright" + # sections. Answer with fixed, read-only settings; project settings + # come from pyrightconfig.json / pyproject.toml in the workspace. + if not isinstance(params, dict): + return [] + items = params.get("items") + if not isinstance(items, list): + return [] + if len(items) > 64: + # LSP requires one response per requested configuration item. + return [None] * len(items) + settings = { + "python": {"analysis": {}}, + "python.analysis": {}, + "pyright": { + "disableLanguageServices": False, + "disableOrganizeImports": self._workspace_edit_handler is None, + }, + } + answers = [] + for item in items: + section = item.get("section") if isinstance(item, dict) else None + answers.append(settings.get(section) if isinstance(section, str) else None) + return answers + + async def workspace_apply_edit(params): + if self._workspace_edit_handler is None: + return {"applied": False, "failureReason": "multilspy Pyright client is read-only"} + try: + response = await asyncio.wait_for( + self._workspace_edit_handler(params), + timeout=self._workspace_edit_timeout_seconds, + ) + if not isinstance(response, dict) or type(response.get("applied")) is not bool: + raise ValueError("Invalid LSP workspace edit result") + result = {"applied": response["applied"]} + if not result["applied"]: + if "failureReason" in response: + reason = response["failureReason"] + if not isinstance(reason, str): + raise ValueError("Invalid workspace edit failureReason") + result["failureReason"] = reason[:256] + if "failedChange" in response: + number = response["failedChange"] + if type(number) is not int or number < 0: + raise ValueError("Invalid workspace edit failedChange") + result["failedChange"] = number + return result + except asyncio.TimeoutError: + self.logger.log("LSP: workspace edit handler timed out", logging.WARNING) + return {"applied": False, "failureReason": "Workspace edit handler timed out"} + except Exception as exc: + # Never report applied=true when a client edit failed, or + # echo untrusted exception messages that contain local paths. + self.logger.log( + f"LSP: workspace edit handler failed ({type(exc).__name__})", logging.WARNING + ) + return {"applied": False, "failureReason": "Workspace edit handler failed"} + + async def publish_diagnostics(params): + if not isinstance(params, dict) or not isinstance(params.get("uri"), str): + return + if self.diagnostics.full(): + # Keep the newest diagnostic state rather than permanently + # losing updates when the consumer falls behind. + self.diagnostics_dropped = True + self.diagnostics.get_nowait() + self.diagnostics.put_nowait(params) + + async def do_nothing(params): + return + + async def window_log_message(msg): + self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO) + + self.server.on_request("client/registerCapability", do_nothing) + self.server.on_request("workspace/configuration", workspace_configuration) + self.server.on_request("workspace/applyEdit", workspace_apply_edit) + self.server.on_notification("window/logMessage", window_log_message) + self.server.on_notification("$/progress", do_nothing) + self.server.on_notification("textDocument/publishDiagnostics", publish_diagnostics) + + # A LanguageServer instance may be started more than once. Old progress + # and diagnostics must never be delivered to the next server session. + self.completions_available.clear() + self.diagnostics = asyncio.Queue(maxsize=64) + self.diagnostics_dropped = False + + async with super().start_server(): + self.logger.log("Starting pyright-langserver server process", logging.INFO) + initialized = False + try: + await self.server.start() + initialize_params = self._get_initialize_params(self.repository_root_path) + + self.logger.log( + "Sending initialize request from LSP client to LSP server and awaiting response", + logging.INFO, + ) + init_response = await asyncio.wait_for( + self.server.send.initialize(initialize_params), + timeout=self._initialize_timeout_seconds, + ) + capabilities = init_response.get("capabilities") if isinstance(init_response, dict) else None + if not isinstance(capabilities, dict): + raise TypeError("Invalid Pyright initialization capabilities") + # multilspy sends UTF-16 positions, the LSP default. + if capabilities.get("positionEncoding", "utf-16") != "utf-16": + raise ValueError("Unsupported Pyright position encoding") + for required in ( + "definitionProvider", + "referencesProvider", + "hoverProvider", + "completionProvider", + "documentSymbolProvider", + "workspaceSymbolProvider", + ): + capability = capabilities.get(required) + if capability is not True and not isinstance(capability, dict): + raise ValueError(f"Pyright missing required capability: {required}") + + self.server.notify.initialized({}) + self.completions_available.set() + initialized = True + try: + yield self + finally: + if initialized: + try: + await asyncio.wait_for( + self.server.shutdown(), timeout=self._shutdown_timeout_seconds + ) + except asyncio.TimeoutError: + # A slow/blocked language server must not turn an + # otherwise successful operation into a failed + # context exit; stop() still terminates it. + self.logger.log("LSP: graceful Pyright shutdown timed out", logging.WARNING) + finally: + await self.server.stop() diff --git a/src/multilspy/lsp_protocol_handler/server.py b/src/multilspy/lsp_protocol_handler/server.py index 5c54ef8..d07938c 100644 --- a/src/multilspy/lsp_protocol_handler/server.py +++ b/src/multilspy/lsp_protocol_handler/server.py @@ -117,16 +117,23 @@ def __init__(self) -> None: self.cv = asyncio.Condition() self.result: Optional[PayloadLike] = None self.error: Optional[Error] = None + self.completed = False async def on_result(self, params: PayloadLike) -> None: - self.result = params async with self.cv: - self.cv.notify() + if self.completed: + return + self.result = params + self.completed = True + self.cv.notify_all() async def on_error(self, err: Error) -> None: - self.error = err async with self.cv: - self.cv.notify() + if self.completed: + return + self.error = err + self.completed = True + self.cv.notify_all() def content_length(line: bytes) -> Optional[int]: @@ -196,6 +203,8 @@ def __init__( self.process_launch_info = process_launch_info self.process = None self._received_shutdown = False + self._stopping = False + self._write_lock: Optional[asyncio.Lock] = None self.request_id = 1 self._response_handlers: Dict[Any, Request] = {} @@ -224,17 +233,22 @@ async def start(self) -> None: start_new_session=self.start_independent_lsp_process, ) + self._stopping = False + self._received_shutdown = False + # A SyncLanguageServer can restart this handler in a new event loop. + self._write_lock = asyncio.Lock() self.loop = asyncio.get_event_loop() - self.tasks[self.task_counter] = self.loop.create_task(self.run_forever()) - self.task_counter += 1 - self.tasks[self.task_counter] = self.loop.create_task(self.run_forever_stderr()) - self.task_counter += 1 + self._track_task(self.run_forever()) + self._track_task(self.run_forever_stderr()) async def stop(self) -> None: """ Sends the terminate signal to the language server process and waits for it to exit, with a timeout, killing it if necessary """ - # First cancel all tasks + # Stop admitting new requests and release callers waiting on the + # process, even when it exits without a shutdown response. + self._stopping = True + await self._fail_pending_requests("Language server process stopped") await self._cancel_pending_tasks() process = self.process @@ -246,6 +260,32 @@ async def stop(self) -> None: # Clean up the process await self._cleanup_process(process) + async def _fail_pending_requests(self, reason: str) -> None: + """Wake and forget every request whose response will never arrive.""" + pending = list(self._response_handlers.values()) + self._response_handlers.clear() + for request in pending: + await request.on_error(Error(ErrorCodes.InternalError, reason)) + + def _track_task(self, coroutine) -> None: + """Track only running reader/notification tasks, not completed ones.""" + identifier = self.task_counter + self.task_counter += 1 + task = asyncio.get_running_loop().create_task(coroutine) + self.tasks[identifier] = task + + def remove_completed(finished): + self.tasks.pop(identifier, None) + try: + finished.result() + except asyncio.CancelledError: + pass + except Exception as exc: + # Avoid retaining failed tasks or echoing untrusted wire data. + self._log(f"LSP background task failed: {type(exc).__name__}") + + task.add_done_callback(remove_completed) + async def _cancel_pending_tasks(self): """Cancel all pending tasks and wait for them to complete or timeout.""" pending_tasks = [] @@ -375,6 +415,9 @@ async def run_forever(self) -> bool: Continuously read from the language server process stdout and handle the messages invoking the registered response and notification handlers """ + # A delayed reader from an earlier lifespan must never abort pending + # requests belonging to a new process after restart. + reader_process = self.process try: while self.process and self.process.stdout and not self.process.stdout.at_eof(): line = await self.process.stdout.readline() @@ -392,10 +435,16 @@ async def run_forever(self) -> bool: continue body = await self.process.stdout.readexactly(num_bytes) - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task(self._handle_body(body)) - self.task_counter += 1 - except (BrokenPipeError, ConnectionResetError, StopLoopException): + self._track_task(self._handle_body(body)) + except (BrokenPipeError, ConnectionResetError, StopLoopException, + asyncio.IncompleteReadError): pass + finally: + if self.process is reader_process and not self._received_shutdown: + # EOF/crash is as terminal as an explicit stop, but an old + # reader may not close a newly started session's requests. + self._stopping = True + await self._fail_pending_requests("Language server connection closed") return self._received_shutdown async def run_forever_stderr(self) -> None: @@ -450,37 +499,46 @@ def send_notification(self, method: str, params: Optional[dict] = None) -> None: self._send_payload_sync(make_notification(method, params)) def send_response(self, request_id: Any, params: PayloadLike) -> None: - """ - Send response to the given request id to the server with the given parameters - """ - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task( - self._send_payload(make_response(request_id, params)) - ) - self.task_counter += 1 + """Send a response to a server-initiated request.""" + self._track_task(self._send_payload(make_response(request_id, params))) def send_error_response(self, request_id: Any, err: Error) -> None: - """ - Send error response to the given request id to the server with the given error - """ - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task( - self._send_payload(make_error_response(request_id, err)) - ) - self.task_counter += 1 + """Send an error response to a server-initiated request.""" + self._track_task(self._send_payload(make_error_response(request_id, err))) async def send_request(self, method: str, params: Optional[dict] = None) -> None: """ Send request to the server, register the request id, and wait for the response """ + if self._stopping: + raise Error(ErrorCodes.InternalError, "Language server is stopped") request = Request() request_id = self.request_id self.request_id += 1 self._response_handlers[request_id] = request - async with request.cv: + try: + # Never hold the condition lock across stdin I/O: stop() must be + # able to wake abandoned requests even if pipe.drain() stalls. await self._send_payload(make_request(method, request_id, params)) - await request.cv.wait() - if isinstance(request.error, Error): - raise request.error - return request.result + async with request.cv: + await request.cv.wait_for(lambda: request.completed) + if isinstance(request.error, Error): + raise request.error + return request.result + except asyncio.CancelledError: + # Inform an active server that the request is no longer wanted; + # always preserve cancellation even if stdin is already closed. + if not self._stopping: + try: + self.notify.cancel_request({"id": request_id}) + except (OSError, RuntimeError, ValueError): + pass + raise + finally: + # A timed-out or cancelled request must never retain its response + # record. A late/duplicate reply will be discarded by the handler. + if self._response_handlers.get(request_id) is request: + self._response_handlers.pop(request_id, None) def _send_payload_sync(self, payload: StringDict) -> None: """ @@ -494,16 +552,21 @@ def _send_payload_sync(self, payload: StringDict) -> None: self.process.stdin.writelines(msg) async def _send_payload(self, payload: StringDict) -> None: - """ - Send the payload to the server by writing to its stdin asynchronously. - """ - if not self.process or not self.process.stdin: - return - msg = create_message(payload) - if self.logger: - self.logger("client", "server", payload) - self.process.stdin.writelines(msg) - await self.process.stdin.drain() + """Write a complete LSP frame, serializing concurrent drain calls.""" + lock = self._write_lock + if lock is None: + raise Error(ErrorCodes.InternalError, "Language server is not running") + async with lock: + if self._stopping: + raise Error(ErrorCodes.InternalError, "Language server is stopped") + process = self.process + if not process or not process.stdin: + raise Error(ErrorCodes.InternalError, "Language server is not running") + msg = create_message(payload) + if self.logger: + self.logger("client", "server", payload) + process.stdin.writelines(msg) + await process.stdin.drain() def on_request(self, method: str, cb) -> None: """ @@ -521,13 +584,36 @@ async def _response_handler(self, response: StringDict) -> None: """ Handle the response received from the server for a request, using the id to determine the request """ - request = self._response_handlers.pop(response["id"]) + request_id = response.get("id") + if type(request_id) not in (int, str): + self._log("Ignoring LSP response with unroutable id") + return + request = self._response_handlers.get(request_id) + if request is None or self._stopping: + # Timeout/cancellation and duplicate replies are legal races. + # Never fail another reader task for a completed request id. + self._log("Ignoring late or duplicate LSP response") + return if "result" in response and "error" not in response: await request.on_result(response["result"]) elif "result" not in response and "error" in response: - await request.on_error(Error.from_lsp(response["error"])) + try: + raw_error = response["error"] + if ( + not isinstance(raw_error, dict) + or not isinstance(raw_error.get("code"), int) + or isinstance(raw_error.get("code"), bool) + or not isinstance(raw_error.get("message"), str) + ): + raise ValueError("Invalid JSON-RPC error shape") + error = Error.from_lsp(raw_error) + except (KeyError, TypeError, ValueError): + # A malformed response still completes its waiting request; + # otherwise a corrupt peer could strand the caller forever. + error = Error(ErrorCodes.InvalidRequest, "Malformed LSP error response") + await request.on_error(error) else: - await request.on_error(Error(ErrorCodes.InvalidRequest, "")) + await request.on_error(Error(ErrorCodes.InvalidRequest, "Malformed LSP response")) async def _request_handler(self, response: StringDict) -> None: """ diff --git a/src/multilspy/multilspy_config.py b/src/multilspy/multilspy_config.py index b12a8ca..73983ba 100644 --- a/src/multilspy/multilspy_config.py +++ b/src/multilspy/multilspy_config.py @@ -4,7 +4,7 @@ from enum import Enum from dataclasses import dataclass -from typing import Optional +from typing import Literal, Optional class Language(str, Enum): """ @@ -46,6 +46,10 @@ class MultilspyConfig: # Ignored when server_binary is set. server_install_dir: Optional[str] = None + # Append new options after existing fields to preserve positional callers. + # Jedi remains the default; Pyright requires an explicit choice. + python_server: Literal["jedi", "pyright"] = "jedi" + @classmethod def from_dict(cls, env: dict): """ diff --git a/src/multilspy/multilspy_utils.py b/src/multilspy/multilspy_utils.py index e13ea92..781ddd8 100644 --- a/src/multilspy/multilspy_utils.py +++ b/src/multilspy/multilspy_utils.py @@ -22,50 +22,58 @@ class TextUtils: """ Utilities for text operations. """ + @staticmethod + def _utf16_length(text: str) -> int: + """LSP positions count UTF-16 code units, not Python code points.""" + return sum(2 if ord(character) > 0xFFFF else 1 for character in text) + @staticmethod def get_line_col_from_index(text: str, index: int) -> Tuple[int, int]: - """ - Returns the zero-indexed line and column number of the given index in the given text - """ - l = 0 - c = 0 - idx = 0 - while idx < index: - if text[idx] == '\n': - l += 1 - c = 0 + """Return a zero-based line and UTF-16 column for a Python text index.""" + line = 0 + column = 0 + for character in text[:index]: + if character == "\n": + line += 1 + column = 0 else: - c += 1 - idx += 1 + column += 2 if ord(character) > 0xFFFF else 1 + return line, column - return l, c - @staticmethod def get_index_from_line_col(text: str, line: int, col: int) -> int: - """ - Returns the index of the given zero-indexed line and column number in the given text - """ + """Translate a zero-based LSP UTF-16 position into a Python text index.""" + if line < 0 or col < 0: + raise ValueError("LSP line and column must be non-negative") idx = 0 while line > 0: - assert idx < len(text), (idx, len(text), text) + if idx >= len(text): + raise ValueError("LSP line is outside the document") if text[idx] == "\n": line -= 1 idx += 1 - idx += col + while col > 0: + if idx >= len(text) or text[idx] == "\n": + raise ValueError("LSP column is outside the line") + units = 2 if ord(text[idx]) > 0xFFFF else 1 + if col < units: + raise ValueError("LSP column splits a UTF-16 surrogate pair") + idx += 1 + col -= units return idx - + @staticmethod - def get_updated_position_from_line_and_column_and_edit(l: int, c: int, text_to_be_inserted: str) -> Tuple[int, int]: - """ - Utility function to get the position of the cursor after inserting text at a given line and column. - """ - num_newlines_in_gen_text = text_to_be_inserted.count('\n') + def get_updated_position_from_line_and_column_and_edit(l: int, c: int, text_to_be_inserted: str) -> Tuple[int, int]: # noqa: E741 + """Return the LSP UTF-16 cursor position after inserting text.""" + # Preserve existing named arguments `l` and `c` for API compatibility. + line, column = l, c + num_newlines_in_gen_text = text_to_be_inserted.count("\n") if num_newlines_in_gen_text > 0: - l += num_newlines_in_gen_text - c = len(text_to_be_inserted.split('\n')[-1]) + line += num_newlines_in_gen_text + column = TextUtils._utf16_length(text_to_be_inserted.split("\n")[-1]) else: - c += len(text_to_be_inserted) - return (l, c) + column += TextUtils._utf16_length(text_to_be_inserted) + return line, column class PathUtils: """ @@ -95,7 +103,12 @@ def get_relative_path(path: str, base_path: str) -> Union[str, None]: Gets relative path if it's possible (paths should be on the same drive), returns `None` otherwise. """ - if PurePath(path).drive == PurePath(base_path).drive: + # Windows drive letters are case-insensitive. Python 3.14's + # urllib.request.url2pathname preserves the URL's drive casing, + # unlike older Python releases which uppercased it. Compare drives + # using the native filesystem rules so Pyright's file:///c%3A/... URI + # resolves relative to a workspace rooted at C:\... . + if os.path.normcase(PurePath(path).drive) == os.path.normcase(PurePath(base_path).drive): return str(PurePath(os.path.relpath(path, base_path))) return None diff --git a/tests/multilspy/test_completion_responses.py b/tests/multilspy/test_completion_responses.py index 8f770d5..4d86e57 100644 --- a/tests/multilspy/test_completion_responses.py +++ b/tests/multilspy/test_completion_responses.py @@ -31,6 +31,9 @@ def server(tmp_path): ([[]], []), ([[ITEM]], EXPECTED), ([{"isIncomplete": False, "items": [ITEM]}], EXPECTED), + # A valid CompletionItem may be label-only, with no edit or kind. + ([[{"label": "example", "kind": 6}]], EXPECTED), + ([[{"label": "example"}]], [{"completionText": "example", "kind": 1}]), ([{"isIncomplete": True, "items": []}, None], []), ([{"isIncomplete": True, "items": []}, {"isIncomplete": False, "items": [ITEM]}], EXPECTED), ]) @@ -52,3 +55,39 @@ async def test_incomplete_completion_retries_are_bounded(server, allow_incomplet assert result == (EXPECTED if allow_incomplete else []) assert server.server.send.completion.await_count == 30 assert not server.open_file_buffers + +@pytest.mark.asyncio +async def test_retry_incomplete_completions_uses_protocol_trigger(server): + seen = [] + responses = [ + {"isIncomplete": True, "items": []}, + {"isIncomplete": True, "items": []}, + {"isIncomplete": False, "items": [ITEM]}, + ] + + async def completion(params): + seen.append(params["context"]["triggerKind"]) + return responses[len(seen) - 1] + + server.server.send.completion = AsyncMock(side_effect=completion) + result = await server.request_completions("example.py", 0, 0) + assert result == EXPECTED + assert seen == [1, 3, 3] + assert not server.open_file_buffers + + +@pytest.mark.asyncio +async def test_completion_deduplication_preserves_server_ranking(server): + # Duplicates must not scramble server ordering (e.g. with randomized hash + # seeds); rank order is meaningful for editors and coding agents. + candidates = [ + {"label": "zeta", "kind": 6}, + {"label": "alpha", "kind": 6}, + {"label": "zeta", "kind": 6}, + {"label": "beta", "kind": 6}, + ] + server.server.send.completion = AsyncMock(return_value=candidates) + suggestions = await server.request_completions("example.py", 0, 0) + assert [item["completionText"] for item in suggestions] == ["zeta", "alpha", "beta"] + assert server.server.send.completion.await_count == 1 + assert not server.open_file_buffers diff --git a/tests/multilspy/test_lsp_request_lifecycle.py b/tests/multilspy/test_lsp_request_lifecycle.py new file mode 100644 index 0000000..25218ef --- /dev/null +++ b/tests/multilspy/test_lsp_request_lifecycle.py @@ -0,0 +1,354 @@ +"""JSON-RPC pending request lifecycle across all language server adapters. + +This is shared multilspy behavior, not Pyright-specific. No external LSP +binary or network required for the unit cases; real subprocess EOF is tested. +""" + +import asyncio +import sys +from unittest.mock import AsyncMock, Mock + +import pytest + +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes +from multilspy.lsp_protocol_handler.server import Error, LanguageServerHandler, ProcessLaunchInfo + + +@pytest.fixture +def handler(tmp_path): + client = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path))) + client._send_payload = AsyncMock() + client._send_payload_sync = Mock() + return client + + +async def wait_for_pending(handler, n): + async def wait_for_count(): + while len(handler._response_handlers) != n: + await asyncio.sleep(0) + return list(handler._response_handlers) + + return await asyncio.wait_for(wait_for_count(), 2) + + +@pytest.mark.asyncio +async def test_response_race_before_wait_starts(handler): + async def fast_peer(payload): + # A response may be scheduled while request bytes are still draining. + asyncio.create_task(handler._response_handler({"id": payload["id"], "result": "ready"})) + await asyncio.sleep(0) + + handler._send_payload.side_effect = fast_peer + assert await asyncio.wait_for(handler.send_request("example", {"x": 1}), 2) == "ready" + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_null_result_unblocks_waiter(handler): + task = asyncio.create_task(handler.send_request("textDocument/references", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "result": None}) + assert await asyncio.wait_for(task, 2) is None + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_lsp_error_unblocks_waiter_and_cleans_map(handler): + task = asyncio.create_task(handler.send_request("bad", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "error": { + "code": ErrorCodes.MethodNotFound, "message": "not here" + }}) + with pytest.raises(Error) as exc: + await asyncio.wait_for(task, 2) + assert exc.value.code == ErrorCodes.MethodNotFound + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_transport_send_exception_cleans_map(handler): + handler._send_payload.side_effect = OSError("pipe unavailable") + with pytest.raises(OSError, match="pipe unavailable"): + await handler.send_request("x", {}) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_cancellation_cleans_map_and_sends_cancel_request(handler): + task = asyncio.create_task(handler.send_request("long", {})) + (identifier,) = await wait_for_pending(handler, 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert handler._response_handlers == {} + handler._send_payload_sync.assert_called_once() + payload = handler._send_payload_sync.call_args.args[0] + assert payload == { + "jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": identifier} + } + await handler._response_handler({"id": identifier, "result": "late"}) + await handler._response_handler({"id": identifier, "result": "duplicate"}) + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_concurrent_requests_resolve_out_of_order_without_leak(handler): + tasks = [asyncio.create_task(handler.send_request("request", {"ordinal": i})) for i in range(20)] + identifiers = await wait_for_pending(handler, 20) + assert len(set(identifiers)) == len(tasks) + for identifier in reversed(identifiers): + await handler._response_handler({"id": identifier, "result": identifier}) + assert await asyncio.wait_for(asyncio.gather(*tasks), 3) == identifiers + for identifier in identifiers: + await handler._response_handler({"id": identifier, "result": "duplicate"}) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_stop_wakes_all_waiters_and_rejects_new_requests(handler): + tasks = [asyncio.create_task(handler.send_request("stalled", {})) for _ in range(10)] + old_ids = await wait_for_pending(handler, len(tasks)) + await asyncio.wait_for(handler.stop(), 3) + results = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 3) + assert len(results) == len(tasks) + assert all(isinstance(item, Error) and "stopped" in str(item) for item in results) + assert not handler._response_handlers + for identifier in old_ids: + await handler._response_handler({"id": identifier, "result": "late"}) + with pytest.raises(Error, match="stopped"): + await asyncio.wait_for(handler.send_request("new", {}), 1) + + +@pytest.mark.asyncio +async def test_stop_does_not_wait_for_stalled_stdin_drain(handler): + sending = asyncio.Event() + still_draining = asyncio.Event() + + async def blocked_send(_payload): + sending.set() + await still_draining.wait() + + handler._send_payload.side_effect = blocked_send + task = asyncio.create_task(handler.send_request("blocked", {})) + await asyncio.wait_for(sending.wait(), 2) + assert len(handler._response_handlers) == 1 + await asyncio.wait_for(handler.stop(), 1) + assert not handler._response_handlers + still_draining.set() + with pytest.raises(Error, match="stopped"): + await asyncio.wait_for(task, 2) + + +@pytest.mark.asyncio +async def test_restarted_session_never_reuses_old_request_id(handler): + task = asyncio.create_task(handler.send_request("old", {})) + (old_id,) = await wait_for_pending(handler, 1) + await handler.stop() + with pytest.raises(Error): + await task + # start() resets stopped state when a new child is successfully spawned; + # simulate only that lifecycle transition without launching a provider. + handler._stopping = False + next_request = asyncio.create_task(handler.send_request("new", {})) + (next_id,) = await wait_for_pending(handler, 1) + assert old_id != next_id + await handler._response_handler({"id": old_id, "result": "obsolete"}) + assert not next_request.done() + await handler._response_handler({"id": next_id, "result": "fresh"}) + assert await asyncio.wait_for(next_request, 2) == "fresh" + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_server_crash_and_eof_wake_outstanding_request(tmp_path): + script = tmp_path / "exit_on_input.py" + script.write_text("import sys\nsys.stdin.buffer.read(1)\n", encoding="utf-8") + handler = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable, "-u", str(script)], cwd=str(tmp_path))) + await handler.start() + try: + with pytest.raises(Error, match="connection closed"): + await asyncio.wait_for(handler.send_request("never-answered", {}), 5) + assert not handler._response_handlers + with pytest.raises(Error, match="stopped"): + await handler.send_request("after-eof", {}) + finally: + await handler.stop() + assert handler.process is None + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_duplicate_response_before_waiter_finishes_is_ignored(handler): + task = asyncio.create_task(handler.send_request("repeat", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "result": "first"}) + await handler._response_handler({"id": identifier, "result": "second"}) + assert await asyncio.wait_for(task, 2) == "first" + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_repeated_cancels_never_accumulate_pending_requests(handler): + for _ in range(100): + task = asyncio.create_task(handler.send_request("repeated", {})) + (identifier,) = await wait_for_pending(handler, 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await handler._response_handler({"id": identifier, "result": "obsolete"}) + assert not handler._response_handlers + assert handler.request_id == 101 + assert handler._send_payload_sync.call_count == 100 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response", [ + {"error": None}, + {"error": {}}, + {"error": {"code": "wrong"}}, + {"error": {"code": "wrong", "message": "not an integer"}}, + {"error": {"code": True, "message": "boolean is not an error code"}}, + {"error": {"code": -32601, "message": 99}}, + {"result": 1, "error": {"code": -32000, "message": "bad"}}, +]) +async def test_malformed_reply_unblocks_and_fails_request(handler, response): + task = asyncio.create_task(handler.send_request("malformed", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, **response}) + with pytest.raises(Error) as exc: + await asyncio.wait_for(task, 2) + assert exc.value.code == ErrorCodes.InvalidRequest + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_partial_response_frame_then_eof_wakes_request(tmp_path): + script = tmp_path / "truncated_frame.py" + script.write_text( + "import sys\n" + "sys.stdin.buffer.read(1)\n" + "sys.stdout.buffer.write(b'Content-Length: 20\\r\\n\\r\\nshort')\n" + "sys.stdout.buffer.flush()\n", + encoding="utf-8", + ) + handler = LanguageServerHandler( + ProcessLaunchInfo(cmd=[sys.executable, "-u", str(script)], cwd=str(tmp_path)) + ) + await handler.start() + try: + with pytest.raises(Error, match="connection closed"): + await asyncio.wait_for(handler.send_request("partial", {}), 5) + assert handler._response_handlers == {} + finally: + await handler.stop() + assert handler.process is None + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_concurrent_stdin_drain_is_serialized_even_on_stop(handler): + """Python 3.10/3.11 StreamWriter supports only one pending drain waiter.""" + from types import SimpleNamespace + + first_drain = asyncio.Event() + release = asyncio.Event() + + class Writer: + drain_calls = 0 + + def writelines(self, _segments): + pass + + async def drain(self): + self.drain_calls += 1 + if self.drain_calls == 1: + first_drain.set() + await release.wait() + + writer = Writer() + handler.process = SimpleNamespace(stdin=writer) + handler._write_lock = asyncio.Lock() + handler._cleanup_process = AsyncMock() + # Restore the real method; the basic fixture uses a mocked sender. + handler._send_payload = LanguageServerHandler._send_payload.__get__(handler) + tasks = [asyncio.create_task(handler.send_request("stress", {})) for _ in range(2)] + await asyncio.wait_for(first_drain.wait(), 2) + await asyncio.sleep(0) + assert writer.drain_calls == 1 + await asyncio.wait_for(handler.stop(), 2) + release.set() + outcomes = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 2) + assert all(isinstance(item, Error) for item in outcomes) + assert not handler._response_handlers + assert writer.drain_calls == 1 # queued write is never sent after stop + + +@pytest.mark.asyncio +async def test_old_reader_cannot_fail_requests_in_new_process(handler): + from types import SimpleNamespace + from multilspy.lsp_protocol_handler.server import Request + + entered = asyncio.Event() + hold = asyncio.Event() + + class Reader: + def at_eof(self): + return False + + async def readline(self): + entered.set() + await hold.wait() + return b"" + + old_process = SimpleNamespace(stdout=Reader()) + handler.process = old_process + old_reader = asyncio.create_task(handler.run_forever()) + await asyncio.wait_for(entered.wait(), 2) + handler.process = SimpleNamespace(stdout=None) + pending = Request() + handler._response_handlers[42] = pending + old_reader.cancel() + with pytest.raises(asyncio.CancelledError): + await old_reader + assert not handler._stopping + assert handler._response_handlers[42] is pending + await pending.on_error(Error(ErrorCodes.InternalError, "test done")) + handler._response_handlers.clear() + + +@pytest.mark.asyncio +async def test_background_task_tracking_reaps_completed_tasks(handler): + for _ in range(300): + handler._track_task(asyncio.sleep(0)) + # The loop schedules task completion callbacks one turn after the tasks + # themselves finish; wait for the bound rather than assuming tick count. + async def drained(): + while handler.tasks: + await asyncio.sleep(0) + + await asyncio.wait_for(drained(), 2) + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_request_before_server_start_fails_instead_of_hanging(tmp_path): + handler = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path))) + with pytest.raises(Error, match="not running"): + await asyncio.wait_for(handler.send_request("premature", {}), 1) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_unroutable_and_duplicate_responses_leave_a_generic_log(tmp_path): + callback = Mock() + handler = LanguageServerHandler( + ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path)), logger=callback + ) + await handler._response_handler({"id": None, "error": {"code": -32700, "message": "bad"}}) + await handler._response_handler({"id": 70000, "result": "late"}) + assert not handler._response_handlers + assert callback.call_count == 2 + logs = [call.args[2] for call in callback.call_args_list] + assert "unroutable" in logs[0] + assert "duplicate" in logs[1] + assert "70000" not in logs[1] # no echo of untrusted response content diff --git a/tests/multilspy/test_lsp_result_shapes.py b/tests/multilspy/test_lsp_result_shapes.py new file mode 100644 index 0000000..253ebcd --- /dev/null +++ b/tests/multilspy/test_lsp_result_shapes.py @@ -0,0 +1,113 @@ +"""Normalize valid LSP return shapes across Python language server adapters. + +Like test_completion_responses.py, inject a mocked LSP response and verify the +language-agnostic API without launching or downloading a language server. +""" + +from contextlib import contextmanager +from types import SimpleNamespace + +import pytest + +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture(params=("jedi", "pyright")) +def server(tmp_path, request): + (tmp_path / "example.py").write_text("def greet(): return 'hi'\n") + instance = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server=request.param, + ), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + + @contextmanager + def open_file(_relative_path): + yield + + instance.open_file = open_file + instance.server_started = True + return instance, tmp_path.resolve() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "response_kind", + ("location", "link_without_origin", "link_with_origin", "null", "empty"), +) +async def test_definition_accepts_lsp_3_17_result_variants(server, response_kind): + instance, root = server + uri = (root / "example.py").as_uri() + selection = { + "start": {"line": 0, "character": 4}, + "end": {"line": 0, "character": 9}, + } + variants = { + "location": {"uri": uri, "range": selection}, + "link_without_origin": { + "targetUri": uri, + "targetRange": selection, + "targetSelectionRange": selection, + }, + "link_with_origin": { + "originSelectionRange": selection, + "targetUri": uri, + "targetRange": selection, + "targetSelectionRange": selection, + }, + } + response = ( + None + if response_kind == "null" + else [] + if response_kind == "empty" + else [variants[response_kind]] + ) + + async def definition(_params): + return response + + instance.server.send = SimpleNamespace(definition=definition) + normalized = await instance.request_definition("example.py", 0, 5) + if response_kind in ("null", "empty"): + assert normalized == [] + else: + assert len(normalized) == 1 + assert normalized[0]["relativePath"] == "example.py" + assert normalized[0]["range"] == selection + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response", (None, [])) +async def test_references_support_null_or_empty_list(server, response): + instance, _ = server + + async def references(_params): + return response + + instance.server.send = SimpleNamespace(references=references) + assert await instance.request_references("example.py", 0, 5) == [] + + +@pytest.mark.asyncio +async def test_references_preserve_valid_locations(server): + instance, root = server + target = root / "example.py" + span = { + "start": {"line": 0, "character": 4}, + "end": {"line": 0, "character": 9}, + } + + async def references(_params): + return [{"uri": target.as_uri(), "range": span}] + + instance.server.send = SimpleNamespace(references=references) + normalized = await instance.request_references("example.py", 0, 5) + assert len(normalized) == 1 + assert normalized[0]["relativePath"] == "example.py" + assert normalized[0]["range"] == span diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py new file mode 100644 index 0000000..98f6727 --- /dev/null +++ b/tests/multilspy/test_multilspy_pyright.py @@ -0,0 +1,1264 @@ +"""Pyright language-server integration, following the other adapter tests. + +Use a disposable local workspace instead of cloning a remote repository. +The integration tests require an explicit, preinstalled Pyright executable; +they skip rather than download/install when it is unavailable. + +Every expected payload below is the exact response of pyright-langserver +1.1.413 for the temporary project. Rename, code actions and commands are +proposals only: the workspace files are compared byte for byte afterwards. +""" + +import asyncio +import json +import os +import re +import subprocess +import sys +import venv +from pathlib import Path + +import pytest + +from multilspy import LanguageServer, SyncLanguageServer +from multilspy.language_servers.jedi_language_server.jedi_server import JediServer +from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, +) +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes +from multilspy.lsp_protocol_handler.server import Error +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_exceptions import MultilspyException +from multilspy.multilspy_logger import MultilspyLogger +from multilspy.multilspy_utils import PathUtils, TextUtils + +# The adapter, the capability matrix and every exact payload in this module +# were captured against this Pyright release. +TESTED_PYRIGHT_VERSION = (1, 1, 413) + +# Server capabilities that pyright-langserver 1.1.413 advertises to multilspy's +# read-only client. Everything else (implementationProvider, diagnosticProvider +# for pull diagnostics, semantic tokens, inlay hints, folding, formatting, ...) +# is not advertised and such requests fail with MethodNotFound. +ADVERTISED_CAPABILITIES = { + "callHierarchyProvider", + "codeActionProvider", + "completionProvider", + "declarationProvider", + "definitionProvider", + "documentHighlightProvider", + "documentSymbolProvider", + "executeCommandProvider", + "hoverProvider", + "referencesProvider", + "renameProvider", + "signatureHelpProvider", + "textDocumentSync", + "typeDefinitionProvider", + "workspace", + "workspaceSymbolProvider", +} + +SHAPES_SOURCE = ( + "from dataclasses import dataclass\n" + "\n" + "\n" + "@dataclass\n" + "class Point:\n" + " x: float\n" + " y: float\n" + "\n" + "\n" + "class Shape:\n" + " def area(self) -> float:\n" + " raise NotImplementedError\n" + "\n" + " def describe(self) -> str:\n" + " return f\"{type(self).__name__}: {self.area():.1f}\"\n" + "\n" + "\n" + "class Square(Shape):\n" + " def __init__(self, side: float) -> None:\n" + " self.side = side\n" + "\n" + " def area(self) -> float:\n" + " return self.side * self.side\n" + "\n" + "\n" + "def total_area(shapes: list[Shape]) -> float:\n" + " return sum(shape.area() for shape in shapes)\n" +) + +REPORT_SOURCE = ( + "import sys\n" + "import os\n" + "from shapes import Point, Square, total_area\n" + "\n" + "origin = Point(0.0, 0.0)\n" + "squares = [Square(2.0), Square(side=3.0)]\n" + "summary = total_area(squares)\n" + "label = squares[0].describe()\n" +) + + +def _range(start_line, start_character, end_line, end_character): + return { + "start": {"line": start_line, "character": start_character}, + "end": {"line": end_line, "character": end_character}, + } + + +def _same_file_uri(left, right): + """Compare file locations, not the OS-specific spelling of LSP URIs. + + Windows pathlib emits file:///C:/path, while Pyright's vscode-uri emits + file:///c%3A/path; both represent the same file on the same filesystem. + """ + return os.path.normcase(PathUtils.uri_to_path(left)) == os.path.normcase( + PathUtils.uri_to_path(right) + ) + + +def _portable_lsp_payload(value): + """Normalize only file-URI fields/keys in exact wire response assertions.""" + if isinstance(value, list): + return [_portable_lsp_payload(item) for item in value] + if isinstance(value, dict): + output = {} + for key, item in value.items(): + normalized_key = ( + os.path.normcase(PathUtils.uri_to_path(key)) + if isinstance(key, str) and key.startswith("file:") else key + ) + if key in ("uri", "targetUri") and isinstance(item, str) and item.startswith("file:"): + output[normalized_key] = os.path.normcase(PathUtils.uri_to_path(item)) + else: + output[normalized_key] = _portable_lsp_payload(item) + return output + return value + + +def _pyright_version(language_server_binary): + """Return the Pyright version tuple for a pyright-langserver executable. + + pyright-langserver has no --version flag. The npm and PyPI packages install + a sibling `pyright` CLI that reports the shared version; the npm package + also carries the version in its package.json next to the resolved script. + """ + binary = Path(language_server_binary) + # npm puts .cmd entry points in node_modules/.bin on Windows; they are + # not directly executable with subprocess(shell=False). Read the pinned + # package metadata instead (and avoid invoking wrapper bootstrap logic). + candidates = ( + binary.resolve().parent / "package.json", + binary.parent.parent / "pyright" / "package.json", + ) + for package_json in candidates: + if package_json.is_file(): + version = json.loads(package_json.read_text(encoding="utf-8")).get("version", "") + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version) + if match: + return tuple(int(part) for part in match.groups()) + + for name in ("pyright", "pyright.cmd", "pyright.exe"): + sibling = binary.with_name(name) + if sibling.is_file(): + command = [str(sibling), "--version"] + if os.name == "nt" and sibling.suffix.lower() == ".cmd": + command = ["cmd.exe", "/d", "/c", str(sibling), "--version"] + completed = subprocess.run( + command, capture_output=True, text=True, timeout=60, check=False + ) + match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) + if completed.returncode == 0 and match: + return tuple(int(part) for part in match.groups()) + return None + + +@pytest.fixture +def python_project(tmp_path): + root = tmp_path.resolve() + files = { + "lib.py": ("def greet(name: str) -> str:\n return name.upper()\n"), + "app.py": ( + "from lib import greet\n\nfirst = greet('Ada')\nsecond = greet('Bob')\n" + ), + "worker.py": ( + "class Worker:\n" + " def process(self) -> int:\n" + " return 3\n\n" + "worker = Worker()\n" + "result = worker.process()\n" + ), + "invalid.py": ("def faulty(name: str) -> str:\n return 123\n"), + # The emoji is one code point but two UTF-16 code units; the second + # `x` is at UTF-16 column 14 (code-point column 13). + "emoji.py": ("x = '\U0001F600'; y = x\n"), + "shapes.py": SHAPES_SOURCE, + "report.py": REPORT_SOURCE, + } + for name, contents in files.items(): + (root / name).write_text(contents, encoding="utf-8") + (root / "pyrightconfig.json").write_text( + '{"typeCheckingMode":"standard","include":["."]}\n' + ) + return root + + +@pytest.fixture +def pyright_binary(): + provided = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") + if not provided: + pytest.skip("Set MULTILSPY_PYRIGHT_TEST_BINARY to a preinstalled executable") + binary = Path(provided) + if not binary.is_absolute() or not binary.is_file(): + pytest.fail("MULTILSPY_PYRIGHT_TEST_BINARY must be an existing absolute file") + if os.name != "nt" and not os.access(binary, os.X_OK): + pytest.fail("MULTILSPY_PYRIGHT_TEST_BINARY must be executable") + return str(binary) + + +@pytest.fixture +def create_pyright(python_project, pyright_binary): + def create(): + return LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(python_project), + ) + + return create + + +@pytest.mark.parametrize( + "backend, expected", + [ + ("jedi", JediServer), + ("pyright", PyrightServer), + ], +) +def test_python_backend_selection_is_explicit(tmp_path, backend, expected): + instance = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server=backend, + ), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + assert isinstance(instance, expected) + assert instance.server.process is None + + +def test_existing_jedi_default_and_explicit_server_command(tmp_path): + root = str(tmp_path.resolve()) + default = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON), + MultilspyLogger(), + root, + ) + assert isinstance(default, JediServer) + pyright = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary="/preinstalled/pyright-langserver", + ), + MultilspyLogger(), + root, + ) + assert pyright.server.process_launch_info.cmd == [ + "/preinstalled/pyright-langserver", + "--stdio", + ] + assert pyright.server.process_launch_info.cwd == root + assert pyright.server.process is None + + +def test_existing_positional_config_arguments_are_unchanged(): + config = MultilspyConfig(Language.PYTHON, True, False, None, None) + assert config.trace_lsp_communication is True + assert config.start_independent_lsp_process is False + assert config.server_binary is None + assert config.server_install_dir is None + assert config.python_server == "jedi" + + +def test_pyright_selection_through_from_dict_and_sync_factory(tmp_path): + config = MultilspyConfig.from_dict( + { + "code_language": Language.PYTHON, + "python_server": "pyright", + "server_binary": "/preinstalled/pyright-langserver", + } + ) + sync = SyncLanguageServer.create( + config, MultilspyLogger(), str(tmp_path.resolve()), timeout=15 + ) + assert isinstance(sync.language_server, PyrightServer) + assert sync.language_server.server.process is None + + +def test_invalid_python_backend_cannot_fall_back_to_jedi(tmp_path): + config = MultilspyConfig( + code_language=Language.PYTHON, + python_server="unknown", + ) + with pytest.raises(MultilspyException, match="Unsupported Python"): + LanguageServer.create(config, MultilspyLogger(), str(tmp_path.resolve())) + + +def test_real_pyright_binary_is_the_tested_version(pyright_binary): + version = _pyright_version(pyright_binary) + assert version is not None, "Cannot determine the Pyright version next to the language server" + # The exact payloads in this module belong to one release. To validate a + # newer Pyright, re-capture the expectations and bump TESTED_PYRIGHT_VERSION. + assert version == TESTED_PYRIGHT_VERSION + + +@pytest.mark.asyncio +async def test_real_pyright_advertised_capabilities_match_matrix(create_pyright): + server = create_pyright() + native_initialize = server.server.send.initialize + captured = {} + + async def initialize(params): + captured["result"] = await native_initialize(params) + return captured["result"] + + server.server.send.initialize = initialize + + async def exercise(): + async with server.start_server(): + pass + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + capabilities = captured["result"]["capabilities"] + assert set(capabilities) == ADVERTISED_CAPABILITIES + assert capabilities["textDocumentSync"] == 2 + assert capabilities["completionProvider"] == { + "triggerCharacters": [".", "[", '"', "'"], + "resolveProvider": True, + "completionItem": {"labelDetailsSupport": True}, + "workDoneProgress": True, + } + assert capabilities["signatureHelpProvider"]["triggerCharacters"] == ["(", ",", ")"] + assert capabilities["renameProvider"]["prepareProvider"] is True + assert capabilities["codeActionProvider"]["codeActionKinds"] == [ + "quickfix", + "source.organizeImports", + ] + # Pyright registers no server commands for this client; its commands still + # execute by name (see test_real_pyright_commands_cannot_edit_the_workspace). + assert capabilities["executeCommandProvider"]["commands"] == [] + assert capabilities["callHierarchyProvider"] is True + assert capabilities["workspace"] == { + "workspaceFolders": {"supported": True, "changeNotifications": True} + } + + +@pytest.mark.asyncio +async def test_real_pyright_definition_references_hover_and_symbols( + python_project, + create_pyright, +): + server = create_pyright() + + async def exercise(): + async with server.start_server(): + definition = await asyncio.wait_for( + server.request_definition("app.py", 2, 9), timeout=8 + ) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "lib.py" + assert definition[0]["range"] == _range(0, 4, 0, 9) + + # Keep the import and definition open to avoid relying on when + # background workspace indexing completes on a cold runner. + with server.open_file("app.py"), server.open_file("lib.py"): + references = await asyncio.wait_for( + server.request_references("lib.py", 0, 5), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("app.py", _range(0, 16, 0, 21)), + ("app.py", _range(2, 8, 2, 13)), + ("app.py", _range(3, 9, 3, 14)), + ] + + hover = await asyncio.wait_for( + server.request_hover("app.py", 2, 10), timeout=8 + ) + assert hover == { + "contents": { + "kind": "markdown", + "value": "```python\n(function) def greet(name: str) -> str\n```", + }, + "range": _range(2, 8, 2, 13), + } + + symbols, tree = await asyncio.wait_for( + server.request_document_symbols("lib.py"), timeout=8 + ) + assert tree is None + assert [(entry["name"], entry["kind"]) for entry in symbols] == [ + ("greet", 12), + ("name", 13), + ] + + workspace_symbols = [] + for _ in range(15): + workspace_symbols = await asyncio.wait_for( + server.request_workspace_symbol("greet"), timeout=8 + ) + if workspace_symbols: + break + await asyncio.sleep(0.1) + assert _portable_lsp_payload(workspace_symbols) == _portable_lsp_payload([ + { + "name": "greet", + "kind": 12, + "location": { + "uri": (python_project / "lib.py").as_uri(), + "range": _range(0, 4, 0, 9), + }, + } + ]) + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_high_level_api_on_classes_across_files( + python_project, + create_pyright, +): + """Inheritance, overrides, keyword arguments and cross-file references.""" + server = create_pyright() + + async def exercise(): + async with server.start_server(): + # shape.area() inside total_area resolves to the base method. + definition = await asyncio.wait_for( + server.request_definition("shapes.py", 26, 22), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("shapes.py", _range(10, 8, 10, 12)) + ] + + # Square used through a keyword-argument constructor call. + definition = await asyncio.wait_for( + server.request_definition("report.py", 5, 26), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("shapes.py", _range(17, 6, 17, 12)) + ] + + # References exclude the declaration (multilspy sends includeDeclaration=false). + with server.open_file("shapes.py"), server.open_file("report.py"): + references = await asyncio.wait_for( + server.request_references("shapes.py", 17, 6), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("report.py", _range(2, 26, 2, 32)), + ("report.py", _range(5, 11, 5, 17)), + ("report.py", _range(5, 24, 5, 30)), + ] + # References to the base method do not include the override. + references = await asyncio.wait_for( + server.request_references("shapes.py", 10, 8), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("shapes.py", _range(14, 46, 14, 50)), + ("shapes.py", _range(26, 21, 26, 25)), + ] + + hover = await asyncio.wait_for( + server.request_hover("report.py", 6, 10), timeout=8 + ) + assert hover == { + "contents": { + "kind": "markdown", + "value": "```python\n(function) def total_area(shapes: list[Shape]) -> float\n```", + }, + "range": _range(6, 10, 6, 20), + } + hover = await asyncio.wait_for( + server.request_hover("report.py", 5, 12), timeout=8 + ) + assert hover["contents"]["value"] == "```python\nclass Square(side: float)\n```" + + symbols, _ = await asyncio.wait_for( + server.request_document_symbols("shapes.py"), timeout=8 + ) + assert [(entry["name"], entry["kind"]) for entry in symbols] == [ + ("Point", 5), + ("x", 13), + ("y", 13), + ("Shape", 5), + ("area", 6), + ("describe", 6), + ("Square", 5), + ("__init__", 6), + ("side", 13), + ("area", 6), + ("side", 13), + ("total_area", 12), + ("shapes", 13), + ] + + workspace_symbols = await asyncio.wait_for( + server.request_workspace_symbol("Square"), timeout=8 + ) + assert _portable_lsp_payload({ + "name": "Square", + "kind": 5, + "location": { + "uri": (python_project / "shapes.py").as_uri(), + "range": _range(17, 6, 17, 12), + }, + }) in _portable_lsp_payload(workspace_symbols) + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_high_level_completions_and_signature( + python_project, + create_pyright, +): + server = create_pyright() + + async def exercise(): + async with server.start_server(): + # Use the same high-level API as the existing Jedi/Rust tests. + suggestions = await asyncio.wait_for( + server.request_completions("worker.py", 5, len("result = worker.")), + timeout=8, + ) + assert "process" in {item["completionText"] for item in suggestions} + + # Pyright answers member completions with isIncomplete=true first; + # the high-level API retries with TriggerForIncompleteCompletions. + suggestions = await asyncio.wait_for( + server.request_completions("report.py", 7, len("label = squares[0].")), + timeout=8, + ) + by_name = {item["completionText"]: item["kind"] for item in suggestions} + assert by_name["describe"] == 2 + assert by_name["area"] == 2 + assert by_name["side"] == 6 + + with server.open_file("app.py"): + signature = await asyncio.wait_for( + server.server.send.signature_help( + { + "textDocument": { + "uri": (python_project / "app.py").as_uri() + }, + "position": {"line": 2, "character": len("first = greet(")}, + } + ), + timeout=8, + ) + assert signature == { + "activeParameter": 0, + "activeSignature": 0, + "signatures": [ + { + "activeParameter": 0, + "label": "(name: str) -> str", + "parameters": [ + {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 10]} + ], + } + ], + } + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_read_only_requests_return_exact_shapes( + python_project, + create_pyright, +): + """One server session covers the advertised requests without a high-level API.""" + server = create_pyright() + before = {path: path.read_bytes() for path in python_project.glob("*.py")} + + def uri(name): + return (python_project / name).as_uri() + + def at(name, line, character): + return { + "textDocument": {"uri": uri(name)}, + "position": {"line": line, "character": character}, + } + + square_uses = [_range(2, 26, 2, 32), _range(5, 11, 5, 17), _range(5, 24, 5, 30)] + corpus = [ + ("declaration", at("report.py", 2, 26), [{"uri": uri("shapes.py"), "range": _range(17, 6, 17, 12)}]), + ("type_definition", at("report.py", 4, 0), [{"uri": uri("shapes.py"), "range": _range(4, 6, 4, 11)}]), + ( + "document_highlight", + at("shapes.py", 19, 13), + [ + {"kind": 3, "range": _range(19, 13, 19, 17)}, + {"kind": 2, "range": _range(22, 20, 22, 24)}, + {"kind": 2, "range": _range(22, 32, 22, 36)}, + ], + ), + ("prepare_rename", at("shapes.py", 17, 6), _range(17, 6, 17, 12)), + ( + "signature_help", + at("report.py", 5, len("squares = [Square(2.0), Square(")), + { + "activeParameter": 0, + "activeSignature": 0, + "signatures": [ + { + "activeParameter": 0, + "label": "(side: float) -> Square", + "parameters": [ + {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 12]} + ], + } + ], + }, + ), + ( + "prepare_call_hierarchy", + at("shapes.py", 25, 4), + [ + { + "kind": 12, + "name": "total_area", + "uri": uri("shapes.py"), + "range": _range(25, 4, 25, 14), + "selectionRange": _range(25, 4, 25, 14), + } + ], + ), + # UTF-16 column 14 is the second `x`; a code-point column would miss it. + ("definition", at("emoji.py", 0, 14), [{"uri": uri("emoji.py"), "range": _range(0, 0, 0, 1)}]), + ("hover", at("emoji.py", 0, 10), { + "contents": {"kind": "markdown", "value": "```python\n(variable) y: Literal['\U0001F600']\n```"}, + "range": _range(0, 10, 0, 11), + }), + # Blank line and unknown file: Pyright answers null, never an error. + ("hover", at("app.py", 1, 0), None), + ("definition", at("app.py", 1, 0), None), + ("references", {**at("app.py", 1, 0), "context": {"includeDeclaration": True}}, None), + ("hover", at("missing.py", 0, 0), None), + ("definition", at("missing.py", 0, 0), None), + ( + "code_action", + { + "textDocument": {"uri": uri("report.py")}, + "range": _range(0, 0, 2, 44), + "context": {"diagnostics": []}, + }, + [], + ), + ( + "code_action", + { + "textDocument": {"uri": uri("report.py")}, + "range": _range(0, 0, 2, 44), + "context": {"diagnostics": [], "only": ["source.organizeImports"]}, + }, + [], + ), + ] + + async def exercise(): + async with server.start_server(): + send = server.server.send + with server.open_file("app.py"), server.open_file("emoji.py"), server.open_file( + "shapes.py" + ), server.open_file("report.py"): + for method, params, expected in corpus: + result = await asyncio.wait_for(getattr(send, method)(params), timeout=8) + assert _portable_lsp_payload(result) == _portable_lsp_payload(expected), ( + method, params.get("position", params) + ) + + # The high-level API passes UTF-16 columns through unchanged. + definition = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 14), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + assert await asyncio.wait_for(server.request_hover("app.py", 1, 0), timeout=8) is None + assert await asyncio.wait_for(server.request_references("app.py", 1, 0), timeout=8) == [] + + # Call hierarchy: incoming from the report module, outgoing to + # Shape.area in the workspace and to typeshed's sum overloads. + item = (await asyncio.wait_for(send.prepare_call_hierarchy(at("shapes.py", 25, 4)), timeout=8))[0] + incoming = await asyncio.wait_for(send.incoming_calls({"item": item}), timeout=8) + assert _portable_lsp_payload(incoming) == _portable_lsp_payload([ + { + "from": { + "kind": 2, + "name": "(module) report.py", + "uri": uri("report.py"), + "range": _range(0, 0, 0, 0), + "selectionRange": _range(0, 0, 0, 0), + }, + "fromRanges": [_range(6, 10, 6, 20)], + } + ]) + outgoing = await asyncio.wait_for(send.outgoing_calls({"item": item}), timeout=8) + workspace_calls = [ + call for call in outgoing if _same_file_uri(call["to"]["uri"], uri("shapes.py")) + ] + assert _portable_lsp_payload(workspace_calls) == _portable_lsp_payload([ + { + "to": { + "kind": 6, + "name": "area", + "uri": uri("shapes.py"), + "range": _range(10, 8, 10, 12), + "selectionRange": _range(10, 8, 10, 12), + }, + "fromRanges": [_range(26, 21, 26, 25)], + } + ]) + builtin_calls = [call for call in outgoing if call not in workspace_calls] + assert builtin_calls + for call in builtin_calls: + assert call["to"]["name"] == "sum" + assert call["to"]["uri"].endswith("/stdlib/builtins.pyi") + assert call["fromRanges"] == [_range(26, 11, 26, 14)] + + # Rename is a WorkspaceEdit proposal; nothing is applied. + proposal = await asyncio.wait_for( + send.rename({**at("shapes.py", 17, 6), "newName": "Box"}), timeout=8 + ) + changes = sorted(proposal["documentChanges"], key=lambda change: change["textDocument"]["uri"]) + assert _portable_lsp_payload(changes) == _portable_lsp_payload([ + { + "textDocument": {"uri": uri("report.py"), "version": None}, + "edits": [{"range": span, "newText": "Box"} for span in square_uses], + }, + { + "textDocument": {"uri": uri("shapes.py"), "version": None}, + "edits": [{"range": _range(17, 6, 17, 12), "newText": "Box"}], + }, + ]) + + # completionItem/resolve adds documentation to a raw item. + completion = await asyncio.wait_for( + send.completion({**at("report.py", 7, len("label = squares[0].")), "context": {"triggerKind": 1}}), + timeout=8, + ) + raw = next(entry for entry in completion["items"] if entry["label"] == "describe") + resolved = await asyncio.wait_for(send.resolve_completion_item(raw), timeout=8) + assert resolved["documentation"] == {"kind": "plaintext", "value": "def describe() -> str"} + assert resolved["kind"] == 2 + assert resolved["label"] == "describe" + + # Unadvertised requests fail with MethodNotFound instead of hanging. + with pytest.raises(Error) as unsupported: + await asyncio.wait_for(send.implementation(at("shapes.py", 10, 8)), timeout=8) + assert unsupported.value.code == ErrorCodes.MethodNotFound + + await asyncio.wait_for(exercise(), timeout=60) + assert server.server.process is None + assert {path: path.read_bytes() for path in python_project.glob("*.py")} == before + + +@pytest.mark.asyncio +async def test_real_pyright_commands_cannot_edit_the_workspace( + python_project, + create_pyright, +): + """workspace/executeCommand is reachable but never changes files. + + Pyright's organize-imports command is disabled by the adapter configuration + and returns an empty result. When a client enables it, Pyright answers with + a WorkspaceEdit proposal and asks the client to apply it; the adapter + refuses that reverse request, so the workspace stays unchanged. + """ + server = create_pyright() + report = python_project / "report.py" + before = report.read_bytes() + apply_requests = [] + + async def exercise(): + async with server.start_server(): + send = server.server.send + handlers = server.server.on_request_handlers + refuse_edit = handlers["workspace/applyEdit"] + + async def record_apply_edit(params): + result = await refuse_edit(params) + apply_requests.append((params, result)) + return result + + handlers["workspace/applyEdit"] = record_apply_edit + command = {"command": "pyright.organizeimports", "arguments": [report.as_uri()]} + + with server.open_file("report.py"): + assert await asyncio.wait_for(send.execute_command(command), timeout=8) == [] + with pytest.raises(Error): + await asyncio.wait_for( + send.execute_command({"command": "pyright.doesNotExist", "arguments": []}), + timeout=8, + ) + + # Opt in to organize imports and let Pyright re-read its settings. + adapter_configuration = handlers["workspace/configuration"] + + async def permissive_configuration(params): + answers = await adapter_configuration(params) + for item, answer in zip(params["items"], answers): + if item.get("section") == "pyright": + answer["disableOrganizeImports"] = False + return answers + + handlers["workspace/configuration"] = permissive_configuration + server.server.notify.workspace_did_change_configuration({"settings": {}}) + loop = asyncio.get_running_loop() + deadline = loop.time() + 10 + proposal = [] + while not proposal and loop.time() < deadline: + await asyncio.sleep(0.1) + proposal = await asyncio.wait_for(send.execute_command(command), timeout=8) + assert _portable_lsp_payload(proposal) == _portable_lsp_payload({ + "changes": { + report.as_uri(): [ + { + "range": _range(0, 0, 2, 44), + "newText": "import os\nimport sys\n\nfrom shapes import Point, Square, total_area", + } + ] + } + }) + for _ in range(50): + if apply_requests: + break + await asyncio.sleep(0.1) + assert [result for _, result in apply_requests] == [ + {"applied": False, "failureReason": "multilspy Pyright client is read-only"} + ] + assert apply_requests[0][0]["edit"] == proposal + + await asyncio.wait_for(exercise(), timeout=60) + assert server.server.process is None + assert report.read_bytes() == before + + +@pytest.mark.asyncio +async def test_real_pyright_publishes_type_diagnostics_without_editing( + python_project, + create_pyright, +): + server = create_pyright() + source = python_project / "invalid.py" + before = source.read_bytes() + + async def exercise(): + async with server.start_server(): + with server.open_file("invalid.py"): + found = set() + # Allow delayed cold starts: a short timeout is not a failure. + loop = asyncio.get_running_loop() + deadline = loop.time() + 18 + while loop.time() < deadline: + try: + notification = await server.next_diagnostics( + timeout=min(2, max(0.01, deadline - loop.time())) + ) + except asyncio.TimeoutError: + continue + if not _same_file_uri(notification.get("uri", ""), source.as_uri()): + continue + found.update( + entry.get("code") + for entry in notification.get("diagnostics", []) + if isinstance(entry, dict) + ) + if "reportReturnType" in found: + break + assert "reportReturnType" in found + + await asyncio.wait_for(exercise(), timeout=30) + assert source.read_bytes() == before + assert server.server.process is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "mode, expected_codes", + [ + ("off", set()), + ("basic", {"reportReturnType"}), + ("standard", {"reportReturnType"}), + ("strict", {"reportReturnType"}), + ], +) +async def test_real_pyright_type_checking_mode_controls_push_diagnostics( + python_project, + create_pyright, + mode, + expected_codes, +): + (python_project / "pyrightconfig.json").write_text( + json.dumps({"typeCheckingMode": mode, "include": ["."]}) + ) + server = create_pyright() + source = python_project / "invalid.py" + + async def exercise(): + async with server.start_server(): + with server.open_file("invalid.py"): + # Pyright can publish an initial empty snapshot and then a + # complete analysis. Observe until the expected diagnostic + # state appears, with an explicit finite deadline. + loop = asyncio.get_running_loop() + deadline = loop.time() + 18 + observed = None + while loop.time() < deadline: + try: + notification = await server.next_diagnostics( + timeout=min(2, max(0.01, deadline - loop.time())) + ) + except asyncio.TimeoutError: + continue + if not _same_file_uri(notification.get("uri", ""), source.as_uri()): + continue + observed = notification.get("diagnostics", []) + if {item.get("code") for item in observed} == expected_codes: + return observed + pytest.fail(f"Expected diagnostics {expected_codes!r}; last received: {observed!r}") + + diagnostics = await asyncio.wait_for(exercise(), timeout=30) + assert {entry["code"] for entry in diagnostics} == expected_codes + assert all(entry["severity"] == 1 for entry in diagnostics) + assert all(entry["range"] == _range(1, 11, 1, 14) for entry in diagnostics) + assert server.server.process is None + assert not server.diagnostics_dropped + + +def test_real_pyright_sync_api_works_and_closes_provider( + python_project, + pyright_binary, +): + sync = SyncLanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(python_project), + timeout=15, + ) + with sync.start_server(): + definition = sync.request_definition("app.py", 2, 9) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "lib.py" + completion = sync.request_completions("worker.py", 5, len("result = worker.")) + assert "process" in {item["completionText"] for item in completion} + # Cross-file references require the target module to be indexed. + # Keep both files open instead of relying on OS-dependent background + # workspace discovery timing. + with sync.open_file("shapes.py"), sync.open_file("report.py"): + references = sync.request_references("shapes.py", 17, 6) + assert [item["relativePath"] for item in references] == ["report.py"] * 3 + hover = sync.request_hover("report.py", 6, 10) + assert hover["range"] == _range(6, 10, 6, 20) + symbols, _ = sync.request_document_symbols("shapes.py") + assert "total_area" in {entry["name"] for entry in symbols} + assert sync.request_hover("app.py", 1, 0) is None + assert sync.language_server.server.process is None + assert sync.loop.is_closed() + assert not sync.loop_thread.is_alive() + + +def test_invalid_explicit_pyright_binary_fails_instead_of_skipping( + request, monkeypatch, tmp_path +): + # A broken CI installation or an incorrectly set env var must fail visibly, + # not turn all real Pyright tests green by skipping them. + monkeypatch.setenv("MULTILSPY_PYRIGHT_TEST_BINARY", str(tmp_path / "not-installed")) + with pytest.raises(pytest.fail.Exception, match="existing absolute file"): + request.getfixturevalue("pyright_binary") + + +@pytest.mark.asyncio +async def test_real_pyright_unicode_workspace_and_restart(tmp_path, pyright_binary): + # Spaces, non-ASCII names and non-BMP characters must survive URI encoding + # and reuse of a LanguageServer instance must not replay old notifications. + root = tmp_path / "Python project δΈ­ζ–‡ 🐍" + root.mkdir() + (root / "functions.py").write_text( + "def greet(name: str) -> str:\n return name.upper()\n", encoding="utf-8" + ) + (root / "caller.py").write_text( + "from functions import greet\nresult = greet('Ada')\n", encoding="utf-8" + ) + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(root), + ) + params = server._get_initialize_params(str(root)) + assert params["rootUri"] == root.as_uri() + assert params["workspaceFolders"][0]["uri"] == root.as_uri() + + for attempt in range(2): + previous_queue = server.diagnostics + if attempt: + previous_queue.put_nowait({"uri": "file:///old-session.py"}) + server.diagnostics_dropped = True + async with server.start_server(): + assert server.diagnostics is not previous_queue + assert not server.diagnostics_dropped + definition = await asyncio.wait_for( + server.request_definition("caller.py", 1, 10), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("functions.py", _range(0, 4, 0, 9)) + ] + assert server.server.process is None + assert not server.server_started + + +@pytest.mark.asyncio +async def test_real_pyright_incremental_edits_use_utf16_columns( + python_project, create_pyright +): + """Local buffer and Pyright must agree on didChange after an astral symbol.""" + source = python_project / "emoji.py" + original = source.read_bytes() + server = create_pyright() + async with server.start_server(): + with server.open_file("emoji.py"): + before = await asyncio.wait_for(server.request_definition("emoji.py", 0, 14), 8) + assert [(item["relativePath"], item["range"]) for item in before] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + # `x` after the emoji starts at UTF-16 column 14, not codepoint 13. + cursor = server.insert_text_at_position("emoji.py", 0, 14, "missing_") + assert cursor == {"line": 0, "character": 22} + assert server.get_open_file_text("emoji.py") == "x = 'πŸ˜€'; y = missing_x\n" + for _ in range(20): + changed = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 18), timeout=8 + ) + if not changed: + break + await asyncio.sleep(0.1) + assert changed == [] + + assert server.delete_text_between_positions( + "emoji.py", {"line": 0, "character": 14}, + {"line": 0, "character": 22}, + ) == "missing_" + assert server.get_open_file_text("emoji.py") == source.read_text(encoding="utf-8") + for _ in range(20): + restored = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 14), timeout=8 + ) + if restored: + break + await asyncio.sleep(0.1) + assert [(item["relativePath"], item["range"]) for item in restored] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + assert source.read_bytes() == original + assert server.server.process is None + + +@pytest.mark.parametrize("extension", ["", ".cmd", ".exe"]) +def test_pyright_version_resolves_platform_specific_cli_wrappers( + tmp_path, monkeypatch, extension +): + binary = tmp_path / "pyright-langserver" + binary.write_text("fake", encoding="utf-8") + sibling = tmp_path / ("pyright" + extension) + sibling.write_text("fake", encoding="utf-8") + calls = [] + + def fake_run(argv, **kwargs): + calls.append((argv, kwargs)) + return subprocess.CompletedProcess(argv, 0, stdout="pyright 1.1.413\n", stderr="") + + monkeypatch.setattr(subprocess, "run", fake_run) + assert _pyright_version(binary) == TESTED_PYRIGHT_VERSION + expected_command = [str(sibling), "--version"] + if os.name == "nt" and extension == ".cmd": + expected_command = ["cmd.exe", "/d", "/c", str(sibling), "--version"] + assert calls[0][0] == expected_command + assert calls[0][1]["timeout"] == 60 + + +@pytest.mark.asyncio +async def test_real_pyright_opt_in_organize_imports_applies_via_authorized_client( + python_project, create_pyright +): + """An explicitly installed callback can apply an actual Pyright WorkspaceEdit. + + The library does not make file changes by itself. The callback simulates + the embedding editor's authorization, UTF-16 position handling and disk + persistence, restricted to a temporary fixture file. + """ + server = create_pyright() + report = python_project / "report.py" + before = {path: path.read_bytes() for path in python_project.iterdir() if path.is_file()} + done = asyncio.Event() + received = [] + + async def apply_authorized_edit(params): + received.append(params) + keys = list(params["edit"]["changes"]) + if len(keys) != 1 or not _same_file_uri(keys[0], report.as_uri()): + raise ValueError("Unexpected workspace edit target") + edits = params["edit"]["changes"][keys[0]] + content = report.read_text(encoding="utf-8") + translated = [] + for edit in edits: + start = edit["range"]["start"] + end = edit["range"]["end"] + translated.append(( + TextUtils.get_index_from_line_col(content, start["line"], start["character"]), + TextUtils.get_index_from_line_col(content, end["line"], end["character"]), + edit["newText"], + )) + for start, end, replacement in sorted(translated, reverse=True): + content = content[:start] + replacement + content[end:] + report.write_text(content, encoding="utf-8") + done.set() + return {"applied": True} + + server.set_workspace_edit_handler(apply_authorized_edit) + async def exercise(): + async with server.start_server(): + with server.open_file("report.py"): + command = {"command": "pyright.organizeimports", "arguments": [report.as_uri()]} + result = await asyncio.wait_for( + server.server.send.execute_command(command), timeout=8 + ) + assert isinstance(result, dict) + assert any(_same_file_uri(key, report.as_uri()) for key in result["changes"]) + await asyncio.wait_for(done.wait(), timeout=8) + + await asyncio.wait_for(exercise(), timeout=35) + assert len(received) == 1 + assert report.read_text(encoding="utf-8").startswith( + "import os\nimport sys\n\nfrom shapes import Point, Square, total_area" + ) + for path, contents in before.items(): + if path != report: + assert path.read_bytes() == contents + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_create_type_stub_writes_without_workspace_apply_edit( + tmp_path, pyright_binary +): + """A Pyright command can write .pyi files directly, without asking applyEdit. + + Exercise only an isolated disposable virtualenv and project. This is an + explicit warning that merely denying workspace/applyEdit is not a sandbox. + """ + env_root = tmp_path / "venvs" + env = env_root / "isolated" + venv.create(env, with_pip=False) + if os.name == "nt": + site_packages = env / "Lib" / "site-packages" + else: + site_packages = env / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "site-packages" + vendor = site_packages / "toy_untyped_package" + vendor.mkdir(parents=True) + (vendor / "__init__.py").write_text( + "def hello(x):\n return x * 2\n", encoding="utf-8" + ) + project = tmp_path / "project" + project.mkdir() + source = project / "app.py" + original = "import toy_untyped_package\nprint(toy_untyped_package.hello(3))\n" + source.write_text(original, encoding="utf-8") + (project / "pyrightconfig.json").write_text(json.dumps({ + "typeCheckingMode": "strict", + "reportMissingTypeStubs": "warning", + "venvPath": str(env_root), + "venv": "isolated", + "stubPath": "typings", + "include": ["app.py"], + }), encoding="utf-8") + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), str(project) + ) + apply_requests = [] + # No edit callback is registered; prove the server still writes directly. + stub = project / "typings" / "toy_untyped_package" / "__init__.pyi" + + async def exercise(): + async with server.start_server(): + refuse_edit = server.server.on_request_handlers["workspace/applyEdit"] + + async def record_edit_request(params): + apply_requests.append(params) + return await refuse_edit(params) + + server.server.on_request_handlers["workspace/applyEdit"] = record_edit_request + with server.open_file("app.py"): + diagnostics = [] + loop = asyncio.get_running_loop() + deadline = loop.time() + 20 + while loop.time() < deadline: + try: + notification = await server.next_diagnostics(timeout=2) + except asyncio.TimeoutError: + continue + if _same_file_uri(notification.get("uri", ""), source.as_uri()): + diagnostics = notification.get("diagnostics", []) + if any(d.get("code") == "reportMissingTypeStubs" for d in diagnostics): + break + assert any(d.get("code") == "reportMissingTypeStubs" for d in diagnostics) + actions = await asyncio.wait_for(server.server.send.code_action({ + "textDocument": {"uri": source.as_uri()}, + "range": _range(0, 0, 0, len("import toy_untyped_package")), + "context": {"diagnostics": diagnostics}, + }), timeout=8) + action = next( + action for action in actions + if action.get("command", {}).get("command") == "pyright.createtypestub" + ) + assert not stub.exists() + await asyncio.wait_for( + server.server.send.execute_command(action["command"]), timeout=18 + ) + for _ in range(40): + if stub.is_file(): + break + await asyncio.sleep(0.1) + assert stub.is_file() + assert "def hello" in stub.read_text(encoding="utf-8") + + await asyncio.wait_for(exercise(), timeout=65) + assert source.read_text(encoding="utf-8") == original + assert server.server.process is None + assert not server.server_started + assert apply_requests == [] diff --git a/tests/multilspy/test_path_utils_portability.py b/tests/multilspy/test_path_utils_portability.py new file mode 100644 index 0000000..7ebfd6a --- /dev/null +++ b/tests/multilspy/test_path_utils_portability.py @@ -0,0 +1,28 @@ +"""Cross-platform URI and Windows drive casing regressions. + +Exercise Windows semantics on Linux/macOS too, independent of running a +Windows interpreter; native Windows CI separately exercises real Pyright. +""" + +import ntpath +from pathlib import PureWindowsPath +from types import SimpleNamespace + +from multilspy.multilspy_utils import PathUtils +import multilspy.multilspy_utils as utils + + +def test_case_insensitive_windows_drives_are_same_drive(monkeypatch): + monkeypatch.setattr(utils, "PurePath", PureWindowsPath) + monkeypatch.setattr(utils, "os", SimpleNamespace(path=ntpath)) + # Pyright uses lowercase drive URI, pathlib workspace might uppercase it. + assert PathUtils.get_relative_path( + r"c:\Repo\src\module.py", r"C:\Repo" + ) == r"src\module.py" + assert PathUtils.get_relative_path( + r"D:\Repo\src\module.py", r"C:\Repo" + ) is None + # A differently cased but otherwise identical workspace is same location. + assert PathUtils.get_relative_path( + r"c:\REPO\module.py", r"C:\repo" + ) == "module.py" diff --git a/tests/multilspy/test_pyright_adapter_notifications.py b/tests/multilspy/test_pyright_adapter_notifications.py new file mode 100644 index 0000000..b8b1210 --- /dev/null +++ b/tests/multilspy/test_pyright_adapter_notifications.py @@ -0,0 +1,456 @@ +"""Pyright adapter callbacks and startup behavior without a language-server process. + +Mirrors the mock-transport pattern from test_adapter_notifications.py. +""" + +import asyncio +import os +from unittest.mock import AsyncMock, Mock + +import pytest + +from multilspy.language_server import LanguageServer +from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, +) +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_exceptions import MultilspyException +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture +def pyright(tmp_path): + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server="pyright"), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + assert isinstance(server, PyrightServer) + requests, notifications = {}, {} + transport = Mock() + transport.on_request.side_effect = lambda method, handler: requests.update( + {method: handler} + ) + transport.on_notification.side_effect = lambda method, handler: ( + notifications.update({method: handler}) + ) + transport.start = AsyncMock() + transport.shutdown = AsyncMock() + transport.stop = AsyncMock() + transport.send.initialize = AsyncMock( + return_value={ + "capabilities": { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, + "textDocumentSync": 2, + } + } + ) + server.server = transport + return server, transport, requests, notifications + + +def test_pyright_initialize_params_are_loaded_from_profile(tmp_path): + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server="pyright"), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + params = server._get_initialize_params(str(tmp_path.resolve())) + assert "_description" not in params + assert params["processId"] == os.getpid() + assert params["rootUri"] == tmp_path.resolve().as_uri() + assert params["rootPath"] == str(tmp_path.resolve()) + assert params["workspaceFolders"] == [ + {"name": tmp_path.resolve().name, "uri": tmp_path.resolve().as_uri()} + ] + assert params["capabilities"]["general"]["positionEncodings"] == ["utf-16"] + assert params["capabilities"]["workspace"]["applyEdit"] is False + assert params["capabilities"]["workspace"]["configuration"] is True + assert params["capabilities"]["textDocument"]["completion"]["contextSupport"] is True + assert params["capabilities"]["textDocument"]["signatureHelp"] + + +@pytest.mark.asyncio +async def test_pyright_initializes_and_cleans_up_like_existing_adapters(pyright): + server, transport, requests, notifications = pyright + async with server.start_server(): + assert server.server_started + assert server.completions_available.is_set() + transport.send.initialize.assert_awaited_once() + transport.notify.initialized.assert_called_once_with({}) + assert "workspace/configuration" in requests + assert "workspace/applyEdit" in requests + assert "client/registerCapability" in requests + assert "textDocument/publishDiagnostics" in notifications + assert "window/logMessage" in notifications + assert "$/progress" in notifications + assert transport.start.await_count == 1 + assert not server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_accepts_empty_capability_options(pyright): + server, transport, _, _ = pyright + transport.send.initialize.return_value = { + "capabilities": { + "definitionProvider": {}, + "referencesProvider": {}, + "hoverProvider": {}, + "completionProvider": {}, + "documentSymbolProvider": {}, + "workspaceSymbolProvider": {}, + "positionEncoding": "utf-16", + } + } + async with server.start_server(): + assert server.server_started + assert server.completions_available.is_set() + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_configuration_is_explicit_and_bounded(pyright): + server, _, requests, _ = pyright + async with server.start_server(): + handler = requests["workspace/configuration"] + result = await handler( + { + "items": [ + {"section": "python"}, + {"section": "python.analysis"}, + {"section": "pyright"}, + {"section": "untrusted"}, + ] + } + ) + assert result[0] == {"analysis": {}} + assert result[1] == {} + assert result[2]["disableLanguageServices"] is False + assert result[3] is None + assert await handler({"items": []}) == [] + assert await handler({"items": "bad"}) == [] + assert await handler({"items": [{}] * 65}) == [None] * 65 + assert await handler(None) == [] + + +@pytest.mark.asyncio +async def test_pyright_refuses_edit_and_ignores_registration(pyright): + server, _, requests, _ = pyright + async with server.start_server(): + result = await requests["workspace/applyEdit"]( + {"edit": {"changes": {"file:///tmp/example.py": []}}} + ) + assert result == { + "applied": False, + "failureReason": "multilspy Pyright client is read-only", + } + # Like the other adapters, registration requests are acknowledged and ignored. + assert await requests["client/registerCapability"]( + {"registrations": [{"method": "workspace/executeCommand"}]} + ) is None + + +@pytest.mark.asyncio +async def test_pyright_diagnostics_are_queued_not_dropped_silently(pyright): + server, _, _, notifications = pyright + async with server.start_server(): + await notifications["textDocument/publishDiagnostics"](None) + await notifications["textDocument/publishDiagnostics"]({"uri": 12}) + assert server.diagnostics.empty() + for i in range(64): + await notifications["textDocument/publishDiagnostics"]( + { + "uri": "file:///tmp/example.py", + "diagnostics": [], + "version": i, + } + ) + assert server.diagnostics.full() + await notifications["textDocument/publishDiagnostics"]( + { + "uri": "file:///tmp/example.py", + "version": 65, + } + ) + assert server.diagnostics_dropped is True + updates = [await server.next_diagnostics(timeout=1) for _ in range(64)] + assert [item["version"] for item in updates] == list(range(1, 64)) + [65] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "capabilities, exception, error", + [ + (None, TypeError, "Invalid Pyright"), + ([], TypeError, "Invalid Pyright"), + ({}, ValueError, "Pyright missing required capability"), + ( + {"definitionProvider": True, "referencesProvider": True, "hoverProvider": True}, + ValueError, "Pyright missing required capability: completionProvider", + ), + ( + { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, + "positionEncoding": "utf-8", + }, + ValueError, + "Unsupported Pyright position", + ), + ], +) +async def test_bad_initialize_rejected_and_process_stopped( + pyright, capabilities, exception, error +): + server, transport, _, _ = pyright + transport.send.initialize.return_value = {"capabilities": capabilities} + with pytest.raises(exception, match=error): + async with server.start_server(): + pytest.fail("Malformed capabilities cannot enable a server") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_failed_initialize_request_still_stops_provider(pyright): + server, transport, _, _ = pyright + transport.send.initialize.side_effect = TimeoutError("synthetic") + with pytest.raises(TimeoutError): + async with server.start_server(): + pytest.fail("Initialize must fail") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_failed_process_start_still_enters_stop_cleanup(pyright): + server, transport, _, _ = pyright + transport.start.side_effect = OSError("synthetic failed spawn") + with pytest.raises(OSError): + async with server.start_server(): + pytest.fail("Process start must fail") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_shutdown_error_never_skips_process_stop(pyright): + server, transport, _, _ = pyright + transport.shutdown.side_effect = RuntimeError("synthetic shutdown failure") + with pytest.raises(RuntimeError, match="shutdown failure"): + async with server.start_server(): + assert server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_cancelled_initialize_still_stops_process(pyright): + server, transport, _, _ = pyright + ready = asyncio.Event() + block = asyncio.Event() + + async def initialize(_params): + ready.set() + await block.wait() + + transport.send.initialize.side_effect = initialize + + async def enter_context(): + async with server.start_server(): + pytest.fail("Cancelled initialization cannot enter context") + + task = asyncio.create_task(enter_context()) + await asyncio.wait_for(ready.wait(), 2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_pyright_restarting_instance_resets_session_state(pyright): + server, transport, _, notifications = pyright + async with server.start_server(): + await notifications["textDocument/publishDiagnostics"]( + {"uri": "file:///old-session.py", "diagnostics": [{"message": "stale"}]} + ) + server.diagnostics_dropped = True + assert server.diagnostics.qsize() == 1 + assert server.completions_available.is_set() + + async def initialize_again(_params): + # Completion readiness and the diagnostics queue belong to this run. + assert not server.completions_available.is_set() + assert server.diagnostics.empty() + assert not server.diagnostics_dropped + return {"capabilities": { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, + }} + + transport.send.initialize.side_effect = initialize_again + async with server.start_server(): + assert server.diagnostics.empty() + assert server.completions_available.is_set() + assert not server.diagnostics_dropped + assert transport.start.await_count == 2 + assert transport.stop.await_count == 2 + assert transport.shutdown.await_count == 2 + + +@pytest.mark.asyncio +async def test_pyright_does_not_allow_nested_server_lifetimes(pyright): + server, transport, _, _ = pyright + async with server.start_server(): + with pytest.raises(MultilspyException, match="already started"): + async with server.start_server(): + pytest.fail("Nested start must fail before altering the running server") + assert server.server_started + assert transport.stop.await_count == 0 + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_unresponsive_shutdown_cannot_block_pyright_cleanup(pyright): + server, transport, _, _ = pyright + server._shutdown_timeout_seconds = 0.05 + waiting_forever = asyncio.Event() + transport.shutdown.side_effect = waiting_forever.wait + async with server.start_server(): + assert server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_pyright_opt_in_workspace_edit_handler_is_explicit_and_bounded(pyright): + server, _, requests, _ = pyright + expected = {"edit": {"changes": {"file:///test.py": []}}, "label": "demo"} + callback = AsyncMock(return_value={"applied": True}) + with pytest.raises(TypeError, match="async function"): + server.set_workspace_edit_handler(42) + with pytest.raises(TypeError, match="async function"): + server.set_workspace_edit_handler(lambda _params: {"applied": True}) + with pytest.raises(ValueError, match="positive finite"): + server.set_workspace_edit_handler(callback, timeout_seconds=0) + with pytest.raises(ValueError, match="positive finite"): + server.set_workspace_edit_handler(callback, timeout_seconds=float("inf")) + server.set_workspace_edit_handler(callback) + assert server._get_initialize_params(server.repository_root_path)["capabilities"]["workspace"]["applyEdit"] is True + + async with server.start_server(): + configuration = await requests["workspace/configuration"]( + {"items": [{"section": "pyright"}]} + ) + assert configuration[0]["disableOrganizeImports"] is False + assert await requests["workspace/applyEdit"](expected) == {"applied": True} + callback.assert_awaited_once_with(expected) + with pytest.raises(MultilspyException, match="while running"): + server.set_workspace_edit_handler(None) + + # A caller can revert to safe/default behavior between sessions. + server.set_workspace_edit_handler(None) + assert server._get_initialize_params(server.repository_root_path)["capabilities"]["workspace"]["applyEdit"] is False + async with server.start_server(): + configuration = await requests["workspace/configuration"]( + {"items": [{"section": "pyright"}]} + ) + assert configuration[0]["disableOrganizeImports"] is True + assert await requests["workspace/applyEdit"](expected) == { + "applied": False, + "failureReason": "multilspy Pyright client is read-only", + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad_response", [None, {}, {"applied": "yes"}, []]) +async def test_pyright_invalid_workspace_edit_response_fails_closed(pyright, bad_response): + server, _, requests, _ = pyright + callback = AsyncMock(return_value=bad_response) + server.set_workspace_edit_handler(callback) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, + "failureReason": "Workspace edit handler failed", + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_edit_handler_exception_fails_closed_without_leaking_paths(pyright): + server, transport, requests, _ = pyright + private_path = "/private/secret/fixture.py" + server.set_workspace_edit_handler(AsyncMock(side_effect=OSError(private_path))) + async with server.start_server(): + result = await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) + assert result == {"applied": False, "failureReason": "Workspace edit handler failed"} + assert private_path not in repr(result) + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_workspace_edit_handler_times_out_and_stops(pyright): + server, transport, requests, _ = pyright + wait = asyncio.Event() + async def never_return(_params): + await wait.wait() + server.set_workspace_edit_handler(never_return, timeout_seconds=0.02) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, "failureReason": "Workspace edit handler timed out" + } + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_workspace_edit_response_is_normalized(pyright): + server, _, requests, _ = pyright + callback = AsyncMock(return_value={ + "applied": False, "failureReason": "Needs approval", "failedChange": 1, + "untrustedExtraField": "do not forward", + }) + server.set_workspace_edit_handler(callback) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"documentChanges": []}}) == { + "applied": False, "failureReason": "Needs approval", "failedChange": 1 + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad", [ + {"applied": False, "failedChange": True}, + {"applied": False, "failedChange": -1}, + {"applied": False, "failureReason": 123}, +]) +async def test_pyright_workspace_edit_response_invalid_metadata_is_rejected(pyright, bad): + server, _, requests, _ = pyright + server.set_workspace_edit_handler(AsyncMock(return_value=bad)) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, "failureReason": "Workspace edit handler failed" + } diff --git a/tests/multilspy/test_pyright_process_lifecycle.py b/tests/multilspy/test_pyright_process_lifecycle.py new file mode 100644 index 0000000..d4950fe --- /dev/null +++ b/tests/multilspy/test_pyright_process_lifecycle.py @@ -0,0 +1,169 @@ +"""Pyright startup timeout/cancellation against a real but nonresponsive peer. + +These process-level tests mirror test_sync_startup.py: they launch only a +local disposable Python script, never install or discover Pyright. +""" + +import asyncio +import os +import sys + +import pytest + +from multilspy.language_server import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture +def hung_stdio_server(tmp_path): + script = tmp_path / "silent_lsp.py" + script.write_text( + "import sys\n" + "for line in sys.stdin.buffer:\n" + " pass # Read incoming LSP frames; never answer initialize.\n" + ) + return script + + +@pytest.fixture +def pyright_with_fake_transport(tmp_path, hung_stdio_server): + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + ), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + handler = server.server + handler.process_launch_info.cmd = [ + sys.executable, + "-u", + str(hung_stdio_server), + ] + started = asyncio.Event() + created = [] + native_start = handler.start + + async def capture_process(): + await native_start() + created.append(handler.process) + started.set() + + handler.start = capture_process + return server, handler, created, started + + +@pytest.mark.asyncio +async def test_real_initialize_timeout_stops_process_and_readers( + pyright_with_fake_transport, +): + server, handler, created, _started = pyright_with_fake_transport + server._initialize_timeout_seconds = 0.05 + + async def exercise(): + async with server.start_server(): + pytest.fail("No response from synthetic LSP server") + + try: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(exercise(), timeout=5) + assert len(created) == 1 + assert created[0].returncode is not None + assert handler.process is None + assert handler.tasks == {} + assert not handler._response_handlers + assert not server.server_started + finally: + for process in created: + if process.returncode is None: + process.kill() + await process.wait() + + +@pytest.mark.asyncio +async def test_real_cancelled_initialize_stops_process_and_readers( + pyright_with_fake_transport, +): + server, handler, created, started = pyright_with_fake_transport + + async def exercise(): + async with server.start_server(): + pytest.fail("Cancelled startup must not enter the context") + + pending = asyncio.create_task(exercise()) + try: + await asyncio.wait_for(started.wait(), timeout=3) + assert len(created) == 1 + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(pending, timeout=5) + assert created[0].returncode is not None + assert handler.process is None + assert handler.tasks == {} + assert not handler._response_handlers + assert not server.server_started + finally: + if not pending.done(): + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + for process in created: + if process.returncode is None: + process.kill() + await process.wait() + + +@pytest.mark.asyncio +async def test_real_pyright_restarts_after_abandoned_request(tmp_path): + binary = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") + if not binary: + pytest.skip("Real pinned Pyright is not configured") + + (tmp_path / "sample.py").write_text( + "value = 42\nresult = value\n", encoding="utf-8" + ) + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", server_binary=binary, + ), + MultilspyLogger(), str(tmp_path.resolve()), + ) + seen_ids = [] + for _ in range(2): + async with server.start_server(): + handler = server.server + original_send = handler._send_payload + + async def unanswered(payload): + # Pyright may concurrently send workspace/configuration + # requests. Their client responses must keep flowing; only + # silence this *one* outgoing definition request. + if payload.get("method") == "textDocument/definition": + return None + return await original_send(payload) + + handler._send_payload = unanswered + try: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for( + handler.send_request("textDocument/definition", {}), 0.05 + ) + finally: + handler._send_payload = original_send + assert handler._response_handlers == {} + seen_ids.append(handler.request_id - 1) + with server.open_file("sample.py"): + definition = await asyncio.wait_for( + server.request_definition("sample.py", 1, 10), 8 + ) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "sample.py" + assert definition[0]["range"]["start"] == { + "line": 0, "character": 0, + } + assert handler._response_handlers == {} + assert handler.process is None + assert handler.tasks == {} + assert seen_ids[1] > seen_ids[0] diff --git a/tests/multilspy/test_utf16_buffer_positions.py b/tests/multilspy/test_utf16_buffer_positions.py new file mode 100644 index 0000000..cd6d820 --- /dev/null +++ b/tests/multilspy/test_utf16_buffer_positions.py @@ -0,0 +1,60 @@ +"""Regression tests for UTF-16 LSP positions in in-memory file buffers. + +Other language servers share this code, so use both Python adapters with a +mocked transport and no external binary or network access. +""" + +from unittest.mock import Mock + +import pytest + +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger +from multilspy.multilspy_utils import TextUtils + + +@pytest.mark.parametrize("backend", ["jedi", "pyright"]) +def test_utf16_insert_and_delete_do_not_desynchronize_file_buffer(tmp_path, backend): + source = "value = '🐍'; target = 1\n" + filename = tmp_path / "example.py" + filename.write_text(source, encoding="utf-8") + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server=backend), + MultilspyLogger(), str(tmp_path.resolve()) + ) + server.server = Mock() + server.server_started = True + before_target = source.index("target") + column = TextUtils._utf16_length(source[:before_target]) + assert column == before_target + 1 # Python index excludes surrogate pair length. + + with server.open_file("example.py"): + position = server.insert_text_at_position("example.py", 0, column, "🦊_") + assert position == {"line": 0, "character": column + 3} + assert server.get_open_file_text("example.py") == "value = '🐍'; 🦊_target = 1\n" + assert server.delete_text_between_positions( + "example.py", {"line": 0, "character": column}, + {"line": 0, "character": column + 3}, + ) == "🦊_" + assert server.get_open_file_text("example.py") == source + changes = [call.args[0] for call in server.server.notify.did_change_text_document.call_args_list] + assert [event["textDocument"]["version"] for event in changes] == [1, 2] + assert [event["contentChanges"][0]["range"]["start"]["character"] for event in changes] == [column, column] + assert filename.read_text(encoding="utf-8") == source + assert not server.open_file_buffers + + +def test_utf16_positions_round_trip_and_reject_half_surrogate(): + text = "a🐍b\n🦊x\n" + for idx in range(len(text) + 1): + line, col = TextUtils.get_line_col_from_index(text, idx) + assert TextUtils.get_index_from_line_col(text, line, col) == idx + with pytest.raises(ValueError, match="surrogate"): + TextUtils.get_index_from_line_col(text, 0, 2) + with pytest.raises(ValueError, match="outside the line"): + TextUtils.get_index_from_line_col(text, 0, 8) + with pytest.raises(ValueError, match="non-negative"): + TextUtils.get_index_from_line_col(text, -1, 0) + assert TextUtils.get_updated_position_from_line_and_column_and_edit(0, 0, "🐍") == (0, 2) + assert TextUtils.get_updated_position_from_line_and_column_and_edit(0, 9, "🐍\n🦊x") == (1, 3)