# Author: Guoliang Chen, a Senior Digital Design Engineer """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: answered in ms` lines can be read beside the wire. - **`workspace/applyEdit` is captured, timed and declined.** A command-bearing offer (extract, inline) does not answer with its edit: it pushes one at a client that said `workspace.applyEdit`. `Session(apply_edit=True)` says so, records the payload and the instant it arrived — that instant is the end of the server's edit computation — and answers `applied: false` with a capture reason, so the corpus is never written. See `schema.CAPTURE_REASON`. 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 import schema # 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, apply_edit=False, create_files=False, ): 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.apply_edit = apply_edit self.create_files = create_files 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.server_requests = [] # every server->client request, answered self.applied = [] # captured workspace/applyEdit pushes, in order self.pending = {} # id -> (method, sent_at) for in-flight requests #: The `perf_counter` instant each indexing bar came *down*, stamped by #: the reader thread where the bytes land. One entry per scan: the #: server puts one bar up per scan and takes it down when that scan #: lands (`server/progress.rs`), and a mid-scan publish sends no `end`. #: A probe reads `scan_completed_at` — the first of them — and checks #: this list's length to prove that first `end` was the scan's. self.progress_ends = [] #: When the session's **scan** finished, independent of anything the #: client sent. Review finding F3: a request window's own chatter is #: not a scan event, so the settle instant is taken from the server's #: own end-of-scan message and never from "the last thing we heard". self.scan_completed_at = None #: id -> the `perf_counter` instant the reader thread parsed the #: response. Stamped where the bytes land rather than where a caller #: gets round to looking, so a probe holding many requests in flight #: at once measures each one's own wait and not its own poll interval #: (`phases_r4.py`). Entries are consumed by [`Session.poll_answers`]; #: `await_id` neither reads nor needs them. self._arrived = {} 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: if "method" not in message and message.get("id") is not None: self._arrived[message["id"]] = time.perf_counter() 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/applyEdit": self._capture_apply_edit(message) return 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}) def _capture_apply_edit(self, message): """Record a pushed edit, then decline it. Nothing is ever written. `arrived` is the end of the server's edit computation and `replied` is when this client let it go on, so a phase can report the two halves of an `executeCommand` separately. The answer is `applied: false` with `schema.CAPTURE_REASON`: an intentional benchmark refusal, recorded as status `capture`, never confused with an engine refusal. """ arrived = time.perf_counter() params = message.get("params") or {} self._write({ "jsonrpc": "2.0", "id": message["id"], "result": {"applied": False, "failureReason": schema.CAPTURE_REASON}, }) replied = time.perf_counter() with self._cond: self.applied.append({ "arrived": arrived, "replied": replied, "label": params.get("label"), "edit": params.get("edit") or {}, }) self._cond.notify_all() def take_applied(self): """Consume and return the `workspace/applyEdit` pushes captured.""" with self._cond: found, self.applied = self.applied, [] return found # -- 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._arrived.pop(rid, None) 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] def poll_answers(self): """Take every response that has arrived, without waiting for any. The pipelining half of [`Session.await_id`]: a probe that sends on a clock rather than after the previous answer holds many requests in flight at once and must not block on the oldest of them. Each entry is `(rid, method, elapsed_ms, arrived)` plus the message, with `elapsed` measured from the write to the instant the **reader thread** parsed the response, so the caller's poll interval is not in the number. """ out = [] with self._cond: kept = [] for message in self._inbox: rid = message.get("id") if "method" in message or rid not in self.pending: kept.append(message) continue method, sent = self.pending.pop(rid) arrived = self._arrived.pop(rid, None) or time.perf_counter() out.append((rid, method, (arrived - sent) * 1000.0, arrived, message)) self._inbox[:] = kept self._drain_locked() return out # -- 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" in message: # A server->client request, already answered from the reader # thread. Logged and dropped so the inbox cannot grow without # bound across a long session. self.server_requests.append(message["method"]) elif "method" in message and "id" not in message: self.notifications.append(message) if message["method"] == "$/progress": params = message.get("params") or {} value = params.get("value") or {} if value.get("kind") == "end": self.progress_ends.append(time.perf_counter()) if self.scan_completed_at is None: self.scan_completed_at = self.progress_ends[-1] elif message["method"] == "window/logMessage": text = message.get("params", {}).get("message", "") self.log_messages.append(text) # The `--verbose` line the bar's own `end` is followed by — # the fallback for a client that showed no bar at all. if text.startswith("timing: scan finished:") and self.scan_completed_at is None: self.scan_completed_at = time.perf_counter() 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"]} # `resourceOperations: ["create"]` with `documentChanges` is what the # server reads as "this client can be given a new file", which is what # decides whether an extraction puts the new module in a file of its # own or beside the old one (`extract.rs::execute`). workspace_edit = {"documentChanges": True} if self.create_files: workspace_edit["resourceOperations"] = ["create", "rename", "delete"] workspace = { "configuration": True, "workspaceEdit": workspace_edit, "symbol": {"dynamicRegistration": False}, "didChangeConfiguration": {"dynamicRegistration": False}, } if self.apply_edit: workspace["applyEdit"] = True return { "workspace": workspace, "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 client_shape(self): """The capability shape this session asked with, for the record. The same cursor answers differently to each shape: a resolving client gets a lazy offer, a client that cannot be pushed an edit gets a command's edit as the result instead. """ return { "resolveSupport": self.resolve_support, "applyEdit": self.apply_edit, "createFiles": self.create_files, } 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:]) # Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com