"""Exercise GCC 16's observable query, recovery, module and metaprogram data.""" import argparse import json import os from pathlib import Path import re import subprocess import tempfile import time FIXTURES = Path(__file__).resolve().parent def run(argv, work, expected=0): start = time.monotonic() result = subprocess.run(argv, cwd=work, env={**os.environ, "LC_ALL": "C"}, capture_output=True, text=True, timeout=60) if result.returncode != expected: raise RuntimeError(f"{argv}: expected {expected}, got {result.returncode}\n{result.stderr}") return result, round((time.monotonic() - start) * 1000, 2) def require(value, reason): if not value: raise ValueError(reason) def fixture_tree(path): # This fixture has a single invocation and a single field access. Its node # numbers and declaration ordering may change independently of its bindings. nodes = {} for match in re.finditer(r"^@(\d+)\s+(\w+)\s+(.*?)(?=^@\d+|\Z)", path.read_text(), re.MULTILINE | re.DOTALL): nodes[match[1]] = (match[2], match[3]) return nodes def edge(nodes, node, key, expected_kind=None): target = re.search(r"(?= 1, "missing source column") return {"message": entry["message"]["text"], "region": region, "related_locations": len(entry.get("relatedLocations", []))} raise ValueError(f"missing {source_name}:{line} diagnostic containing {needle}") def check_modules(flags, work, value): # A content generation gets an isolated GCC module cache. Compile an # importer against the new interface and a control expecting the old value. work.mkdir() provider = (FIXTURES / "gate.cppm").read_text() require(provider.count("Ready = 17") == 1, "expected one serialized enum value") (work / "gate.cppm").write_text(provider.replace("Ready = 17", f"Ready = {value}")) importer = (FIXTURES / "importer.cpp").read_text() importer += f"\nstatic_assert(int([:gate::ready_info():]) == {value});\n" (work / "importer.cpp").write_text(importer) _, compile_ms = run([*flags, "-fmodules", "-x", "c++", "-c", "gate.cppm", "-o", "gate.o"], work) _, import_ms = run([*flags, "-fmodules", "-fsyntax-only", "importer.cpp"], work) other = 41 if value == 17 else 17 (work / "control.cpp").write_text(importer + f"static_assert(int([:gate::ready_info():]) == {other});\n") failed, _ = run([*flags, "-fmodules", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", "control.cpp"], work, expected=1) diagnostic(failed.stderr, "control.cpp", len((work / "control.cpp").read_text().splitlines()), "static assertion failed") return {"case": f"private module generation {value}", "imported_value": value, "interface_ms": compile_ms, "import_ms": import_ms} def probe(compiler, work): version, _ = run([compiler, "-dumpfullversion"], work) require(version.stdout.startswith("16."), f"expected GCC 16, got {version.stdout}") flags = [compiler, "-std=c++26", "-freflection"] saved = (FIXTURES / "gcc-queries.cpp").read_text() projected = saved.replace("shapes::Point point)", "shapes::Point point, double weight)").replace( "coordinate(point)", "coordinate(weight)") cases = [check_query(flags, work, saved, "saved overload", 6, "int"), check_query(flags, work, projected, "projected edit", 7, "double")] (work / "query.cpp").write_text(projected.replace("coordinate(weight)", "missing(weight)")) failed, _ = run([*flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", "query.cpp"], work, expected=1) cases.append({"case": "malformed edit", **diagnostic(failed.stderr, "query.cpp", 11, "missing")}) cases.append(check_query(flags, work, saved, "recovered overload", 6, "int")) for value in (17, 41): cases.append(check_modules(flags, work / f"module-{value}", value)) source = FIXTURES / "gcc-evaluation.cpp" trace = work / "template.txt" run([*flags, f"-fdump-lang-tinst={trace}", "-fsyntax-only", source], work) lines = trace.read_text().splitlines() outer = next(i for i, line in enumerate(lines) if re.match(r"I consteval int twice\(\).*State", line)) require(any(re.match(r" I consteval int reflected_value\(\).*State", line) for line in lines[outer + 1:]), "missing nested consteval instantiation") cases.append({"case": "template instantiation dump", "outer": "twice", "inner": "reflected_value"}) failed, _ = run([*flags, "-DCHECK_CONSTRAINT_DIAGNOSTIC", "-fconcepts-diagnostics-depth=3", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", source], work, expected=1) constraint = diagnostic(failed.stderr, source.name, 11, "reflected_value") require(constraint["related_locations"] > 0, "constraint failure has no related source locations") cases.append({"case": "constraint rejection", **constraint}) require((FIXTURES / "gcc-queries.cpp").read_text() == saved, "saved input changed") return {"gcc": version.stdout.strip(), "cases": cases} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--cxx", default="g++") args = parser.parse_args() with tempfile.TemporaryDirectory(prefix="vls-gcc-tooling-") as temp: print(json.dumps(probe(args.cxx, Path(temp)), indent=2))