-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathpyright_server.py
More file actions
284 lines (242 loc) · 12.4 KB
/
Copy pathpyright_server.py
File metadata and controls
284 lines (242 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""
Provides Python specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Python.
"""
import logging
import os
import pathlib
import re
import threading
from typing import cast
from overrides import override
from solidlsp.ls import LanguageServerDependencyProvider, LanguageServerDependencyProviderUvx, SolidLanguageServer
from solidlsp.ls_config import LanguageServerConfig
from solidlsp.lsp_protocol_handler.lsp_types import InitializeParams
from solidlsp.settings import SolidLSPSettings
log = logging.getLogger(__name__)
PYRIGHT_VERSION = "1.1.403"
class PyrightServer(SolidLanguageServer):
"""
Provides Python specific instantiation of the LanguageServer class using Pyright.
Contains various configurations and settings specific to Python.
"""
def __init__(self, config: LanguageServerConfig, repository_root_path: str, solidlsp_settings: SolidLSPSettings):
"""
Creates a PyrightServer instance. This class is not meant to be instantiated directly.
Use LanguageServer.create() instead.
"""
super().__init__(
config,
repository_root_path,
None,
"python",
solidlsp_settings,
)
# Event to signal when initial workspace analysis is complete
self.analysis_complete = threading.Event()
self.found_source_files = False
def _create_dependency_provider(self) -> LanguageServerDependencyProvider:
return LanguageServerDependencyProviderUvx(
self._custom_settings,
self._ls_resources_dir,
package="pyright",
entrypoint="pyright-langserver",
default_version=PYRIGHT_VERSION,
version_setting_key="pyright_version",
extra_args=("--stdio",),
)
@override
def is_ignored_dirname(self, dirname: str) -> bool:
return super().is_ignored_dirname(dirname) or dirname in ["venv", "__pycache__"]
def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams:
"""
Returns the initialize params for the Pyright Language Server.
"""
# Build exclude list based on ignore_all_dot_files setting.
# Pyright's default behavior excludes all dot-prefixed directories (**/.*).
# When ignore_all_dot_files=False, we only exclude specific known directories
# and explicitly include "." to override pyright's internal dot-directory exclusion.
exclude = [
"**/.git",
"**/__pycache__",
"**/build",
"**/dist",
]
if self._ignore_all_dot_files:
exclude.extend(["**/.venv", "**/.env", "**/.pixi"])
init_options: dict = {
"exclude": exclude,
"reportMissingImports": "error",
}
if not self._ignore_all_dot_files:
init_options["include"] = ["."]
# Create basic initialization parameters
initialize_params = { # type: ignore
"processId": os.getpid(),
"rootPath": repository_absolute_path,
"rootUri": pathlib.Path(repository_absolute_path).as_uri(),
"initializationOptions": init_options,
"capabilities": {
"workspace": {
"workspaceEdit": {"documentChanges": True},
"didChangeConfiguration": {"dynamicRegistration": True},
"didChangeWatchedFiles": {"dynamicRegistration": True},
"symbol": {
"dynamicRegistration": True,
"symbolKind": {"valueSet": list(range(1, 27))},
},
"executeCommand": {"dynamicRegistration": True},
},
"textDocument": {
"synchronization": {"dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True, "didSave": True},
"hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]},
"signatureHelp": {
"dynamicRegistration": True,
"signatureInformation": {
"documentationFormat": ["markdown", "plaintext"],
"parameterInformation": {"labelOffsetSupport": True},
},
},
"definition": {"dynamicRegistration": True},
"references": {"dynamicRegistration": True},
"documentSymbol": {
"dynamicRegistration": True,
"symbolKind": {"valueSet": list(range(1, 27))},
"hierarchicalDocumentSymbolSupport": True,
},
"publishDiagnostics": {"relatedInformation": True},
},
},
"workspaceFolders": [
{"uri": pathlib.Path(repository_absolute_path).as_uri(), "name": os.path.basename(repository_absolute_path)}
],
}
return cast(InitializeParams, initialize_params)
def _start_server(self) -> None:
"""
Starts the Pyright Language Server and waits for initial workspace analysis to complete.
This prevents zombie processes by ensuring Pyright has finished its initial background
tasks before we consider the server ready.
Usage:
```
async with lsp.start_server():
# LanguageServer has been initialized and workspace analysis is complete
await lsp.request_definition(...)
await lsp.request_references(...)
# Shutdown the LanguageServer on exit from scope
# LanguageServer has been shutdown cleanly
```
"""
def execute_client_command_handler(params: dict) -> list:
return []
def do_nothing(params: dict) -> None:
return
def window_log_message(msg: dict) -> None:
"""
Monitor Pyright's log messages to detect when initial analysis is complete.
Pyright logs "Found X source files" when it finishes scanning the workspace.
"""
message_text = msg.get("message", "")
log.info(f"LSP: window/logMessage: {message_text}")
# Look for "Found X source files" which indicates workspace scanning is complete
# Unfortunately, pyright is unreliable and there seems to be no better way
if re.search(r"Found \d+ source files?", message_text):
log.info("Pyright workspace scanning complete")
self.found_source_files = True
self.analysis_complete.set()
def handle_pyright_progress_notification(progress_kind: str, params: object | None) -> None:
"""Tracks Pyright-specific progress notifications.
Pyright can emit custom progress notifications instead of only using
``$/progress``. Handling them avoids noisy unhandled-method warnings
and provides an additional signal that initial analysis has quiesced.
"""
# normalizing the notification payload
message_text = ""
percentage: object | None = None
if isinstance(params, dict):
raw_message = params.get("message")
message_text = "" if raw_message is None else str(raw_message)
percentage = params.get("percentage")
elif params is not None:
message_text = str(params)
progress_label = f"{message_text} ({percentage}%)" if percentage is not None else message_text
# logging the progress transition
if progress_kind == "begin":
log.info("Pyright progress started: %s", progress_label)
return
if progress_kind == "report":
log.debug("Pyright progress update: %s", progress_label)
return
log.info("Pyright progress finished: %s", progress_label)
self.analysis_complete.set()
def pyright_begin_progress(params: object | None) -> None:
"""Handles the ``pyright/beginProgress`` notification."""
# delegating to the shared progress handler
handle_pyright_progress_notification("begin", params)
def pyright_report_progress(params: object | None) -> None:
"""Handles the ``pyright/reportProgress`` notification."""
# delegating to the shared progress handler
handle_pyright_progress_notification("report", params)
def pyright_end_progress(params: object | None) -> None:
"""Handles the ``pyright/endProgress`` notification."""
# delegating to the shared progress handler
handle_pyright_progress_notification("end", params)
def check_experimental_status(params: dict) -> None:
"""
Also listen for experimental/serverStatus as a backup signal
"""
if params.get("quiescent") == True:
log.info("Received experimental/serverStatus with quiescent=true")
if not self.found_source_files:
self.analysis_complete.set()
def workspace_configuration_handler(params: dict) -> list:
"""Handle workspace/configuration requests from pyright.
Pyright requests python.analysis settings through this mechanism.
We use it to control include/exclude paths, particularly to allow
dot-prefixed directories when ignore_all_dot_files is False.
"""
log.info(f"Received workspace/configuration request: {params}")
items = params.get("items", [])
results = []
for item in items:
section = item.get("section", "")
if section == "python.analysis" and not self._ignore_all_dot_files:
exclude = ["**/.git", "**/__pycache__", "**/build", "**/dist"]
results.append({"include": ["."], "exclude": exclude})
else:
results.append({})
return results
# Set up notification handlers
self.server.on_request("client/registerCapability", do_nothing)
self.server.on_request("workspace/configuration", workspace_configuration_handler)
self.server.on_notification("language/status", do_nothing)
self.server.on_notification("window/logMessage", window_log_message)
self.server.on_request("workspace/executeClientCommand", execute_client_command_handler)
self.server.on_notification("$/progress", do_nothing)
self.server.on_notification("pyright/beginProgress", pyright_begin_progress)
self.server.on_notification("pyright/reportProgress", pyright_report_progress)
self.server.on_notification("pyright/endProgress", pyright_end_progress)
self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.server.on_notification("language/actionableNotification", do_nothing)
self.server.on_notification("experimental/serverStatus", check_experimental_status)
log.info("Starting pyright-langserver server process")
self.server.start()
# Send proper initialization parameters
initialize_params = self._get_initialize_params(self.repository_root_path)
log.info("Sending initialize request from LSP client to pyright server and awaiting response")
init_response = self.server.send.initialize(initialize_params)
log.info(f"Received initialize response from pyright server: {init_response}")
# Verify that the server supports our required features
assert "textDocumentSync" in init_response["capabilities"]
assert "completionProvider" in init_response["capabilities"]
assert "definitionProvider" in init_response["capabilities"]
# Complete the initialization handshake
self.server.notify.initialized({})
# Wait for Pyright to complete its initial workspace analysis
# This prevents zombie processes by ensuring background tasks finish
log.info("Waiting for Pyright to complete initial workspace analysis...")
if self.analysis_complete.wait(timeout=5.0):
log.info("Pyright initial analysis complete, server ready")
else:
log.warning("Timeout waiting for Pyright analysis completion, proceeding anyway")
# Fallback: assume analysis is complete after timeout
self.analysis_complete.set()