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.
581 lines
30 KiB
Python
581 lines
30 KiB
Python
"""Verify GCC 16 module scanning and compilation in isolated CMI caches."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
FIXTURES = Path(__file__).resolve().parent
|
|
FLAGS = ("-std=c++26", "-freflection", "-fmodules", "-fdiagnostics-color=never")
|
|
PREPROCESS = ("-E", "-MD")
|
|
ALLOW_MISSING = ("-M", "-MG")
|
|
MODULE = "corpus.topology"
|
|
API = f"{MODULE}:api"
|
|
DETAIL = f"{MODULE}:detail"
|
|
HEADER = "vls-unit.hpp"
|
|
TEXT_INPUTS = ("config/seed.hpp", "config/value.hpp")
|
|
MODULE_UNITS = ("detail", "api", "topology", "implementation")
|
|
MAX_SCAN_BYTES = 256 * 1024
|
|
MAX_MANIFEST_BYTES = 2 * 1024 * 1024
|
|
COMPILER_ENV = ("LC_ALL", "GCC_EXEC_PREFIX", "COMPILER_PATH", "LIBRARY_PATH",
|
|
"NIX_CFLAGS_COMPILE", "NIX_CFLAGS_COMPILE_FOR_TARGET")
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise ValueError(message)
|
|
|
|
|
|
def capture(stream):
|
|
stream.seek(0)
|
|
return read_limited(stream, 8192).decode("utf-8", errors="replace").strip()
|
|
|
|
|
|
def read_limited(stream, limit):
|
|
data = stream.read(limit + 1)
|
|
require(len(data) <= limit, f"{stream.name}: exceeded {limit} bytes")
|
|
return data
|
|
|
|
|
|
def scan_text(path):
|
|
with path.open("rb") as stream:
|
|
return read_limited(stream, MAX_SCAN_BYTES).decode("utf-8")
|
|
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(json.dumps(value, sort_keys=True).encode("ascii")).hexdigest()
|
|
|
|
|
|
def file_digest(path, limit=MAX_SCAN_BYTES):
|
|
require(path.is_file(), f"expected a regular fixture input: {path}")
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as stream:
|
|
while chunk := stream.read(min(limit + 1, 1024 * 1024)):
|
|
require(len(chunk) <= limit, f"file exceeds hashing limit: {path}")
|
|
limit -= len(chunk)
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def rejection(result, diagnostic):
|
|
return {"exit": result.returncode,
|
|
"diagnostic": next(line for line in result.stderr.splitlines() if diagnostic in line)}
|
|
|
|
|
|
class Corpus:
|
|
def __init__(self, compiler, planner=None):
|
|
self.compiler = compiler
|
|
self.planner = planner
|
|
self.env = {**os.environ, "LC_ALL": "C"}
|
|
# GCC's default mapper keeps CMIs under the invocation's working directory.
|
|
for key in ("CXX_MODULE_MAPPER", "CPATH", "CPLUS_INCLUDE_PATH"):
|
|
self.env.pop(key, None)
|
|
self.scans = {}
|
|
self.rejections = {}
|
|
self.observations = {}
|
|
self.plans = {}
|
|
|
|
def run(self, work, argv, diagnostic=None, *, stdin=subprocess.DEVNULL):
|
|
with tempfile.TemporaryFile(dir=work) as stdout, tempfile.TemporaryFile(dir=work) as stderr:
|
|
result = subprocess.run(argv, cwd=work, env=self.env, stdin=stdin,
|
|
stdout=stdout, stderr=stderr, timeout=30)
|
|
result.stdout, result.stderr = capture(stdout), capture(stderr)
|
|
expected = 0 if diagnostic is None else 1
|
|
require(result.returncode == expected and (diagnostic is None or diagnostic in result.stderr),
|
|
f"{work.name}: {argv!r}: expected exit {expected}, diagnostic {diagnostic!r}; "
|
|
f"got exit {result.returncode}\n{result.stderr}\n{result.stdout}")
|
|
return result
|
|
|
|
def compile(self, work, *args, diagnostic=None):
|
|
return self.run(work, [self.compiler, *FLAGS, *args], diagnostic)
|
|
|
|
def reject(self, work, name, diagnostic, *args):
|
|
result = self.compile(work, *args, diagnostic=diagnostic)
|
|
self.rejections[f"{work.name}/{name}"] = {"arguments": args, **rejection(result, diagnostic)}
|
|
|
|
def scan(self, work, name, source, *, provides=None, requires=(), flags=(),
|
|
mode=PREPROCESS, make_inputs=(), diagnostic=None, writes_rule=True):
|
|
output = f"scan-{name}.json"
|
|
depfile = f"scan-{name}.d"
|
|
primary = f"{name}.o"
|
|
make_target = f"{name}.make.o"
|
|
argv = [self.compiler, *FLAGS, *flags, *mode, "-MF", depfile, "-MT", make_target,
|
|
"-fdeps-format=p1689r5", f"-fdeps-file={output}", f"-fdeps-target={primary}",
|
|
"-o", os.devnull, source]
|
|
result = self.run(work, argv, diagnostic)
|
|
case = f"{work.name}/{name}"
|
|
require(case not in self.scans, f"duplicate scanner capture: {case}")
|
|
record = {"source": source, "options": [*mode, *flags], "exit": result.returncode}
|
|
if diagnostic is not None:
|
|
record.update(rejection(result, diagnostic))
|
|
self.scans[case] = record
|
|
|
|
path = work / output
|
|
require(path.is_file() == writes_rule, f"{case}: unexpected presence of P1689 output")
|
|
if not writes_rule:
|
|
record["rule"] = None
|
|
return
|
|
|
|
raw = scan_text(path)
|
|
data = json.loads(raw)
|
|
require((data["version"], data["revision"], len(data["rules"])) == (0, 0, 1),
|
|
f"{case}: unexpected GCC P1689 envelope {data!r}")
|
|
rule = data["rules"][0]
|
|
observed_provides = rule.get("provides", [])
|
|
observed_requires = sorted(rule["requires"], key=lambda item: item["logical-name"])
|
|
expected_provides = [] if provides is None else [
|
|
{"logical-name": provides[0], "is-interface": provides[1]},
|
|
]
|
|
expected_requires = [{"logical-name": item} for item in sorted(requires)]
|
|
require((rule["primary-output"], observed_provides, observed_requires) ==
|
|
(primary, expected_provides, expected_requires), f"{case}: unexpected P1689 rule {rule!r}")
|
|
record["rule"] = {"primary-output": rule["primary-output"], "provides": observed_provides,
|
|
"requires": observed_requires}
|
|
|
|
tokens = scan_text(work / depfile).replace("\\\n", " ").split()
|
|
require(tokens and tokens[0] == f"{make_target}:" and set(make_inputs).issubset(tokens[1:]),
|
|
f"{case}: unexpected Make dependencies {tokens!r}")
|
|
if make_inputs:
|
|
record["make_inputs"] = list(make_inputs)
|
|
if self.planner:
|
|
self.observations[case] = (argv, raw, tokens[1:], len(self.scans))
|
|
|
|
def identify_toolchain(self, work, version, target):
|
|
frontend = Path(self.run(work, [self.compiler, "-print-prog-name=cc1plus"]).stdout)
|
|
require(frontend.is_absolute(), f"GCC did not identify its cc1plus: {frontend}")
|
|
images = (Path(self.compiler).resolve(strict=True), frontend.resolve(strict=True))
|
|
self.toolchain = digest({
|
|
"version": version, "target": target,
|
|
"images": [(str(path), file_digest(path, 512 * 1024 * 1024)) for path in images],
|
|
"environment": {key: self.env.get(key) for key in COMPILER_ENV},
|
|
})
|
|
|
|
def member(self, work, name, *, owner=None, writer=None, dependencies=(), complete=True,
|
|
header_provider=False, no_header_units=True):
|
|
case = f"{work.name}/{name}"
|
|
record = self.scans[case]
|
|
argv, raw, make_dependencies, sequence = self.observations[case]
|
|
owner = owner or record["source"]
|
|
expected = {owner, *record.get("make_inputs", ()), *dependencies}
|
|
actual = set(make_dependencies)
|
|
implicit = actual - expected
|
|
# The only nonfixture input in these selected runs is GCC's implicit preinclude,
|
|
# when present. Refuse to open any other dependency named by the depfile.
|
|
require(expected <= actual and len(implicit) <= 1 and
|
|
all(Path(path).is_absolute() and Path(path).name == "stdc-predef.h"
|
|
for path in implicit), f"{case}: cannot attest dependencies {make_dependencies!r}")
|
|
observations = [(path, file_digest(work / path)) for path in make_dependencies]
|
|
primary = record["rule"]["primary-output"]
|
|
member = {
|
|
"name": name, "source": record["source"], "owning_source": owner,
|
|
"argv": argv, "exit": record["exit"], "p1689": raw,
|
|
"primary_output": primary, "writer": writer or primary,
|
|
"command_id": digest((self.toolchain, str(work), argv)),
|
|
"source_id": dict(observations)[owner], "textual_closure": digest(observations),
|
|
"complete": complete, "header_provider": header_provider,
|
|
"no_header_units": no_header_units,
|
|
}
|
|
return {**member, "scan_revision": digest((sequence, member))}
|
|
|
|
def plan(self, work, name, requested, members, shared_flags):
|
|
# These are closed, authored fixture inputs. The only named topology lookups are
|
|
# the quoted config headers and the private CMI root. The reader assertion define
|
|
# belongs to its exact command, while the shared bias define belongs to the domain.
|
|
require(all(member["argv"][1:1 + len(FLAGS) + len(shared_flags)] == [*FLAGS, *shared_flags]
|
|
for member in members), "scan command does not match fixture domain")
|
|
compatibility = digest((self.toolchain, FLAGS, shared_flags))
|
|
inputs = {member["name"]: {key: member[key] for key in
|
|
("command_id", "source_id", "textual_closure", "exit")}
|
|
for member in members}
|
|
lookup = digest((str(work), str(work / "gcm.cache"), inputs))
|
|
revision = digest((compatibility, lookup, [member["scan_revision"] for member in members]))
|
|
manifest = {"cwd": str(work), "revision": revision, "toolchain": self.toolchain,
|
|
"compatibility": compatibility, "lookup": lookup, "requested": requested,
|
|
"members": members}
|
|
payload = json.dumps(manifest).encode("ascii")
|
|
require(len(payload) <= MAX_MANIFEST_BYTES, "planner fixture manifest too large")
|
|
with tempfile.TemporaryFile(dir=work) as stdin:
|
|
stdin.write(payload)
|
|
stdin.seek(0)
|
|
result = self.run(work, [self.planner], stdin=stdin)
|
|
require(not result.stderr, f"planner wrote to stderr: {result.stderr}")
|
|
plan = json.loads(result.stdout)
|
|
require(isinstance(plan, dict) and plan.get("matches_census") is True,
|
|
f"{work.name}/{name}: planner lost census identity")
|
|
self.plans[f"{work.name}/{name}"] = {
|
|
**plan, "census_revision": revision, "compatibility": compatibility,
|
|
"lookup": lookup, "inputs": inputs,
|
|
}
|
|
return plan
|
|
|
|
|
|
def copy_fixtures(work):
|
|
for source in FIXTURES.rglob("*"):
|
|
if source.suffix in {".cpp", ".cppm", ".hpp"}:
|
|
destination = work / source.relative_to(FIXTURES)
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copyfile(source, destination)
|
|
|
|
|
|
def run_reader(corpus, work, bias, expected, name):
|
|
corpus.compile(work, f"-DCORPUS_BIASED={bias}", f"-DEXPECT_READY={expected}",
|
|
"-c", "importer.cpp", "-o", f"{name}.o")
|
|
corpus.compile(work, *(f"{unit}.o" for unit in MODULE_UNITS), f"{name}.o", "-o", name)
|
|
result = corpus.run(work, [work / name])
|
|
return {"reflected_value": expected, "implementation_value": expected + 7, "exit": result.returncode}
|
|
|
|
|
|
def require_blocked(plan, expected, label):
|
|
actual = {(entry["code"], entry.get("unit"), entry.get("scan_error")) for entry in plan["blockers"]}
|
|
require(plan["ready"] is False and plan["claims_complete"] is False and
|
|
plan["order"] == [] and actual == expected,
|
|
f"{label}: unexpected planner disposition {plan!r}")
|
|
|
|
|
|
def check_topology_plan(corpus, work, flags, bias, check_invalid_wire):
|
|
members = [corpus.member(work, name) for name in MODULE_UNITS]
|
|
importer = corpus.member(work, "importer", writer="reader.o")
|
|
plan = corpus.plan(work, "named", "importer", [*members, importer], flags)
|
|
expected_order = ["api", "topology", "importer"]
|
|
if bias:
|
|
expected_order.insert(0, "detail")
|
|
require(plan["ready"] is True and plan["claims_complete"] is True and
|
|
plan["order"] == expected_order and not plan["blockers"],
|
|
f"{work.name}: unexpected prerequisite order {plan!r}")
|
|
expected_units = {
|
|
"detail": {"kind": "internal_partition",
|
|
"consumers": ["api", "implementation"] if bias else ["implementation"]},
|
|
"api": {"kind": "interface_partition", "consumers": ["topology"]},
|
|
"topology": {"kind": "primary_interface", "consumers": ["implementation", "importer"]},
|
|
"implementation": {"kind": "unknown", "consumers": []},
|
|
"importer": {"kind": "unknown", "consumers": []},
|
|
}
|
|
require(plan["units"] == expected_units, f"{work.name}: unexpected module reverse edges {plan!r}")
|
|
|
|
if check_invalid_wire:
|
|
wrong_output = json.loads(importer["p1689"])
|
|
wrong_output["rules"][0]["primary-output"] = "wrong-importer.o"
|
|
for error, raw in (("wrong_output", json.dumps(wrong_output)),
|
|
("invalid_json", importer["p1689"].rstrip()[:-1])):
|
|
changed = {**importer, "p1689": raw, "scan_revision": digest((importer["scan_revision"], raw))}
|
|
plan = corpus.plan(work, error, "importer", [*members, changed], flags)
|
|
require_blocked(plan, {("invalid_rule", "importer", error)}, error)
|
|
|
|
|
|
def check_topology(corpus, work, seed, bias, previous_context=None):
|
|
copy_fixtures(work)
|
|
if seed != 17:
|
|
path = work / "config/value.hpp"
|
|
text = path.read_text(encoding="utf-8")
|
|
require(text.count("#define CORPUS_SEED 17\n") == 1, "unexpected saved seed fixture")
|
|
path.write_text(text.replace("#define CORPUS_SEED 17\n", f"#define CORPUS_SEED {seed}\n"),
|
|
encoding="utf-8")
|
|
|
|
flags = (f"-DCORPUS_BIASED={bias}",)
|
|
corpus.scan(work, "detail", "detail.cppm", provides=(DETAIL, False), flags=flags)
|
|
corpus.scan(work, "api", "api.cppm", provides=(API, True), requires=(DETAIL,) if bias else (),
|
|
flags=flags, make_inputs=TEXT_INPUTS)
|
|
corpus.scan(work, "topology", "topology.cppm", provides=(MODULE, True), requires=(API,), flags=flags)
|
|
corpus.scan(work, "implementation", "implementation.cpp", requires=(MODULE, DETAIL), flags=flags)
|
|
expected = seed + 7 * bias
|
|
corpus.scan(work, "importer", "importer.cpp", requires=(MODULE,),
|
|
flags=(*flags, f"-DEXPECT_READY={expected}"))
|
|
cache = work / "gcm.cache"
|
|
require(not list(cache.rglob("*.gcm")), f"{work.name}: preprocessing created a CMI")
|
|
if corpus.planner:
|
|
check_topology_plan(corpus, work, flags, bias, check_invalid_wire=(seed == 17))
|
|
|
|
for unit in MODULE_UNITS:
|
|
suffix = "cpp" if unit == "implementation" else "cppm"
|
|
corpus.compile(work, *flags, "-c", f"{unit}.{suffix}", "-o", f"{unit}.o")
|
|
cmis = sorted(path.name for path in cache.glob("*.gcm"))
|
|
require(cmis == [f"{MODULE}-api.gcm", f"{MODULE}-detail.gcm", f"{MODULE}.gcm"],
|
|
f"{work.name}: unexpected named-module CMIs {cmis!r}")
|
|
reader = run_reader(corpus, work, bias, expected, "reader")
|
|
if previous_context is not None:
|
|
previous_bias, previous_value = previous_context
|
|
corpus.reject(work, "stale-expectation", "error: static assertion failed: wrong reflected module value",
|
|
f"-DCORPUS_BIASED={previous_bias}", f"-DEXPECT_READY={previous_value}",
|
|
"-fsyntax-only", "importer.cpp")
|
|
return {"seed": seed, "bias_flag": bias, "cmis": cmis, **reader}
|
|
|
|
|
|
def check_visibility(corpus, work):
|
|
corpus.reject(work, "hidden-partition-name", "error: 'context_bias' is not a member of 'topology'",
|
|
"-fsyntax-only", "visibility.cpp")
|
|
corpus.reject(work, "partition-import-in-global-module", "error: import specifying a module-partition",
|
|
"-DCORPUS_DIRECT_PARTITION=1", "-fsyntax-only", "visibility.cpp")
|
|
|
|
|
|
def header_reader(corpus, work, name, flags, value, logical_name, cmi):
|
|
executable = f"header-reader-{name}"
|
|
result = corpus.compile(work, *flags, f"-DEXPECT_HEADER={value}", "-flang-info-module-cmi",
|
|
"header-importer.cpp", "-o", executable)
|
|
require(f"{logical_name}: note: reading CMI '{cmi}'" in result.stderr,
|
|
f"{name}: wrong CMI read\n{result.stderr}")
|
|
result = corpus.run(work, [work / executable])
|
|
return {"value": value, "cmi": cmi, "exit": result.returncode}
|
|
|
|
|
|
def check_header_units(corpus, work, system_header):
|
|
copy_fixtures(work)
|
|
normal = ("-Iinclude",)
|
|
shadow_first = ("-Ishadow", *normal)
|
|
quoted = ("-DCORPUS_QUOTED_HEADER=1", *shadow_first)
|
|
header_macro = "-DCORPUS_CHECK_HEADER_MACRO=1"
|
|
source = "header-importer.cpp"
|
|
normal_name, shadow_name = f"./include/{HEADER}", f"./shadow/{HEADER}"
|
|
normal_cmi, shadow_cmi = f"gcm.cache/,/include/{HEADER}.gcm", f"gcm.cache/,/shadow/{HEADER}.gcm"
|
|
system_cmi = f"gcm.cache/.{system_header}.gcm"
|
|
missing = "error: failed to read compiled module"
|
|
|
|
corpus.scan(work, "unresolved-header", source, requires=(f"./{HEADER}",),
|
|
mode=ALLOW_MISSING, make_inputs=(HEADER,))
|
|
corpus.scan(work, "cold-header", source, flags=normal,
|
|
diagnostic=f"{normal_name}: {missing}", writes_rule=False)
|
|
corpus.scan(work, "cold-header-macro", source, requires=(normal_name,),
|
|
flags=(*normal, header_macro), mode=ALLOW_MISSING)
|
|
corpus.scan(work, "header-provider", HEADER, provides=(normal_name, True),
|
|
flags=(*normal, "-x", "c++-user-header"))
|
|
corpus.compile(work, *normal, "-x", "c++-user-header", "-c", HEADER)
|
|
corpus.scan(work, "warm-header-macro", source, requires=(normal_name, MODULE),
|
|
flags=(*normal, header_macro), mode=ALLOW_MISSING)
|
|
if corpus.planner:
|
|
provider = corpus.member(work, "header-provider", owner=f"include/{HEADER}",
|
|
header_provider=True)
|
|
# GCC recorded a CMI prerequisite and found the macro-conditioned edge. The depfile
|
|
# cannot certify the consumed CMI generation against this provider's full source closure.
|
|
consumer = corpus.member(work, "warm-header-macro", dependencies=(normal_cmi,),
|
|
complete=False, no_header_units=False)
|
|
plan = corpus.plan(work, "warm-header-pending", "warm-header-macro", [provider, consumer], normal)
|
|
require_blocked(plan, {("incomplete_scan", "warm-header-macro", None),
|
|
("unproven_mapping", "warm-header-macro", None)}, "warm header CMI")
|
|
|
|
results = {}
|
|
for name, flags, value, logical_name, cmi in (
|
|
("normal", normal, 11, normal_name, normal_cmi),
|
|
("quoted", quoted, 11, normal_name, normal_cmi),
|
|
("shadow", shadow_first, 29, shadow_name, shadow_cmi),
|
|
):
|
|
if name == "shadow":
|
|
corpus.reject(work, "different-header-lookup", f"{shadow_name}: {missing}",
|
|
*flags, "-DEXPECT_HEADER=29", "-fsyntax-only", source)
|
|
corpus.scan(work, "shadow-provider", HEADER, provides=(shadow_name, True),
|
|
flags=(*flags, "-x", "c++-user-header"))
|
|
corpus.compile(work, *flags, "-x", "c++-user-header", "-c", HEADER)
|
|
corpus.scan(work, f"{name}-header", source, requires=(logical_name,), flags=flags)
|
|
results[name] = header_reader(corpus, work, name, flags, value, logical_name, cmi)
|
|
|
|
system_source = "system-importer.cpp"
|
|
corpus.scan(work, "cold-system-header", system_source, diagnostic=f"{system_header}: {missing}",
|
|
writes_rule=False)
|
|
corpus.scan(work, "system-header-missing-allowed", system_source, requires=(system_header,),
|
|
mode=ALLOW_MISSING)
|
|
corpus.scan(work, "system-header-provider", "stddef.h", provides=(system_header, True),
|
|
flags=("-x", "c++-system-header"))
|
|
corpus.compile(work, "-x", "c++-system-header", "-c", "stddef.h")
|
|
corpus.scan(work, "system-header", system_source, requires=(system_header,), mode=("-E", "-MMD"))
|
|
result = corpus.compile(work, "-flang-info-module-cmi", "-fsyntax-only", system_source)
|
|
require(f"{system_header}: note: reading CMI '{system_cmi}'" in result.stderr,
|
|
f"wrong system CMI read\n{result.stderr}")
|
|
results["system"] = {"cmi": system_cmi, "exit": result.returncode}
|
|
return results
|
|
|
|
|
|
def check_unresolved(corpus, work):
|
|
copy_fixtures(work)
|
|
missing = "error: failed to read compiled module"
|
|
for name, needed, provided in (
|
|
("missing-provider.cpp", "corpus.missing", None),
|
|
("std-importer.cpp", "std", None),
|
|
("cycle-a.cppm", "corpus.cycle.b", "corpus.cycle.a"),
|
|
("cycle-b.cppm", "corpus.cycle.a", "corpus.cycle.b"),
|
|
):
|
|
case = Path(name).stem
|
|
corpus.scan(work, case, name, provides=(provided, True) if provided else None, requires=(needed,))
|
|
corpus.reject(work, case, f"{needed}: {missing}", "-c", name, "-o", f"{case}.o")
|
|
|
|
fragment = "private-fragment.cppm"
|
|
corpus.scan(work, "private-fragment", fragment, provides=("corpus.fragment", True),
|
|
diagnostic="error: module already declared")
|
|
fragment_cmi = work / "gcm.cache/corpus.fragment.gcm"
|
|
require(not fragment_cmi.exists(), "private fragment scan created a CMI")
|
|
if corpus.planner:
|
|
member = corpus.member(work, "private-fragment", complete=False)
|
|
plan = corpus.plan(work, "failed-scan", "private-fragment", [member], ())
|
|
require_blocked(plan, {("scan_failed", "private-fragment", None),
|
|
("incomplete_scan", "private-fragment", None)}, "failed scan with rule")
|
|
diagnostic = "sorry, unimplemented: private module fragment"
|
|
result = corpus.compile(work, "-c", fragment, "-o", "private-fragment.o", diagnostic=diagnostic)
|
|
return {**rejection(result, diagnostic), "cmi_written_after_failure": fragment_cmi.is_file()}
|
|
|
|
|
|
def check_artifacts(compiler, work, fixture):
|
|
"""Produce a real CMI through the C++ producer and consume the published copy."""
|
|
root = work / "artifacts"
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
source = root / "corpus.cmi.cppm"
|
|
source.write_text("export module corpus.cmi;\n"
|
|
"export int twice(int value) { return value * 2; }\n", encoding="utf-8")
|
|
command = [compiler, "-std=c++26", "-fmodules-ts", "-c", str(source),
|
|
"-o", str(root / "corpus.cmi.o")]
|
|
manifest = {
|
|
"staging": str(root / "staging"),
|
|
"cache": str(root / "cache"),
|
|
"compatibility": "gcc-corpus/x86_64",
|
|
"units": [{
|
|
"alternative": "corpus.cmi",
|
|
"working_directory": str(root),
|
|
"command": command,
|
|
"command_id": "command-corpus-cmi",
|
|
"source_id": "source-corpus-cmi",
|
|
"textual_closure": "closure-corpus-cmi",
|
|
}],
|
|
}
|
|
result = subprocess.run([str(fixture)], input=json.dumps(manifest).encode(),
|
|
capture_output=True, timeout=120)
|
|
require(result.returncode == 0,
|
|
f"artifact fixture failed: {result.stderr[-800:].decode(errors='replace')!r}")
|
|
report = json.loads(result.stdout)
|
|
require(len(report.get("generation", "")) == 64 and len(report.get("artifacts", [])) == 1,
|
|
"incomplete generation report")
|
|
cmi = Path(report["artifacts"][0]["path"])
|
|
require(cmi.is_file() and cmi.read_bytes()[:4] == b"\x7fELF",
|
|
"the published artifact is not a GCC CMI")
|
|
importer = root / "importer"
|
|
(importer / "gcm.cache").mkdir(parents=True)
|
|
published = importer / "gcm.cache" / "corpus.cmi.gcm"
|
|
shutil.copyfile(cmi, published)
|
|
(importer / "main.cpp").write_text(
|
|
"import corpus.cmi;\nint main() { return twice(21) == 42 ? 0 : 1; }\n", encoding="utf-8")
|
|
usable = subprocess.run([compiler, "-std=c++26", "-fmodules-ts", "-fsyntax-only", "main.cpp"],
|
|
cwd=importer, capture_output=True, timeout=120)
|
|
require(usable.returncode == 0,
|
|
f"the published CMI was not usable: {usable.stderr[-800:].decode(errors='replace')!r}")
|
|
published.write_bytes(published.read_bytes()[:128])
|
|
broken = subprocess.run([compiler, "-std=c++26", "-fmodules-ts", "-fsyntax-only", "main.cpp"],
|
|
cwd=importer, capture_output=True, timeout=120)
|
|
require(broken.returncode != 0, "a truncated CMI was accepted")
|
|
scan_command = [compiler, *FLAGS, *PREPROCESS, "-MF", str(root / "scan.d"),
|
|
"-MT", "scan.o", "-fdeps-format=p1689r5",
|
|
f"-fdeps-file={root / 'scan-deps.json'}",
|
|
f"-fdeps-target={root / 'corpus.cmi.o'}",
|
|
"-o", os.devnull, str(source)]
|
|
scan_manifest = {"mode": "scan", "directory": str(root / "scan-private"),
|
|
"working_directory": str(root), "command": scan_command,
|
|
"output": {"working_directory": str(root),
|
|
"spelling": str(root / "corpus.cmi.o")}}
|
|
result = subprocess.run([str(fixture)], input=json.dumps(scan_manifest).encode(),
|
|
capture_output=True, timeout=120)
|
|
require(result.returncode == 0,
|
|
f"scan fixture failed: {result.stderr[-800:].decode(errors='replace')!r}")
|
|
scanned = json.loads(result.stdout)
|
|
require("corpus.cmi" in scanned["provides"], scanned)
|
|
require(scanned["requires"] == [], scanned)
|
|
require(len(scanned.get("generation", "")) == 64,
|
|
f"the scanned module did not publish an artifact generation: {scanned}")
|
|
supersede = dict(manifest)
|
|
supersede.update({"cache": str(root / "supersede-cache"),
|
|
"staging": str(root / "supersede-staging"), "supersede": True})
|
|
result = subprocess.run([str(fixture)], input=json.dumps(supersede).encode(),
|
|
capture_output=True, timeout=120)
|
|
require(result.returncode == 0,
|
|
f"supersede fixture failed: {result.stderr[-800:].decode(errors='replace')!r}")
|
|
superseded = json.loads(result.stdout)
|
|
require(superseded.get("superseded") is True and superseded.get("published") is False,
|
|
f"a superseded module build published: {superseded}")
|
|
require(len(superseded.get("clean_generation", "")) == 64,
|
|
"the clean generation after supersession is missing")
|
|
return {"generation": report["generation"], "sha256": report["artifacts"][0]["sha256"],
|
|
"usable": True, "truncated_rejected": True,
|
|
"superseded_published": False,
|
|
"clean_generation": superseded["clean_generation"],
|
|
"scan": {"provides": scanned["provides"], "requires": scanned["requires"],
|
|
"generation": scanned["generation"]}}
|
|
|
|
|
|
def verify(compiler, work, planner=None, artifacts=None):
|
|
corpus = Corpus(compiler, planner)
|
|
version = corpus.run(work, [compiler, "-dumpfullversion"]).stdout
|
|
require(version.startswith("16."), f"expected GCC 16, got {version!r}")
|
|
target = corpus.run(work, [compiler, "-dumpmachine"]).stdout
|
|
system_header = corpus.run(work, [compiler, "-print-file-name=include/stddef.h"]).stdout
|
|
require(Path(system_header).is_absolute() and Path(system_header).is_file(),
|
|
f"GCC did not locate its system stddef.h: {system_header!r}")
|
|
if planner:
|
|
corpus.identify_toolchain(work, version, target)
|
|
|
|
baseline = work / "baseline"
|
|
biased = work / "biased"
|
|
topologies = {
|
|
"baseline": check_topology(corpus, baseline, 17, 0),
|
|
"edited": check_topology(corpus, work / "edited", 41, 0, previous_context=(0, 17)),
|
|
"biased": check_topology(corpus, biased, 41, 1, previous_context=(0, 41)),
|
|
}
|
|
check_visibility(corpus, biased)
|
|
retained = run_reader(corpus, baseline, 0, 17, "retained-reader")
|
|
headers = check_header_units(corpus, work / "headers", system_header)
|
|
private_fragment = check_unresolved(corpus, work / "unresolved")
|
|
report = {
|
|
"gcc": version, "target": target, "flags": FLAGS,
|
|
"p1689": {"format": "p1689r5", "version": 0, "revision": 0, "scans": corpus.scans},
|
|
"positive_controls": {"topologies": topologies, "retained_reader": retained, "header_units": headers},
|
|
"expected_rejections": corpus.rejections,
|
|
"missing_capabilities": {
|
|
"private_module_fragment": private_fragment,
|
|
"complete_cold_header_unit_scan": {
|
|
"unresolved": "headers/unresolved-header",
|
|
"preprocess_error": "headers/cold-header",
|
|
"conditional_edge_missing": "headers/cold-header-macro",
|
|
"conditional_edge_present_with_cmi": "headers/warm-header-macro",
|
|
},
|
|
},
|
|
}
|
|
if planner:
|
|
original, edited, biased_plan = (corpus.plans[f"{name}/named"] for name in topologies)
|
|
old_api, new_api = original["inputs"]["api"], edited["inputs"]["api"]
|
|
require(old_api["source_id"] == new_api["source_id"] and
|
|
old_api["textual_closure"] != new_api["textual_closure"],
|
|
"the transitive header edit did not change the API input closure")
|
|
require(original["compatibility"] == edited["compatibility"] != biased_plan["compatibility"] and
|
|
len({plan["lookup"] for plan in (original, edited, biased_plan)}) == 3,
|
|
"fixture generations lost lookup or compatibility identity")
|
|
report["planner"] = {"toolchain": corpus.toolchain, "cases": corpus.plans}
|
|
if artifacts:
|
|
report["artifacts"] = check_artifacts(compiler, work, artifacts)
|
|
return report
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--cxx", default="g++", help="GCC 16 C++ executable")
|
|
parser.add_argument("--planner", type=Path, help="opt-in vls_module_scan_fixture executable")
|
|
parser.add_argument("--artifacts", type=Path,
|
|
help="opt-in vls_module_artifact_fixture executable")
|
|
args = parser.parse_args()
|
|
compiler = shutil.which(args.cxx)
|
|
if compiler is None:
|
|
parser.exit(1, f"GCC executable {args.cxx!r} was not found\n")
|
|
try:
|
|
planner = args.planner.resolve(strict=True) if args.planner else None
|
|
if planner is not None:
|
|
require(planner.is_file() and os.access(planner, os.X_OK), f"planner is not executable: {planner}")
|
|
artifacts = args.artifacts.resolve(strict=True) if args.artifacts else None
|
|
if artifacts is not None:
|
|
require(artifacts.is_file() and os.access(artifacts, os.X_OK),
|
|
f"artifact fixture is not executable: {artifacts}")
|
|
with tempfile.TemporaryDirectory(prefix="vls-gcc-modules-") as temp:
|
|
report = verify(os.path.abspath(compiler), Path(temp).resolve(), planner, artifacts)
|
|
print(json.dumps(report, indent=2))
|
|
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
|
|
parser.exit(1, f"{error}\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|