Files
Language-Server/tests/corpus/frontend/verify-gcc-events.py
T
faumaray da8003f6d4 Implement the VLS roadmap on the native VBS build
Native VBS and CMake builds of the server and every registered suite:
protocol and document sync, VBS/compdb providers, stock GCC diagnostics
(including in-process default profile preparation), the stock occurrence
observer and hover/definition, the bounded Scheduler, C++ module graph,
scan and artifact cache with real CMI production, the context-aware
symbol index with schema-2 snapshot migration, navigation and guarded
rename, reflection provenance with splice-origin extraction, index-backed
completion and signature help, live GCC worker control with a registered
DAP suite, and the Neovim and VS Code clients.

VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced
from the versioned patches and verified stepping reflection/template code
with projected values 17/34 and 41/82.
2026-12-05 14:06:50 +03:00

551 lines
25 KiB
Python

#!/usr/bin/env python3
"""Exercise the private GCC evaluator on the real gcc-live.cpp translation unit."""
import argparse
from contextlib import ExitStack
import json
import os
from pathlib import Path
import re
import secrets
import select
import selectors
import signal
import subprocess
import sys
import tempfile
import time
BACKEND = "gcc-16.2.0/vls-eval-1"
KINDS = {"hello", "enter", "body", "cached", "value", "stopped", "resumed",
"leave", "terminal", "frontendEnd"}
TRACE_LIMIT = 1024 * 1024
FRAME_LIMIT = 64 * 1024
DEADLINE = 10
# Relocate both inherited endpoints before touching 3 or 4. exec preserves the
# PID; raw stdin/stdout and diagnostics are independent of the two probe pipes.
LAUNCH = """
import fcntl, os, sys
original = [int(fd) for fd in sys.argv[1:3]]
high = [fcntl.fcntl(fd, fcntl.F_DUPFD_CLOEXEC, 5) for fd in original]
for fd, target in zip(high, (3, 4)):
os.dup2(fd, target, inheritable=True)
for fd in original:
if fd > 4:
os.close(fd)
os.execv(sys.argv[3], sys.argv[3:])
"""
def check(condition, message):
if not condition:
raise AssertionError(message)
def unique_keys(pairs):
result = {}
for key, value in pairs:
check(key not in result, f"duplicate JSON key {key!r}")
result[key] = value
return result
def reject_number(value):
raise ValueError(f"non-JSON number {value}")
def integer(value):
check(set(value) == {"kind", "precision", "signed", "bitsHex"},
f"malformed integer {value}")
width, signed, bits = value["precision"], value["signed"], value["bitsHex"]
check(type(width) is int and 1 <= width <= 64 and type(signed) is bool,
f"invalid integer type {value}")
check(isinstance(bits, str) and len(bits) == (width + 3) // 4
and re.fullmatch("[0-9a-f]+", bits), f"invalid integer encoding {value}")
raw = int(bits, 16)
check(raw < 1 << width, f"excess bits {value}")
return raw - (1 << width) if signed and raw & (1 << (width - 1)) else raw
class Invocation:
"""Own and reap one private cc1plus process, with bounded multiplexed reads."""
def __init__(self, binary, source, flags, nonce=None, invalid_pipe=False):
self.nonce = nonce if nonce is not None else secrets.token_hex(16)
self.events = []
self.pending = bytearray()
self.trace_bytes = 0
self.outputs = {"stdout": bytearray(), "stderr": bytearray()}
self.mux = selectors.DefaultSelector()
self.deadline = time.monotonic() + DEADLINE
self.control = None
self.process = None
self.owned = ExitStack()
self.owned.callback(self.mux.close)
try:
with ExitStack() as child:
control_read, self.control = os.pipe()
child.callback(os.close, control_read)
self.owned.callback(self.close_control)
event_read, event_write = os.pipe()
self.owned.callback(os.close, event_read)
child.callback(os.close, event_write)
if invalid_pipe:
event_write = os.open(os.devnull, os.O_WRONLY)
child.callback(os.close, event_write)
args = [sys.executable, "-I", "-c", LAUNCH, str(control_read),
str(event_write), str(binary), "-quiet", "-std=c++26",
"-freflection", "-fsyntax-only", "-nostdinc", *flags,
source.name, "-o", os.devnull]
self.process = subprocess.Popen(
args, cwd=source.parent,
env={"LC_ALL": "C", "VLS_GCC_NONCE": self.nonce},
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
pass_fds=(control_read, event_write), start_new_session=True)
self.owned.callback(self.process.stdout.close)
self.owned.callback(self.process.stderr.close)
os.set_blocking(self.control, False)
for stream, channel in ((event_read, "trace"), (self.process.stdout, "stdout"),
(self.process.stderr, "stderr")):
self.mux.register(stream, selectors.EVENT_READ, channel)
except BaseException:
self.close()
raise
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def close_control(self):
if self.control is not None:
os.close(self.control)
self.control = None
def close(self):
try:
if self.process is not None and self.process.poll() is None:
try:
os.killpg(self.process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
self.process.wait(timeout=2)
finally:
self.owned.close()
def remaining(self):
seconds = self.deadline - time.monotonic()
check(seconds > 0, f"cc1plus timeout after {len(self.events)} events")
return seconds
def trace(self, data):
self.trace_bytes += len(data)
check(self.trace_bytes <= TRACE_LIMIT, "trace too large")
self.pending.extend(data)
while (end := self.pending.find(b"\n")) >= 0:
check(end + 1 <= FRAME_LIMIT, "frame too large")
event = json.loads(bytes(self.pending[:end]).decode("utf-8", errors="strict"),
object_pairs_hook=unique_keys, parse_constant=reject_number)
del self.pending[:end + 1]
index = len(self.events)
check(isinstance(event, dict) and type(event.get("v")) is int and event["v"] == 1
and event.get("nonce") == self.nonce and type(event.get("seq")) is int
and event["seq"] == index and index < 4096 and event.get("kind") in KINDS,
f"invalid envelope at {index}: {event}")
if index == 0:
check(event["kind"] == "hello" and event.get("backend") == BACKEND
and event.get("pid") == self.process.pid and set(event["kinds"]) == KINDS
and {"integralReturn", "cooperativeStep"} <= set(event["capabilities"]),
f"unexpected handshake {event}")
self.events.append(event)
check(len(self.pending) < FRAME_LIMIT, "oversized unfinished frame")
def pump(self, timeout):
for key, _ in self.mux.select(timeout=min(timeout, self.remaining())):
data = os.read(key.fd, 16384)
if not data:
self.mux.unregister(key.fileobj)
continue
if key.data == "trace":
self.trace(data)
else:
output = self.outputs[key.data]
output.extend(data)
check(len(output) <= 256 * 1024, f"{key.data} exceeded its byte limit")
def next_stop(self, after=-1):
while True:
for event in self.events[after + 1:]:
if event["kind"] == "stopped":
return event
check(self.mux.get_map(), f"missing stopped event: {self.outputs['stderr'][:500]!r}")
self.pump(self.remaining())
def held(self, stop):
end = time.monotonic() + 0.1
while time.monotonic() < end:
self.pump(max(0, end - time.monotonic()))
check(self.process.poll() is None and os.getpgid(self.process.pid) == self.process.pid,
"compiler left the held stop")
check(self.events[-1] == stop and not self.pending, "compiler emitted data past the stop")
def send(self, data):
while data:
_, writable, _ = select.select([], [self.control], [], self.remaining())
check(writable, "timeout sending control")
try:
size = os.write(self.control, data)
except BlockingIOError:
continue
check(size > 0, "short control write")
data = data[size:]
def command(self, stop, action):
return f"{self.nonce} {stop['seq']} {action}\n".encode("ascii")
def wait(self, code):
while self.mux.get_map():
self.pump(self.remaining())
result = self.process.wait(timeout=self.remaining())
check(not self.pending, "truncated last record")
check(not self.outputs["stdout"], f"unexpected stdout {self.outputs['stdout'][:200]!r}")
check(result == code, f"exit {result}, expected {code}: {self.outputs['stderr'][:500]!r}")
return bytes(self.outputs["stderr"])
def frames(events, terminal="frontendEnd"):
"""Check the full call/stop grammar and index each observed frame's evidence."""
check(events and events[0]["kind"] == "hello" and events[-1]["kind"] == terminal,
f"missing handshake or expected {terminal}")
calls, stack = {}, []
stopped = None
for i, event in enumerate(events[1:], 1):
kind = event["kind"]
if stopped is not None:
check(kind in ("resumed", "terminal") and event.get("stop") == stopped["seq"],
"unacknowledged stop")
if kind in ("terminal", "frontendEnd"):
check(i == len(events) - 1, "records after termination")
if kind == "frontendEnd":
check(not stack and stopped is None, "unfinished calls at frontendEnd")
continue
frame = event.get("frame")
parent = event.get("parent")
check(type(frame) is int and frame > 0 and "parent" in event
and (parent is None or type(parent) is int), f"invalid call identity {event}")
if kind == "enter":
check(frame not in calls and parent == (stack[-1] if stack else None),
"wrong call parent or reused frame")
stack.append(frame)
calls[frame] = {"enter": event}
continue
check(stack and frame == stack[-1] and calls[frame]["enter"]["parent"] == parent,
"event for inactive frame")
call = calls[frame]
check(kind not in call, f"duplicate {kind} in frame {frame}")
call[kind] = event
if kind == "body":
check("cached" not in call, "body for cache hit")
elif kind == "cached":
check("body" not in call and "value" not in call, "cache hit with observed body")
elif kind == "value":
check("body" in call, "value outside body")
value = event["value"]
if value["kind"] == "integer":
integer(value)
else:
check(value == {"kind": "unavailable", "reason": "unsupportedScalar"},
f"invalid unavailable value {value}")
elif kind == "stopped":
prev = events[i - 1]
check(prev["kind"] == "value" and prev["frame"] == frame
and prev["value"]["kind"] == "integer", "stop without an actual integer")
stopped = event
elif kind == "resumed":
check(stopped is not None and event["action"] in ("step", "continue"),
"unmatched resume")
stopped = None
elif kind == "leave":
check(event["outcome"] in {"returned", "failed", "overflow", "throw", "jump",
"void", "constructor"}, f"unexpected outcome {event}")
stack.pop()
else:
raise AssertionError(f"unexpected {kind}")
return calls
def witness(calls, ready):
pairs = []
for frame, outer in calls.items():
if outer["enter"]["name"] != "twice" or "value" not in outer:
continue
children = [c for c in calls.values() if c["enter"]["parent"] == frame
and c["enter"]["name"] == "reflected_value" and "value" in c]
check(len(children) == 1, f"expected inner reflected_value for frame {frame}")
inner = children[0]
check(outer["body"]["seq"] < inner["enter"]["seq"] < inner["body"]["seq"]
< inner["value"]["seq"] < inner["leave"]["seq"] < outer["value"]["seq"]
< outer["leave"]["seq"], "observed values outside their dynamic bodies")
for call in (inner, outer):
check(call["leave"]["outcome"] == "returned", "return failed after capture")
check(call["value"]["value"]["signed"] and call["value"]["value"]["precision"] == 32,
"fixture did not return int")
pairs.append((integer(inner["value"]["value"]), integer(outer["value"]["value"])))
expected = [(ready, 2 * ready), (ready + 5, 2 * (ready + 5))]
check(pairs == expected, f"observed {pairs}, expected {expected}")
return pairs
OBSERVE = ["-fvls-observe"]
STEP = [*OBSERVE, "-fvls-step"]
def completed(binary, source, flags, code=0, **kwargs):
with Invocation(binary, source, flags, **kwargs) as run:
diagnostics = run.wait(code)
return run.events, diagnostics
def values_and_parity(binary, source, original):
for ready in (17, 41):
edited = original.replace("Ready = 17", f"Ready = {ready}")
check(edited.count(">(0) > 0") == 1 and edited.count(">(5) > 0") == 1,
"fixture predicates changed")
source.write_text(edited, encoding="utf-8")
disabled, reference = completed(binary, source, [])
observed, diagnostics = completed(binary, source, OBSERVE)
check(not disabled and reference == diagnostics == b"", "disabled/on parity failed")
calls = frames(observed)
pairs = witness(calls, ready)
for call in calls.values():
enter = call["enter"]
if enter["name"] in ("reflected_value", "twice"):
check(enter.get("sourceKind") == "logicalDeclaration"
and enter["source"] == source.name and enter["byteColumn"] > 0
and enter["line"] in (5, 10), f"unexpected declaration location {enter}")
print(f"Ready={ready} real integral returns at bias 0 and 5: {pairs}")
def control_cases(binary, source):
with Invocation(binary, source, STEP) as run:
inner = run.next_stop()
frames_seen = {e["frame"]: e for e in run.events if e["kind"] == "enter"}
value = run.events[inner["seq"] - 1]
check(frames_seen[inner["frame"]]["name"] == "reflected_value"
and frames_seen[inner["parent"]]["name"] == "twice"
and value["frame"] == inner["frame"] and integer(value["value"]) == 17,
"first stop outside the real inner return")
run.held(inner)
# Same shape but guaranteed different nonce; old and future sequences,
# an unrecognized action, and a NUL suffix must also leave the child held.
other = ("0" if run.nonce[0] != "0" else "1") + run.nonce[1:]
run.send(f"{other} {inner['seq']} step\n".encode())
run.send(run.command({"seq": inner["seq"] - 1}, "continue"))
run.send(run.command({"seq": inner["seq"] + 1}, "cancel"))
run.send(run.command(inner, "step\0garbage"))
run.held(inner)
command = run.command(inner, "step")
run.send(command[:-1])
run.held(inner)
run.send(command[-1:])
outer = run.next_stop(after=inner["seq"])
check(outer["frame"] == inner["parent"]
and integer(run.events[outer["seq"] - 1]["value"]) == 34,
"step did not reach the outer return")
run.send(run.command(inner, "continue"))
run.held(outer)
run.send(run.command(outer, "continue"))
check(not run.wait(0), "unexpected step diagnostics")
witness(frames(run.events), 17)
acks = [(e["stop"], e["action"]) for e in run.events if e["kind"] == "resumed"]
check(acks == [(inner["seq"], "step"), (outer["seq"], "continue")],
f"wrong control acknowledgements {acks}")
print(f"PID {run.process.pid} held at inner 17, stepped to outer 34, continued and reaped")
for action, reason, code in (("cancel", "cancelled", 125), ("EOF", "controlEOF", 126),
("oversize", "controlLimit", 126)):
with Invocation(binary, source, STEP) as run:
stop = run.next_stop()
check(integer(run.events[stop["seq"] - 1]["value"]) == 17, "wrong initial stop")
run.held(stop)
if action == "EOF":
run.close_control()
elif action == "oversize":
run.send(b"x" * 4097)
else:
run.send(run.command(stop, action))
run.wait(code)
calls = frames(run.events, "terminal")
check(run.events[-1]["reason"] == reason and "value" not in calls[stop["parent"]],
"control loss or cancellation allowed outer evaluation")
print(f"{action} at inner stop: {reason}, exit {code}, reaped PID {run.process.pid}")
SCALARS = """
consteval signed char narrow(int n) { return static_cast<signed char>(-n); }
consteval unsigned long long high(unsigned n) { return (1ULL << 63) + n; }
consteval long long negative(long long n) { return -n; }
consteval bool flag(int n) { return n != 0; }
consteval __int128 wide(int n) { return static_cast<__int128>(n) << 64; }
consteval double floating(int n) { return static_cast<double>(n); }
consteval int reuse(int n) { return n + 1; }
consteval int repeat(int n) { return reuse(n) + reuse(n); }
static_assert(narrow(3) < 0 && high(5) > 0 && flag(7));
static_assert(negative(23) < 0 && wide(7) > 0 && floating(3) > 0);
static_assert(repeat(11) > 0);
"""
FAILURES = """
consteval int may_throw(int n) {
if (n) throw n;
return n;
}
consteval int recover(int n) {
try { return may_throw(n); } catch (int caught) { return caught * 2; }
}
static_assert(recover(7) > 0);
struct Piece { int x; constexpr Piece(int n): x(n) {} };
constexpr void bump(Piece& p) { ++p.x; }
consteval int worked(int n) { Piece p(n); bump(p); return p.x; }
static_assert(worked(18) > 0);
"""
BAD_CLEANUP = """
struct Gone { int x; };
consteval int provisional(Gone g, Gone*& p) { p = &g; g.~Gone(); return 9; }
consteval int caller(int n) { Gone* p; return provisional(Gone{n}, p); }
static_assert(caller(5) > 0);
"""
OVERFLOW = """
consteval int over(int n) { return n + 1; }
static_assert(over(__INT_MAX__) > 0);
"""
LIMIT = """
consteval int one(int n) { return n + 1; }
consteval int many(int count) {
int sum = 0;
for (int i = 0; i < count; ++i) sum += one(i);
return sum;
}
static_assert(many(1600) > 0);
"""
def scalar_cases(binary, source, original):
source.write_text(original + SCALARS + FAILURES, encoding="utf-8")
events, diagnostics = completed(binary, source, OBSERVE)
check(not diagnostics, f"unexpected scalar diagnostics {diagnostics[:400]!r}")
calls = frames(events)
by_name = {}
for call in calls.values():
by_name.setdefault(call["enter"]["name"], []).append(call)
def snapshot(name):
values = [c["value"]["value"] for c in by_name[name] if "value" in c
and c["leave"]["outcome"] == "returned"]
check(len(values) == 1, f"expected one scalar result for {name}, got {values}")
return values[0]
for name, width, signed, bits in (
("narrow", 8, True, "fd"), ("high", 64, False, "8000000000000005"),
("negative", 64, True, "ffffffffffffffe9"), ("flag", 1, False, "1")):
value = snapshot(name)
check((value["precision"], value["signed"], value["bitsHex"]) == (width, signed, bits),
f"{name}: wrong bits or type {value}")
for name in ("wide", "floating"):
check(snapshot(name)["kind"] == "unavailable", f"{name}: unsupported scalar reported")
hits = [c for c in by_name["reuse"] if "cached" in c]
check(hits and all("body" not in c and "value" not in c for c in hits),
"reused evaluator result had no distinct cache-hit witness")
check(all(not any(x["enter"]["parent"] == hit["enter"]["frame"] for x in calls.values())
for hit in hits), "cache hit fabricated children")
thrown = [c for c in by_name["may_throw"] if c["leave"]["outcome"] == "throw"]
check(thrown and all("value" not in c for c in thrown), "throw reported a normal return")
check(integer(snapshot("recover")) == 14, "caught exception lost its caller's return")
constructors = [c for c in calls.values() if c["leave"]["outcome"] == "constructor"]
check(constructors and all("value" not in c for c in constructors)
and all(c["leave"]["outcome"] == "void" and "value" not in c for c in by_name["bump"])
and integer(snapshot("worked")) == 19, "misclassified void or constructor")
print("Verified integer widths and bits, unsupported scalars, cache, throw, void and constructor")
def failure_parity(binary, source, original):
source.write_text(original, encoding="utf-8")
reject = ["-DVLS_CHECK_REJECTED_CONSTRAINT"]
disabled, reference = completed(binary, source, reject, 1)
events, diagnostics = completed(binary, source, [*OBSERVE, *reject], 1)
check(not disabled and reference == diagnostics and b"constraints not satisfied" in diagnostics,
"constraint diagnostic changed in the observed compiler")
frames(events)
for tail, name, outcome in ((BAD_CLEANUP, "provisional", "failed"),
(OVERFLOW, "over", "overflow")):
source.write_text(original + tail, encoding="utf-8")
disabled, reference = completed(binary, source, [], 1)
events, diagnostics = completed(binary, source, OBSERVE, 1)
check(not disabled and reference and reference == diagnostics, f"{name} diagnostic changed")
attempts = [c for c in frames(events).values() if c["enter"]["name"] == name]
check(attempts and all(c["leave"]["outcome"] == outcome for c in attempts),
f"{name} lost its final outcome")
if name == "provisional":
check(all(integer(c["value"]["value"]) == 9 for c in attempts)
and b"outside its lifetime" in reference, "missing provisional pre-cleanup value")
else:
check(all("value" not in c for c in attempts), "fabricated integer on overflow")
source.write_text(original, encoding="utf-8")
for flags, nonce, invalid_pipe in ((OBSERVE, "a" * 31, False),
(OBSERVE, "A" * 32, False),
(OBSERVE, None, True),
(["-fvls-step"], None, False)):
events, diagnostics = completed(binary, source, flags, 1,
nonce=nonce, invalid_pipe=invalid_pipe)
check(not events and b"invalid private evaluator observer setup" in diagnostics,
"invalid setup did not fail before emitting events")
print("Matched constraint, cleanup and overflow diagnostics; provisional 9 left as failed")
print("Four invalid observer setups rejected before handshake")
def wire_limits(binary, directory, original):
for name, expected in (('quote"slash\\.cpp', 'quote"slash\\.cpp'), ("ctrl\x1f.cpp", None),
(os.fsdecode(b"byte\xff.cpp"), None)):
source = directory / name
source.write_text(original, encoding="utf-8")
events, diagnostics = completed(binary, source, OBSERVE)
check(not diagnostics, "unexpected diagnostics for source name")
calls = frames(events)
witness(calls, 17)
check(all("source" in c["enter"] and c["enter"]["source"] == expected
for c in calls.values()), "unescaped or incorrectly reconstructed source name")
source = directory / "many.cpp"
source.write_text(original + LIMIT, encoding="utf-8")
events, _ = completed(binary, source, OBSERVE, 126)
frames(events, "terminal")
check(len(events) == 4096 and events[-1]["reason"] == "truncated", "invalid quota result")
print(f"Strict JSON survived special source names; event quota closed at {len(events)} records")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc1plus", type=Path, required=True, help="absolute private cc1plus path")
binary = parser.parse_args().cc1plus
check(binary.is_absolute() and binary.is_file() and os.access(binary, os.X_OK),
"supply the absolute path to the patched private cc1plus")
original = Path(__file__).with_name("gcc-live.cpp").read_text(encoding="utf-8")
check(original.count("Ready = 17") == 1, "fixture no longer has its controlled edit")
with tempfile.TemporaryDirectory(prefix="vls-gcc-events-") as work:
directory = Path(work)
source = directory / "live.cpp"
values_and_parity(binary, source, original)
source.write_text(original, encoding="utf-8")
control_cases(binary, source)
scalar_cases(binary, source, original)
failure_parity(binary, source, original)
wire_limits(binary, directory, original)
print(f"{BACKEND} direct evaluator checks passed")
if __name__ == "__main__":
main()