#!/usr/bin/env python3 """Exercise EditorDiagnostics module scan and artifact preparation with real GCC.""" 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) 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 class Session: def __init__(self, argv, cwd, stderr): self.process = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, env={**os.environ, "LC_ALL": "C"}) self.sequence = 0 self.buffer = b"" def send(self, message): self.process.stdin.write(frame(message)) self.process.stdin.flush() def notify(self, method, params): self.send({"method": method, "params": params}) def request(self, method, params, timeout=180): self.sequence += 1 self.send({"id": self.sequence, "method": method, "params": params}) deadline = time.monotonic() + timeout while True: message = self.read(deadline - time.monotonic()) if message.get("id") == self.sequence: return message def read(self, timeout): check(timeout > 0, "LSP response deadline expired") while b"\r\n\r\n" not in self.buffer: ready, _, _ = select.select([self.process.stdout], [], [], timeout) check(ready, "LSP response deadline expired") chunk = os.read(self.process.stdout.fileno(), 65536) check(chunk, "the server 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 LSP response") rest += chunk body, self.buffer = rest[:length], rest[length:] return json.loads(body) def close(self): try: self.request("shutdown", None, timeout=30) self.notify("exit", None) 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 await_field(session, uri, field, predicate, timeout=180): deadline = time.monotonic() + timeout last = None result = None while time.monotonic() < deadline: reply = session.request("voidLanguageServer/analysisStatus", {"textDocument": {"uri": uri}}, timeout=30) result = reply.get("result") or {} last = result.get(field) if last and predicate(last): return last if last and last.get("state") in ("failed", "unavailable", "cancelled"): raise ValueError(f"{field} did not complete: {last} status={result}") time.sleep(0.2) raise ValueError(f"{field} did not finish: {last} status={result}") def run(server, profile, compiler, observer): with tempfile.TemporaryDirectory(prefix="vls-editor-modules-") as temp: root = Path(temp) source = root / "editor.cmi.cpp" source.write_text("export module editor.cmi;\n" "export int twice(int value) { return value * 2; }\n", encoding="utf-8") object_path = root / "editor.cmi.o" database = root / "compile_commands.json" database.write_text(json.dumps([{ "directory": str(root), "file": str(source), "arguments": [str(compiler), "-std=c++26", "-fmodules-ts", "-c", str(source), "-o", str(object_path)]}])) uri = source.as_uri() text = source.read_text(encoding="utf-8") with tempfile.TemporaryFile() as errors: session = Session([str(server), "--stdio", "--workspace-root", str(root), "--provider", "compdb", "--compdb", str(database), "--gcc-profile", str(profile)], root, errors) try: initialized = session.request("initialize", { "processId": None, "capabilities": {}, "workspaceFolders": [{"uri": root.as_uri(), "name": root.name}]}) check(initialized["result"]["capabilities"].get("hoverProvider"), "observer capabilities are not advertised") session.notify("initialized", {}) session.notify("textDocument/didOpen", {"textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": text}}) scan = await_field(session, uri, "moduleScan", lambda value: value.get("state") in ("ready", "partial")) check("editor.cmi" in scan.get("provides", []), f"wrong scan: {scan}") artifact = await_field(session, uri, "moduleArtifact", lambda value: value.get("state") == "ready") check(len(artifact.get("generation", "")) == 64, f"no published artifact generation: {artifact}") finally: session.close() errors.seek(0) diagnostics = errors.read() check(b"fatal" not in diagnostics.lower(), diagnostics[-800:]) print(f"editor modules: scan provided editor.cmi, artifact generation " f"{artifact['generation'][:16]}...") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--server", required=True, type=Path) parser.add_argument("--gcc-profile", required=True, type=Path) parser.add_argument("--cxx", default="g++") parser.add_argument("--observer", type=Path, help="assert this observer is selected by the profile") options = parser.parse_args() compiler = Path(shutil_which(options.cxx)) run(options.server.resolve(strict=True), options.gcc_profile.resolve(strict=True), compiler.resolve(strict=True), options.observer) def shutil_which(name): from shutil import which selected = which(name) check(selected, f"{name} was not found") return selected if __name__ == "__main__": try: main() except (OSError, ValueError, subprocess.SubprocessError) as exc: raise SystemExit(f"verify-editor-modules: {exc}")