395 lines
14 KiB
Python
395 lines
14 KiB
Python
"""A minimal LSP client for the lucisv performance rounds.
|
|
|
|
Framed JSON-RPC over a `lucisv-server` child process's stdio. Python 3
|
|
standard library only, no third-party packages, so it runs from a clean
|
|
checkout with nothing installed.
|
|
|
|
What it does that a generic client does not, and why each exists:
|
|
|
|
- **The configuration pull is answered per session.** `lucisv-server` pulls
|
|
`workspace/configuration` for the `lucisv` section; the index scope it gets
|
|
back decides how many files are scanned, which is the single biggest lever
|
|
on every number in a perf round. `Session(scope=...)` writes that reply.
|
|
- **Client capabilities are settable per session.** A session that advertises
|
|
`textDocument.codeAction.resolveSupport.properties: ["edit"]` gets the lazy
|
|
`codeAction` offer (TODO §37.1); one that does not gets the eager shape.
|
|
Both must be measurable from one harness.
|
|
- **`storagePath` is always ours.** The index cache is directed at a scratch
|
|
directory so cache warmth is controlled (delete it = cold) and so nothing
|
|
is ever written near the corpus.
|
|
- **`window/logMessage` is captured**, so a `--verbose` server's own
|
|
`timing: <method> answered in <n> ms` lines can be read beside the wire.
|
|
|
|
Everything is timed with `time.perf_counter` from just before the write to
|
|
just after the matching response is parsed: what an editor experiences.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
|
|
# The server's own timing line, from `--verbose` (docs/features/verbose-timing).
|
|
TIMING_LINE = re.compile(r"timing: (\S+) answered in ([0-9.]+) ?ms")
|
|
|
|
|
|
def uri(path):
|
|
"""A `file://` URI for an absolute path, percent-encoding what LSP needs."""
|
|
from urllib.parse import quote
|
|
|
|
return "file://" + quote(os.path.abspath(path))
|
|
|
|
|
|
class Session:
|
|
"""One `lucisv-server` process, driven over stdio.
|
|
|
|
Use as a context manager; the process is shut down and reaped on exit.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
server,
|
|
root,
|
|
storage,
|
|
scope=None,
|
|
resolve_support=True,
|
|
verbose=False,
|
|
cold=False,
|
|
guard=None,
|
|
):
|
|
self.server = server
|
|
self.root = os.path.abspath(root)
|
|
self.storage = os.path.abspath(storage)
|
|
self.scope = scope if scope is not None else {}
|
|
self.resolve_support = resolve_support
|
|
self.verbose = verbose
|
|
self.next_id = 1
|
|
self.notifications = [] # every server->client notification, in order
|
|
self.log_messages = [] # window/logMessage texts only
|
|
self.timings = [] # (method, ms) from a --verbose server
|
|
self.pending = {} # id -> (method, sent_at) for in-flight requests
|
|
self.proc = None
|
|
self._reader = None
|
|
self._lock = threading.Lock()
|
|
self._inbox = [] # parsed messages not yet consumed
|
|
self._cond = threading.Condition(self._lock)
|
|
self._cold = cold
|
|
self._guard = guard or []
|
|
|
|
# -- lifecycle ---------------------------------------------------------
|
|
|
|
def __enter__(self):
|
|
if self._cold:
|
|
shutil.rmtree(self.storage, ignore_errors=True)
|
|
os.makedirs(self.storage, exist_ok=True)
|
|
cmd = list(self._guard) + [self.server]
|
|
if self.verbose:
|
|
cmd.append("--verbose")
|
|
cmd.append("--stdio")
|
|
self.proc = subprocess.Popen(
|
|
cmd,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
self._reader = threading.Thread(target=self._read_loop, daemon=True)
|
|
self._reader.start()
|
|
return self
|
|
|
|
def __exit__(self, *_):
|
|
self.close()
|
|
return False
|
|
|
|
def close(self):
|
|
if self.proc is None:
|
|
return
|
|
try:
|
|
self.notify("exit", None)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.proc.stdin.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.proc.wait(timeout=10)
|
|
except Exception:
|
|
self.proc.kill()
|
|
self.proc.wait()
|
|
self.proc = None
|
|
|
|
# -- framing -----------------------------------------------------------
|
|
|
|
def _write(self, message):
|
|
body = json.dumps(message).encode("utf-8")
|
|
header = ("Content-Length: %d\r\n\r\n" % len(body)).encode("ascii")
|
|
self.proc.stdin.write(header + body)
|
|
self.proc.stdin.flush()
|
|
|
|
def _read_loop(self):
|
|
stream = self.proc.stdout
|
|
while True:
|
|
length = None
|
|
while True:
|
|
line = stream.readline()
|
|
if not line:
|
|
return
|
|
line = line.decode("utf-8", "replace").strip()
|
|
if line == "":
|
|
break
|
|
if line.lower().startswith("content-length:"):
|
|
length = int(line.split(":", 1)[1].strip())
|
|
if length is None:
|
|
continue
|
|
payload = b""
|
|
while len(payload) < length:
|
|
chunk = stream.read(length - len(payload))
|
|
if not chunk:
|
|
return
|
|
payload += chunk
|
|
try:
|
|
message = json.loads(payload.decode("utf-8"))
|
|
except ValueError:
|
|
continue
|
|
self._dispatch(message)
|
|
|
|
def _dispatch(self, message):
|
|
with self._cond:
|
|
self._inbox.append(message)
|
|
self._cond.notify_all()
|
|
# Server->client requests must be answered from the reader thread, or
|
|
# the server blocks and every timing after it is a lie.
|
|
if "method" in message and "id" in message:
|
|
self._answer_server_request(message)
|
|
|
|
def _answer_server_request(self, message):
|
|
method = message["method"]
|
|
if method == "workspace/configuration":
|
|
items = message.get("params", {}).get("items", [])
|
|
self._write(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": message["id"],
|
|
"result": [self.scope for _ in items] or [self.scope],
|
|
}
|
|
)
|
|
elif method in ("window/workDoneProgress/create", "client/registerCapability"):
|
|
self._write({"jsonrpc": "2.0", "id": message["id"], "result": None})
|
|
else:
|
|
self._write({"jsonrpc": "2.0", "id": message["id"], "result": None})
|
|
|
|
# -- traffic -----------------------------------------------------------
|
|
|
|
def notify(self, method, params):
|
|
self._write({"jsonrpc": "2.0", "method": method, "params": params})
|
|
|
|
def send(self, method, params):
|
|
"""Send a request without waiting; returns its id (for pipelining)."""
|
|
rid = self.next_id
|
|
self.next_id += 1
|
|
self.pending[rid] = (method, time.perf_counter())
|
|
self._write({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
|
return rid
|
|
|
|
def await_id(self, rid, timeout=300.0):
|
|
"""Wait for the response to `rid`; returns (elapsed_ms, message)."""
|
|
deadline = time.time() + timeout
|
|
while True:
|
|
with self._cond:
|
|
for i, message in enumerate(self._inbox):
|
|
if message.get("id") == rid and "method" not in message:
|
|
self._inbox.pop(i)
|
|
done = time.perf_counter()
|
|
_, sent = self.pending.pop(rid)
|
|
self._drain_locked()
|
|
return (done - sent) * 1000.0, message
|
|
self._drain_locked()
|
|
remaining = deadline - time.time()
|
|
if remaining <= 0:
|
|
raise TimeoutError("no response to request %d" % rid)
|
|
self._cond.wait(min(remaining, 0.05))
|
|
|
|
def request(self, method, params, timeout=300.0):
|
|
"""Send and wait. Returns (elapsed_ms, result_or_error_message)."""
|
|
return self.await_id(self.send(method, params), timeout)
|
|
|
|
def ms(self, method, params, timeout=300.0):
|
|
"""Just the round trip in milliseconds."""
|
|
return self.request(method, params, timeout)[0]
|
|
|
|
# -- notification bookkeeping -----------------------------------------
|
|
|
|
def _drain_locked(self):
|
|
"""Move server notifications out of the inbox into the log."""
|
|
kept = []
|
|
for message in self._inbox:
|
|
if "method" in message and "id" not in message:
|
|
self.notifications.append(message)
|
|
if message["method"] == "window/logMessage":
|
|
text = message.get("params", {}).get("message", "")
|
|
self.log_messages.append(text)
|
|
found = TIMING_LINE.search(text)
|
|
if found:
|
|
self.timings.append((found.group(1), float(found.group(2))))
|
|
else:
|
|
kept.append(message)
|
|
self._inbox[:] = kept
|
|
|
|
def drain(self):
|
|
with self._cond:
|
|
self._drain_locked()
|
|
|
|
def wait_quiet(self, quiet=1.5, timeout=300.0):
|
|
"""Block until no notification has arrived for `quiet` seconds.
|
|
|
|
The scan's end is not one message: `$/progress` `end` can be followed
|
|
by more indexing chatter, so silence is the reliable barrier. Returns
|
|
the seconds from entry to the last notification seen.
|
|
"""
|
|
started = time.perf_counter()
|
|
last = time.perf_counter()
|
|
seen = len(self.notifications)
|
|
deadline = time.time() + timeout
|
|
while True:
|
|
self.drain()
|
|
if len(self.notifications) != seen:
|
|
seen = len(self.notifications)
|
|
last = time.perf_counter()
|
|
if time.perf_counter() - last >= quiet:
|
|
return (last - started) * 1000.0
|
|
if time.time() > deadline:
|
|
raise TimeoutError("server never went quiet")
|
|
time.sleep(0.005)
|
|
|
|
def take_notifications(self, method=None):
|
|
"""Consume and return the notifications logged so far."""
|
|
self.drain()
|
|
found = [n for n in self.notifications if method is None or n["method"] == method]
|
|
self.notifications = []
|
|
return found
|
|
|
|
def take_timings(self, method=None):
|
|
self.drain()
|
|
found = [t for t in self.timings if method is None or t[0] == method]
|
|
self.timings = []
|
|
return found
|
|
|
|
# -- protocol shortcuts ------------------------------------------------
|
|
|
|
def capabilities(self):
|
|
"""The client capabilities this session advertises."""
|
|
code_action = {
|
|
"codeActionLiteralSupport": {
|
|
"codeActionKind": {"valueSet": ["", "quickfix", "refactor", "source"]}
|
|
},
|
|
"dataSupport": True,
|
|
}
|
|
if self.resolve_support:
|
|
code_action["resolveSupport"] = {"properties": ["edit"]}
|
|
return {
|
|
"workspace": {
|
|
"configuration": True,
|
|
"workspaceEdit": {"documentChanges": True},
|
|
"symbol": {"dynamicRegistration": False},
|
|
"didChangeConfiguration": {"dynamicRegistration": False},
|
|
},
|
|
"textDocument": {
|
|
"synchronization": {"dynamicRegistration": False},
|
|
"codeAction": code_action,
|
|
"completion": {"completionItem": {"snippetSupport": True}},
|
|
"hover": {"contentFormat": ["markdown", "plaintext"]},
|
|
"rename": {"prepareSupport": True},
|
|
"publishDiagnostics": {"relatedInformation": True},
|
|
"semanticTokens": {
|
|
"requests": {"full": True},
|
|
"tokenTypes": [],
|
|
"tokenModifiers": [],
|
|
"formats": ["relative"],
|
|
},
|
|
"inlayHint": {"dynamicRegistration": False},
|
|
},
|
|
"window": {"workDoneProgress": True},
|
|
}
|
|
|
|
def initialize(self):
|
|
"""`initialize` + `initialized`; returns the request's milliseconds."""
|
|
params = {
|
|
"processId": os.getpid(),
|
|
"rootUri": uri(self.root),
|
|
"capabilities": self.capabilities(),
|
|
"initializationOptions": {"storagePath": self.storage},
|
|
"workspaceFolders": [{"uri": uri(self.root), "name": "opentitan"}],
|
|
}
|
|
elapsed, _ = self.request("initialize", params)
|
|
self.notify("initialized", {})
|
|
return elapsed
|
|
|
|
def did_open(self, path, language="systemverilog"):
|
|
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
text = handle.read()
|
|
self.notify(
|
|
"textDocument/didOpen",
|
|
{
|
|
"textDocument": {
|
|
"uri": uri(path),
|
|
"languageId": language,
|
|
"version": 1,
|
|
"text": text,
|
|
}
|
|
},
|
|
)
|
|
return text
|
|
|
|
def did_change(self, path, text, version=2):
|
|
self.notify(
|
|
"textDocument/didChange",
|
|
{
|
|
"textDocument": {"uri": uri(path), "version": version},
|
|
"contentChanges": [{"text": text}],
|
|
},
|
|
)
|
|
|
|
def at(self, path, line, character, method, extra=None):
|
|
"""A position request's params, 0-based line and UTF-16 character."""
|
|
params = {
|
|
"textDocument": {"uri": uri(path)},
|
|
"position": {"line": line, "character": character},
|
|
}
|
|
if extra:
|
|
params.update(extra)
|
|
return method, params
|
|
|
|
|
|
def find_position(path, needle, occurrence=1, offset=0):
|
|
"""0-based (line, character) of the `occurrence`th `needle` in a file.
|
|
|
|
Positions are resolved from the text at run time rather than hard-coded,
|
|
so a corpus that moves by a line does not silently measure the wrong
|
|
token. `offset` shifts the character within the match.
|
|
"""
|
|
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
seen = 0
|
|
for number, line in enumerate(handle):
|
|
start = 0
|
|
while True:
|
|
found = line.find(needle, start)
|
|
if found < 0:
|
|
break
|
|
seen += 1
|
|
if seen == occurrence:
|
|
return number, found + offset
|
|
start = found + 1
|
|
raise LookupError("%r not found %dx in %s" % (needle, occurrence, path))
|
|
|
|
|
|
def summarize(values):
|
|
"""(first, min_of_repeats, max_of_repeats) from a try list."""
|
|
if not values:
|
|
return None, None, None
|
|
if len(values) == 1:
|
|
return values[0], values[0], values[0]
|
|
return values[0], min(values[1:]), max(values[1:])
|