forked from mikeoz32/cr-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
243 lines (204 loc) · 7.23 KB
/
Copy pathmain.py
File metadata and controls
243 lines (204 loc) · 7.23 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
import asyncio
import tempfile
from pathlib import Path
from lsprotocol import types
from pygls.lsp.client import LanguageClient
SAMPLE_CODE = """\
class Greeter
def greet
end
def grab
end
end
class Box
def initialize
@bar = 1
@baz = 2
end
def value
@ba
end
end
def call
greeter = Greeter.new
greeter.gr
end
def keyword_demo
ret
end
require \"foo/ba\"
"""
REQUEST_TIMEOUT = 10.0
INIT_TIMEOUT = 60.0
def log(message: str) -> None:
print(message, flush=True)
def position_for(text: str, needle: str, offset: int = 0, occurrence: int = 0) -> types.Position:
idx = -1
for _ in range(occurrence + 1):
idx = text.index(needle, idx + 1)
idx += offset
line = text.count("\n", 0, idx)
last_nl = text.rfind("\n", 0, idx)
col = idx - (last_nl + 1 if last_nl != -1 else 0)
return types.Position(line=line, character=col)
async def stop_client(client: LanguageClient) -> None:
stop_event = getattr(client, "_stop_event", None)
if stop_event:
stop_event.set()
server_proc = getattr(client, "_server", None)
if server_proc:
stdin = getattr(server_proc, "stdin", None)
if stdin:
stdin.close()
try:
await stdin.wait_closed()
except Exception:
pass
if server_proc.returncode is None:
server_proc.terminate()
try:
await asyncio.wait_for(server_proc.wait(), timeout=2.0)
except asyncio.TimeoutError:
server_proc.kill()
await server_proc.wait()
async_tasks = getattr(client, "_async_tasks", [])
for task in async_tasks:
if not task.done():
task.cancel()
if async_tasks:
await asyncio.gather(*async_tasks, return_exceptions=True)
async def await_with_timeout(coro, label: str, timeout: float) -> types.CompletionList | types.InitializeResult:
try:
return await asyncio.wait_for(coro, timeout=timeout)
except asyncio.TimeoutError:
log(f"[timeout] {label} after {timeout}s")
raise
async def request_completion(
client: LanguageClient,
uri: str,
position: types.Position,
trigger_character: str | None = None,
) -> types.CompletionList:
if trigger_character:
context = types.CompletionContext(
trigger_kind=types.CompletionTriggerKind.TriggerCharacter,
trigger_character=trigger_character,
)
else:
context = types.CompletionContext(
trigger_kind=types.CompletionTriggerKind.Invoked,
)
params = types.CompletionParams(
text_document=types.TextDocumentIdentifier(uri=uri),
position=position,
context=context,
)
return await client.text_document_completion_async(params=params)
def print_result(title: str, items: list[types.CompletionItem], expected: list[str]) -> None:
labels = {item.label for item in items}
hits = [label for label in expected if label in labels]
misses = [label for label in expected if label not in labels]
log(f"{title}: {len(items)} items")
if hits:
log(" hits: " + ", ".join(hits))
if misses:
log(" missing: " + ", ".join(misses))
async def main() -> None:
client = LanguageClient("cr-analyzer", "v1")
log("starting server...")
await client.start_io(
"crystal",
"run",
"-Dpreview_mt",
"-Dexecution_context",
"src/bin/cra.cr",
)
log("server started")
async def _drain_stderr(server_proc: asyncio.subprocess.Process | None) -> None:
if server_proc is None or server_proc.stderr is None:
return
async for line in server_proc.stderr:
text = line.decode(errors="replace").rstrip()
if "ERROR" in text or "Error" in text or "error" in text:
log(f"[server stderr] {text}")
stderr_task = asyncio.create_task(_drain_stderr(client._server))
try:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / "src" / "foo").mkdir(parents=True, exist_ok=True)
(root / "src" / "foo" / "bar.cr").write_text("")
(root / "src" / "foo" / "baz.cr").write_text("")
sample_path = root / "sample.cr"
sample_path.write_text(SAMPLE_CODE)
log("initializing...")
await await_with_timeout(
client.initialize_async(
params=types.InitializeParams(
capabilities=types.ClientCapabilities(
workspace=types.WorkspaceClientCapabilities(apply_edit=True)
),
root_uri=root.as_uri(),
)
),
"initialize",
INIT_TIMEOUT,
)
client.initialized(types.InitializedParams())
log("initialized")
client.text_document_did_open(
types.DidOpenTextDocumentParams(
text_document=types.TextDocumentItem(
uri=sample_path.as_uri(),
language_id="crystal",
version=1,
text=SAMPLE_CODE,
)
)
)
log("didOpen sent")
await asyncio.sleep(0.2)
method_pos = position_for(SAMPLE_CODE, "greeter.gr", offset=len("greeter.gr"))
method_items = (
await await_with_timeout(
request_completion(client, sample_path.as_uri(), method_pos, "."),
"completion(method)",
REQUEST_TIMEOUT,
)
).items
print_result("method completion", method_items, ["greet", "grab"])
ivar_pos = position_for(SAMPLE_CODE, "@ba", offset=len("@ba"))
ivar_items = (
await await_with_timeout(
request_completion(client, sample_path.as_uri(), ivar_pos, "@"),
"completion(ivar)",
REQUEST_TIMEOUT,
)
).items
print_result("ivar completion", ivar_items, ["@bar", "@baz"])
keyword_pos = position_for(SAMPLE_CODE, "ret", offset=len("ret"))
keyword_items = (
await await_with_timeout(
request_completion(client, sample_path.as_uri(), keyword_pos),
"completion(keyword)",
REQUEST_TIMEOUT,
)
).items
print_result("keyword completion", keyword_items, ["return"])
require_pos = position_for(SAMPLE_CODE, "foo/ba", offset=len("foo/ba"))
require_items = (
await await_with_timeout(
request_completion(client, sample_path.as_uri(), require_pos),
"completion(require)",
REQUEST_TIMEOUT,
)
).items
print_result("require completion", require_items, ["foo/bar", "foo/baz"])
finally:
stderr_task.cancel()
try:
await stderr_task
except asyncio.CancelledError:
pass
await stop_client(client)
if __name__ == "__main__":
asyncio.run(main())