#!/usr/bin/env python3 """Drive vls-dap --live against the scripted worker: control, inspection, stale rejects.""" import argparse import json import os from pathlib import Path import select import subprocess import tempfile import time def check(condition, detail): if not condition: raise ValueError(detail) class Adapter: def __init__(self, argv): self.process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, "LC_ALL": "C"}) self.sequence = 0 self.buffer = b"" def send(self, message): payload = json.dumps(message).encode() self.process.stdin.write(f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload) self.process.stdin.flush() def send_request(self, command, arguments=None): self.sequence += 1 self.send({"seq": self.sequence, "type": "request", "command": command, "arguments": arguments or {}}) return self.sequence def request(self, command, arguments=None, timeout=15): sequence = self.send_request(command, arguments) while True: message = self.read(timeout) if message.get("type") == "response" and message.get("request_seq") == sequence: return message def event(self, name, timeout=15): deadline = time.monotonic() + timeout while True: remaining = deadline - time.monotonic() check(remaining > 0, f"timed out waiting for the {name} event") message = self.read(remaining) if message.get("type") == "event" and message.get("event") == name: return message def read(self, timeout): while b"\r\n\r\n" not in self.buffer: ready, _, _ = select.select([self.process.stdout], [], [], timeout) check(ready, "DAP response deadline expired") chunk = os.read(self.process.stdout.fileno(), 65536) check(chunk, "the adapter closed stdout") self.buffer += chunk header, rest = self.buffer.split(b"\r\n\r\n", 1) length = int(header.removeprefix(b"Content-Length: ")) while len(rest) < length: chunk = os.read(self.process.stdout.fileno(), 65536) check(chunk, "truncated DAP response") rest += chunk body, self.buffer = rest[:length], rest[length:] return json.loads(body) def close(self): try: self.request("disconnect") except (OSError, ValueError, TimeoutError): pass try: self.process.stdin.close() except OSError: pass try: self.process.wait(timeout=10) except subprocess.TimeoutExpired: self.process.kill() self.process.wait() def run(adapter, worker): with tempfile.TemporaryDirectory(prefix="vls-live-dap-") as temp: root = Path(temp) source = root / "normal.cpp" source.write_text("int value = 17;\n", encoding="utf-8") trace = root / "session.vls" client = Adapter([str(adapter), "--live", str(worker), "/private/cc1plus", "a" * 64, str(source), str(trace)]) try: initialized = client.request("initialize", {"adapterID": "vls"}) check(initialized["success"], initialized) client.event("initialized") client.send_request("launch", {}) client.request("configurationDone", {}) stopped = client.event("stopped") check(stopped["body"]["threadId"] == 1, stopped) threads = client.request("threads") check(len(threads["body"]["threads"]) == 1, threads) stack = client.request("stackTrace", {"threadId": 1}) check("body" in stack, stack) frame = stack["body"]["stackFrames"][0] check(frame["name"] == "fixture_frame" and frame["line"] == 1, frame) scopes = client.request("scopes", {"frameId": frame["id"]}) reference = scopes["body"]["scopes"][0]["variablesReference"] variables = client.request("variables", {"variablesReference": reference}) names = {variable["name"]: variable["value"] for variable in variables["body"]["variables"]} check(names.get("source") == "input.cpp" and names.get("depth") == "0", f"unexpected live variables: {names}") check(names.get("Result") == "17", f"typed value was not projected: {names}") breakpoints = client.request("setBreakpoints", {"source": {"path": "input.cpp"}, "lines": [2, 99]}) check(breakpoints["success"] and len(breakpoints["body"]["breakpoints"]) == 2, breakpoints) moved = client.request("next") check(moved["success"], moved) stopped_event = client.event("stopped") check(stopped_event["body"].get("hitBreakpointIds") == [2], stopped_event) stale = client.request("scopes", {"frameId": frame["id"]}) check(stale["success"] is False and "stale" in stale["message"], stale) stack = client.request("stackTrace", {"threadId": 1}) check(stack["body"]["stackFrames"][0]["line"] == 2, stack) paused = client.request("pause") check(paused["success"] is False, paused) finished = client.request("continue") check(finished["success"], finished) client.event("terminated") finally: client.close() print("live DAP passed: stopped/typed inspection/breakpoints/step/stale rejection/continue, pause refused") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--adapter", required=True, type=Path) parser.add_argument("--worker", required=True, type=Path) options = parser.parse_args() run(options.adapter.resolve(strict=True), options.worker.resolve(strict=True)) if __name__ == "__main__": try: main() except (OSError, ValueError, subprocess.SubprocessError) as exc: raise SystemExit(f"verify-live-dap: {exc}")