"""Run a staged VLS from an empty directory without a tool search path.""" import argparse import json from pathlib import Path import subprocess import tempfile def frame(message): payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode() return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload def replies(data): result = [] while data: header, data = data.split(b"\r\n\r\n", 1) if not header.startswith(b"Content-Length: "): raise ValueError(f"unexpected stdout header {header!r}") length = int(header.removeprefix(b"Content-Length: ")) if not 0 < length <= len(data): raise ValueError("truncated LSP response") result.append(json.loads(data[:length])) data = data[length:] return result def check_install(binary, work, encoding): def start(args, data=b""): return subprocess.run([binary, *args], cwd=work, input=data, capture_output=True, check=True, timeout=10, env={"LC_ALL": "C", "PATH": ""}) version = start(["--version"]) if version.stdout != b"VoidLanguageServer 0.1.0\n" or version.stderr: raise ValueError("unexpected version output") document = {"uri": "untitled:installed-server"} def edit(version, left, right, text): return {"method": "textDocument/didChange", "params": { "textDocument": {**document, "version": version}, "contentChanges": [{ "range": {"start": {"line": 0, "character": left}, "end": {"line": 0, "character": right}}, "text": text}]}} messages = [ {"method": "initialize", "id": 1, "params": {"capabilities": { "general": {"positionEncodings": [encoding]}}}}, {"method": "initialized", "params": {}}, {"method": "textDocument/didOpen", "params": {"textDocument": { **document, "version": 1, "languageId": "cpp", "text": "a"}}}, edit(2, 0, 1, "😀"), edit(3, 1, 1, "b"), {"method": "textDocument/didClose", "params": {"textDocument": document}}, {"method": "shutdown", "id": 2}, {"method": "exit"}, ] process = start(["--stdio"], b"".join(map(frame, messages))) responses = replies(process.stdout) if [r["id"] for r in responses] != [1, 2] or responses[1]["result"] is not None: raise ValueError(f"unexpected replies: {responses}") capabilities = responses[0]["result"]["capabilities"] if capabilities["positionEncoding"] != encoding or capabilities["textDocumentSync"]["change"] != 2: raise ValueError(f"unexpected initialization: {capabilities}") witness = "splits a Unicode scalar" if encoding == "utf-8" else "splits a surrogate pair" if process.stderr.count(b"\n") != 1 or witness.encode() not in process.stderr: raise ValueError(f"edit did not observe the preceding replacement: {process.stderr!r}") print(f"{encoding}: installed binary negotiated sync, applied the edit and detected the split") def check_provider(binary, work, root, database, provider, document): rows = json.loads(database.read_bytes()) owners = sum((database.parent / row["directory"] / row["file"]).resolve() == document for row in rows) if not owners: raise ValueError(f"{database} has no command for {document}") args = [str(binary), "--stdio"] if provider == "compdb": args += ["--workspace-root", str(root), "--provider", "compdb", "--compdb", str(database)] messages = [ {"method": "initialize", "id": 1, "params": {"capabilities": {}, "workspaceFolders": [ {"uri": root.as_uri(), "name": root.name}]}}, {"method": "initialized", "params": {}}, {"method": "voidLanguageServer/providerStatus", "id": 2, "params": { "workspaceUri": root.as_uri(), "textDocument": {"uri": document.as_uri()}}}, {"method": "shutdown", "id": 3}, {"method": "exit"}, ] process = subprocess.run(args, cwd=work, input=b"".join(map(frame, messages)), capture_output=True, check=True, timeout=15, env={"LC_ALL": "C", "PATH": ""}) records = replies(process.stdout) if process.stderr or [r["id"] for r in records] != [1, 2, 3]: raise ValueError(f"unexpected provider transcript: {process.stderr!r}, {records!r}") status = records[1]["result"] if (status["provider"], status["state"], status["workspaceUri"]) != (provider, "ready", root.as_uri()): raise ValueError(f"provider not ready: {status!r}") if (status["contextCount"] != len(rows) or len(status["alternatives"]) != min(owners, 16) or status.get("alternativesTruncated", False) != (owners > 16) or status["selected"]["owningTu"] != document.as_uri()): raise ValueError(f"provider disagrees with {database}: {status!r}") if provider == "vbs" and status["nativeGeneration"] != database.parent.name: raise ValueError(f"selected VBS generation changed: {status!r}") print(f"{provider}: installed server reported {len(rows)} commands for {root.name}, {owners} for {document.name}") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("executable", type=Path) parser.add_argument("--workspace", type=Path, help="workspace used to build the installed server") parser.add_argument("--vbs-database", type=Path, help="expected selected immutable VBS generation database") parser.add_argument("--compdb", type=Path, help="comparison build's compilation database") parser.add_argument("--document", type=Path, default=Path("src/main.cpp"), help="translation unit under the workspace") args = parser.parse_args() if any((args.workspace, args.vbs_database, args.compdb)) and not all((args.workspace, args.vbs_database, args.compdb)): parser.error("--workspace, --vbs-database and --compdb must be supplied together") binary = args.executable.resolve(strict=True) with tempfile.TemporaryDirectory(prefix="vls-install-check-") as work: for encoding in ("utf-8", "utf-16"): check_install(binary, work, encoding) if args.workspace: root = args.workspace.resolve(strict=True) document = (root / args.document).resolve(strict=True) for provider, db in (("vbs", args.vbs_database), ("compdb", args.compdb)): check_provider(binary, work, root, db.resolve(strict=True), provider, document)