[e988c2]: / tests / autocomplete / language_server.py

Download this file

297 lines (255 with data), 11.5 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
285
286
287
288
289
290
291
292
293
294
295
296
"""
Initialize and provide a thin wrapper around a pyright language server
The initialization dance was inferred from the source code of the pyright
playground client:
https://github.com/erictraut/pyright-playground/blob/main/server/src/lspClient.ts
Another good resource is the specification for the Language Server Protocol:
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification)
though it's a bit hard to navigate.
"""
import json
import os
import re
import sys
from pathlib import Path
from subprocess import PIPE, Popen
class LanguageServer:
def __init__(self, temp_file_path: Path):
self._message_id = 0
# The pyright-langserver needs the ehrql repo directory on
# PYTHONPATH so it can understand ehrql, and it needs the current
# location of the python executable (also where pyright-langserver)
# is on its PATH variable
env = os.environ.copy()
env["PYTHONPATH"] = Path("").absolute().as_uri()
env["PATH"] = os.path.dirname(sys.executable)
self._language_server = Popen(
["pyright-langserver", "--stdio"],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
env=env,
)
# Server immediately emits two log messages:
# {'method': 'window/logMessage', 'params': { 'message': 'Pyright language server 1.1.396 starting'}}
# {'method': 'window/logMessage', 'params': { 'message': 'Server root directory: file:...'}}
self._read_messages(2)
# Send an "initialize" message
self._send_message(
"initialize",
{
"processId": os.getpid(),
"rootUri": Path("").absolute().as_uri(),
"capabilities": {
"textDocument": {
"hover": {
# Can also pass in "markdown" in this list as well as "plaintext"
# markdown is what vscode uses, but for testing purposes it's
# slightly easier to compare the plain text results
"contentFormat": ["plaintext"],
},
},
},
},
)
# Confirm with "initialized" notification
self._send_notification("initialized", {})
# Need to _send these notification as well
self._send_notification("workspace/didChangeConfiguration", {})
# Now we create a temp file which we will amend in each test and then
# call the language server to get completions. For reasons I can't quite
# figure out, the initial content needs to have a second, non-empty line
# otherwise some of the tests fail
self.open_doc(temp_file_path, "Line 1\nLine 2")
# Server now emits a number of "window/logMessage" messages (was 6 prior to
# pyright v1.1.393, but is now 7), finishing with a
# "textDocument/publishDiagnostics" message. So we read the messages until
# we get to that one.
self._read_until_specific_method("textDocument/publishDiagnostics")
# The server is now ready for completion and hover requests
def _next_id(self):
self._message_id += 1
return self._message_id
def get_completion_results_from_file(self, line, cursor_position):
"""
For a given line and cursor_position returns the list of potential
completion results. This assumes that the file is already loaded by
the language server (via `open_doc`). If you want to test a single line
of code, then use the `get_completion_results()` method instead
"""
completion_response = self._get_completion(line, cursor_position)
results = completion_response.get("result")
items = results.get("items")
return items
def get_completion_results(
self, text_for_completion, cursor_position=None
): # pragma: no cover
"""
For a given string of text provide the list of potential completion
results. If cursor_position is omitted, then it looks for completion
at the end of the text provided.
To use, you should provide the entire file contents up to the point
that you want to check autocomplete. It should all be on a single
line, with ';' separators.
Returns a list of completion items which look like this:
{ "label": str, "kind": CompletionKind, "sortText": str}
"""
self._notify_document_change(0, text_for_completion)
if cursor_position is None:
cursor_position = len(text_for_completion)
return self.get_completion_results_from_file(0, cursor_position)
def get_element_type_from_file(self, line, cursor_position):
"""
For a given line and cursor_position returns the type of the currently
hovered piece of text. This assumes that the file is already loaded by
the language server (via `open_doc`). If you want to test a single line
of code, then use the `get_element_type()` method instead
"""
hover_response = self._get_hover_text(line, cursor_position)
value = hover_response.get("result").get("contents").get("value")
first_line = value.split("\n\n")[0]
# First line contains the signature like `(variable) name: type`
variable_signature = re.search(
"^\\((?:variable|property)\\) (?P<var_name>[^:]+): (?P<type>.+)",
first_line,
)
# First line contains the signature like `(method) def method_name() -> type`
method_signature = re.search(
"^\\(method\\) def (?P<method_name>[^(]+)\\([^()]*\\) -> (?P<type>.+)",
first_line,
)
if variable_signature:
thing_type = variable_signature.group("type")
elif method_signature:
thing_type = method_signature.group("type")
else: # pragma: no cover
assert 0, (
f"The type signature `{value}` could not be parsed by self._language_server.py."
)
return thing_type
def get_element_type(self, text, cursor_position=None): # pragma: no cover
"""
For a given string of text provide the inferred type of the item at the
current cursor_position. If cursor_position is omitted, it assumes the
thing to check is the last thing typed and so looks at the cursor position
just before the end of the string.
To use, you should provide the entire file contents up to the point
that you want to get the type. It should all be on a single
line, with ';' separators.
"""
self._notify_document_change(0, f"{text}\n")
if cursor_position is None:
cursor_position = len(text) - 1
return self.get_element_type_from_file(0, cursor_position)
def _notify_document_change(self, line_number, new_text): # pragma: no cover
# Need to update text_document version
self._text_document["version"] = f"v{self._next_id()}"
self._send_notification(
"textDocument/didChange",
{
"textDocument": self._text_document,
"contentChanges": [
{
"range": {
"start": {"line": line_number, "character": 0},
"end": {
"line": line_number,
"character": len(new_text),
},
},
"text": new_text,
}
],
},
)
# This notification causes a response to be sent, so we
# need to read it to clear it from stdout
self._read_message()
def _get_completion(self, line_number, character):
"""
Get the list of completion objects for a given position
"""
return self._send_message(
"textDocument/completion",
{
"textDocument": self._text_document,
"position": {"line": line_number, "character": character},
},
)
def _get_hover_text(self, line_number, character):
"""
Get the inferred type
"""
return self._send_message(
"textDocument/hover",
{
"textDocument": self._text_document,
"position": {"line": line_number, "character": character},
},
)
def _read_message(self):
"""
Read a message from the language server.
Message format is a header like "Content-Length: xxx", followed by
\r\n\r\n then the message in JSON RPC.
"""
line = self._language_server.stdout.readline().decode("utf-8").strip()
while not line.startswith("Content-Length:"): # pragma: no cover
line = self._language_server.stdout.readline().decode("utf-8").strip()
content_length = int(line.split(":")[1].strip())
content = self._language_server.stdout.read(content_length + 2).decode("utf-8")
return json.loads(content)
def _read_messages(self, number_of_messages=1):
"""Read multiple messages from the language server"""
messages = []
while number_of_messages > 0:
messages.append(self._read_message())
number_of_messages -= 1
return messages
def _read_until_specific_method(self, method):
"""Reads messages from the server until we get the one we're looking for"""
messages = [self._read_message()]
while messages[-1]["method"] != method:
messages.append(self._read_message())
return messages
def _send(self, message):
content = json.dumps(message)
message_str = f"Content-Length: {str(len(content))}\r\n\r\n{content}"
self._language_server.stdin.write(message_str.encode())
self._language_server.stdin.flush()
def _send_notification(self, method, params):
"""Send a notification to the language server - there is no response."""
notification = {
"jsonrpc": "2.0",
"method": method,
"params": params,
}
self._send(notification)
def _send_message(self, method, params):
"""Send a message to the language server and return the response."""
message = {
"jsonrpc": "2.0",
"id": self._next_id(),
"method": method,
"params": params,
}
self._send(message)
return self._read_message()
def open_doc(self, temp_file_path, content):
"""
Tell the language server about a file we have "opened" so that
it can parse it to make the autocomplete responses faster
"""
temp_file_path.write_text(content, encoding="utf-8")
temp_file_uri = temp_file_path.absolute().as_uri()
self._text_document = {
"uri": temp_file_uri,
"languageId": "python",
"version": 1,
"text": content,
}
self._send_notification(
"textDocument/didOpen",
{"textDocument": self._text_document},
)
self._read_message()