"""Exercise the VLS diagnostic adapter with an unmodified GCC and a real native Void TU.""" import argparse import hashlib import json import os from pathlib import Path import shlex import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parents[3] TU = ROOT / "src/Documents/DocumentSnapshot.cpp" LIB_INCLUDE = ROOT / "build/voidlibrary/current/include" MAX_REPORT = 4 * 1024 * 1024 def check(condition, detail): if not condition: raise ValueError(detail) def checked_command(fixture, compiler, database=None): command = [fixture, "--command", ROOT, TU, compiler] if database: command.append(database) result = subprocess.run(command, capture_output=True, text=True, timeout=30) check(result.returncode == 0 and not result.stderr, f"could not acquire a checked editor compiler context: {result.stderr}") row = json.loads(result.stdout) with open(compiler, "rb") as binary: digest = hashlib.file_digest(binary, "sha256").hexdigest() check(row["provider"] == ("compdb" if database else "vbs") and Path(row["directory"]).is_absolute() and row["file"] == str(TU) and row["driverSha256"] == digest, "wrong compiler lease") return row def native_flags(fixture, compiler, expected): selected = checked_command(fixture, compiler) path = Path(selected["database"]) check(expected is None or path == expected, "the selected native VBS generation changed") check(path.stat().st_size <= 16 * 1024 * 1024, "oversized compilation database") rows = json.loads(path.read_bytes()) matches = [r for r in rows if r.get("file") == str(TU)] check(len(matches) == 1, "the native fixture requires one command for DocumentSnapshot.cpp") row = matches[0] args = row["arguments"] check(Path(args[0]).samefile(compiler) and row["directory"] == selected["directory"] == str(ROOT), "the native fixture and selected stock compiler must agree") check(args[-4:] == ["-c", str(TU), "-o", row["output"]], "unexpected native output operands") check(selected["arguments"] == args[:-2], "C++ lease and native semantic argument order disagree") flags = selected["arguments"][1:-2] roots = {str(ROOT / "include"), str(LIB_INCLUDE.resolve(strict=True))} accepted = {"-std=c++26", "-freflection", "-DVOID_CRYPTO_HAS_OPENSSL=0", "-g", "-O0", "-O2", "-O3", "-DNDEBUG"} i = 0 while i < len(flags): if flags[i] == "-I": check(i + 1 < len(flags) and flags[i + 1] in roots, "unexpected fixture include root") i += 2 else: check(flags[i] in accepted, f"unexpected native fixture argument {flags[i]!r}") i += 1 check(roots.issubset(flags) and {"-std=c++26", "-freflection"}.issubset(flags), "incomplete native C++26 fixture command") return flags def capture_report(argv, cwd, status): with tempfile.TemporaryFile() as report, tempfile.TemporaryFile() as output: proc = subprocess.run(argv, cwd=cwd, env={**os.environ, "LC_ALL": "C"}, stdin=subprocess.DEVNULL, stdout=output, stderr=report, timeout=45) size = report.tell() check(0 < size <= MAX_REPORT and output.tell() == 0, "incomplete GCC diagnostic output") report.seek(0) wire = report.read() check(proc.returncode == status, f"GCC exit {proc.returncode}, expected {status}: {wire[:400]!r}") return wire def compile_report(compiler, flags, source, status): return capture_report([compiler, *flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", source.name], source.parent, status) def observe(fixture, compiler, flags, source, text, status, witness=()): source.write_text(text, encoding="utf-8") report = compile_report(compiler, flags, source, status) result = subprocess.run([fixture, source.name, str(status), *map(str, witness)], cwd=source.parent, input=report, capture_output=True, check=True, timeout=10) check(not result.stderr, result.stderr) return json.loads(result.stdout), json.loads(report)["runs"][0] def clean(result): check(result == {"complete": True, "diagnostics": []}, f"expected a clean owner: {result!r}") def isolated_inputs(fixture, compiler, flags, work): """Nix/Linux fixture. Mount only the known compiler and fixture inputs at their original paths.""" def captured_input(path, edited=None): mode = "--capture-disk" if edited is None else "--capture-overlay" proc = subprocess.run([fixture, mode, ROOT, TU, compiler, path], input=edited or b"", capture_output=True, timeout=30) check(proc.returncode == 0 and not proc.stderr, f"source capture failed: {proc.stderr!r}") entry = json.loads(proc.stdout) check(entry["uri"] == path.as_uri() and entry["overlay"] == (edited is not None), f"source capture returned the wrong binding for {path}") data = entry["text"].encode("utf-8") if edited is not None: check(data == edited, "captured bytes lost an editor change") return data bwrap, store = shutil.which("bwrap"), shutil.which("nix-store") check(bwrap and store, "isolated fixture requires bubblewrap and nix-store") frontend = Path(subprocess.check_output([compiler, "-print-prog-name=cc1plus"], timeout=10, text=True).strip()).resolve(strict=True) check(frontend.is_relative_to("/nix/store") and len(frontend.parts) > 4, "expected a Nix GCC package") package = Path(*frontend.parts[:4]) closure = {Path(p) for p in subprocess.check_output([store, "-qR", package], timeout=20, text=True).splitlines()} check(0 < len(closure) <= 128 and all(p.parent == Path("/nix/store") for p in closure), "unexpected compiler runtime closure") probe = subprocess.run([compiler, "-###", *flags, "-frandom-seed=vls-test-view", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", TU], cwd=ROOT, capture_output=True, text=True, check=True, timeout=15, env={**os.environ, "LC_ALL": "C"}) cmds = [shlex.split(line) for line in probe.stderr.splitlines() if line.lstrip().startswith((str(frontend) + " ", '"' + str(frontend) + '" '))] check(len(cmds) == 1 and cmds[0][0] == str(frontend) and cmds[0].count(str(TU)) == 1, "could not identify one GCC frontend for the original translation unit") args = cmds[0] system_dirs = {Path(args[i + 1]) for i, arg in enumerate(args[:-1]) if arg in {"-isystem", "-idirafter"}} check(all(p.is_relative_to("/nix/store") and p.is_dir() for p in system_dirs), "expected immutable toolchain include directories") sandbox = [bwrap, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", "--setenv", "LC_ALL", "C", "--dev", "/dev", "--tmpfs", "/tmp"] for p in sorted(closure | {p for p in system_dirs if not any(p.is_relative_to(k) for k in closure)}): sandbox.extend(["--ro-bind", p, p]) include = work / "vls-headers" for name in ("DocumentSnapshot.hpp", "Position.hpp", "Uri.hpp"): relative = Path("Void/LanguageServer/Documents", name) dest = include / relative dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(captured_input(ROOT / "include" / relative)) deps = LIB_INCLUDE.resolve(strict=True) original = captured_input(TU) text = original.decode("utf-8") saved = work / "saved-input.cpp" saved.write_bytes(original) broken = work / "broken-input.cpp" broken.write_bytes(captured_input(TU, text.replace("Void::Hash::fnv1a64(text)", "Void::Hash::missing(text)").encode())) line, = [i for i, s in enumerate(broken.read_text().splitlines(), 1) if "Void::Hash::missing(text)" in s] first = broken.read_text().splitlines()[line - 1].index("missing") + 1 end = first + len("missing") def compile_view(source, code, witness=(), additional=()): mounts = [(include, ROOT / "include"), (deps, deps), (source, TU), *additional] command = [*sandbox] for src, dst in mounts: command.extend(["--ro-bind", src, dst]) wire = capture_report([*command, "--chdir", ROOT, "--", *args], work, code) out = subprocess.run([fixture, "--logical-file", TU, source.name, str(code), *map(str, witness)], cwd=work, input=wire, capture_output=True, check=True, timeout=10) check(not out.stderr, out.stderr) return json.loads(out.stdout) clean(compile_view(saved, 0)) batch = compile_view(broken, 1, (line, first, end)) check(batch["complete"] and any(d["range"] == [[line-1, first-1], [line-1, end-1]] and "missing" in d["message"] for d in batch["diagnostics"]), batch) clean(compile_view(saved, 0)) header = Path("Void/Core/Hash.hpp") overlay = work / "Hash.hpp" overlay.write_bytes(captured_input(deps / header, b'#error "VLS private header snapshot"\n' + captured_input(deps / header))) header_error = compile_view(saved, 1, additional=[(overlay, deps / header)]) check(any("VLS private header snapshot" in d["message"] for d in header_error["diagnostics"]), "the compiler ignored the staged header at its original name") clean(compile_view(saved, 0)) # A benign host-only file distinguishes a private lookup domain from accidental fallback. marker = work / "host-only.hpp" marker.write_text("// fixture\n", encoding="ascii") lookup = work / "lookup.cpp" lookup.write_bytes(captured_input(TU, (f'#if __has_include("{marker}")\n' '#error host-only file visible\n#endif\n' + text).encode())) outside = json.loads(compile_report(compiler, flags, lookup, 1))["runs"][0] check(any("host-only file visible" in d["message"]["text"] for d in outside["results"]), "missing ambient positive control") clean(compile_view(lookup, 0)) check(TU.read_bytes() == original, "the original TU was modified") print(f"private source view: {len(closure)} compiler runtime paths, saved/edit/recover, " "header overlay and __has_include controls passed") def run(fixture, compiler, database, work): flags = native_flags(fixture, compiler, database) path = work / TU.name text = TU.read_text(encoding="utf-8") call = "Void::Hash::fnv1a64(text)" check(text.count(call) == 1, "the real Void overload witness changed") modified = text.replace(call, "Void::Hash::fnv1a64(std::as_bytes(std::span{text}))") broken = text.replace(call, "Void::Hash::missing(text)") line, = [i for i,s in enumerate(broken.splitlines(), 1) if "Void::Hash::missing(text)" in s] first = broken.splitlines()[line-1].index("missing") + 1 end = first + len("missing") clean(observe(fixture, compiler, flags, path, text, 0)[0]) clean(observe(fixture, compiler, flags, path, modified, 0)[0]) batch, _ = observe(fixture, compiler, flags, path, broken, 1, (line, first, end)) matches = [d for d in batch["diagnostics"] if "missing" in d["message"]] check(batch["complete"] and len(matches) == 1 and matches[0]["range"] == [[line-1, first-1], [line-1, end-1]], batch) clean(observe(fixture, compiler, flags, path, text, 0)[0]) print(f"stock GCC: saved, overload edit, source error at {line}:[{first},{end}), restored") # Change just the copied overload attributes. The two messages independently identify # the overload selected by the compiler when the caller's argument type changes. relative = Path("Void/Core/Hash.hpp") original = (LIB_INCLUDE / relative).read_bytes() header = original.decode("utf-8") for signature, tag in (("fnv1a64(std::string_view s)", "string_view"), ("fnv1a64(std::span data)", "byte_span")): check(header.count(signature) == 1, signature) start = header.rindex("[[nodiscard]]", 0, header.index(signature)) header = header[:start] + header[start:].replace( "[[nodiscard]]", f'[[nodiscard, deprecated("vls-diagnostic-{tag}")]]', 1) overlay_root = work / "header" overlay = overlay_root / relative overlay.parent.mkdir(parents=True) overlay.write_text(header, encoding="utf-8") insert = flags.index(str(LIB_INCLUDE.resolve())) - 1 header_flags = [*flags[:insert], "-I", str(overlay_root), *flags[insert:]] for caller, tag in ((text, "string_view"), (modified, "byte_span")): batch, raw = observe(fixture, compiler, header_flags, path, caller, 0) matched = [r for r in raw["results"] if f"vls-diagnostic-{tag}" in r["message"]["text"] and any(loc["physicalLocation"]["artifactLocation"].get("uri") == path.name and loc["physicalLocation"]["region"]["startLine"] == line for loc in r["locations"])] check(len(matched) == 1 and any(d["message"] == matched[0]["message"]["text"] for d in batch["diagnostics"]), f"missing overload evidence for {tag}") check(all(d["range"] is None for d in batch["diagnostics"]), "range without a physical witness") overlay.write_bytes(original) clean(observe(fixture, compiler, header_flags, path, text, 0)[0]) check((LIB_INCLUDE / relative).read_bytes() == original, "prepared dependency changed") print("stock GCC: staged header reports string_view, then byte_span, then clears on restoration") path = work / "main.cpp" inactive = "int q(){return missing;}" (work / "alias.hpp").write_text('#line 2 "main.cpp"\n' + inactive + "\n", encoding="utf-8") batch, raw = observe(fixture, compiler, ["-std=c++26", "-freflection"], path, "#if 0\n" + inactive + '\n#endif\n#include "alias.hpp"\n', 1) locations = raw["results"][0]["locations"] check(any(loc["physicalLocation"]["artifactLocation"]["uri"] == "main.cpp" and loc["physicalLocation"]["region"]["startLine"] == 2 for loc in locations), "expected GCC to remap the header to the inactive main line") check(not batch["complete"] and any("missing" in d["message"] and d["range"] is None for d in batch["diagnostics"]), batch) print("stock GCC: header remapped to an inactive source line retained an unlocated message") return flags if __name__ == "__main__": cli = argparse.ArgumentParser(description=__doc__) cli.add_argument("--fixture", required=True, type=Path) cli.add_argument("--database", type=Path, help="assert this is the selected native VBS compilation database") cli.add_argument("--comparison", type=Path, help="also acquire the real TU from this compile_commands.json") cli.add_argument("--cxx", default="g++") cli.add_argument("--isolated-inputs", action="store_true", help="also verify a private Linux/Nix input view with bubblewrap") options = cli.parse_args() compiler = shutil.which(options.cxx) if not compiler: cli.error(f"compiler not found: {options.cxx}") with tempfile.TemporaryDirectory(prefix="vls-stock-diagnostic-") as temp: fixture = options.fixture.resolve(strict=True) for directory in ("left right", "left%20right"): work = Path(temp) / directory work.mkdir() result, run_data = observe(fixture, compiler, ["-std=c++26"], work / "unit.cpp", "int x;\n", 0) clean(result) check(run_data["originalUriBaseIds"]["PWD"]["uri"] == f"file://{work}/", "GCC working-directory spelling changed") database = options.database.resolve(strict=True) if options.database else None flags = run(fixture, compiler, database, Path(temp)) if options.comparison: comparison = options.comparison.resolve(strict=True) compat = checked_command(fixture, compiler, comparison) expected_rows = [r for r in json.loads(comparison.read_bytes()) if r["file"] == str(TU)] check(len(expected_rows) == 1 and compat["directory"] == expected_rows[0]["directory"] and compat["database"] == str(comparison) and "-freflection" in compat["arguments"], "incomplete compatibility compiler context") print("compile_commands: acquired and revalidated the selected real Void translation unit") if options.isolated_inputs: isolated_inputs(fixture, compiler, flags, Path(temp))