blob: 6e21d1c4d4e0d41c91a4eb5eefb632355bcbc0fc [file]
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
"""Unit and mutation tests for `ci/check_taxonomy_lockstep.py`."""
from __future__ import annotations
import contextlib
import copy
import io
import json
from pathlib import Path
import shutil
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import check_taxonomy_lockstep as ctl # noqa: E402
REPO_ROOT = Path(__file__).resolve().parent.parent
TAXONOMY = REPO_ROOT / "tools/anneal-corpus-scan/canonical_taxonomy_v1.json"
class TaxonomyLockstepTests(unittest.TestCase):
def _stage_copy(self, tmp: Path) -> tuple[Path, Path]:
"""Copy files inspected by lockstep into an isolated scratch repo."""
root = tmp / "repo"
for rel in (
"trusted/rustc-capture/src", "trusted/lean/Trusted/MirAst",
"trusted/lean/Trusted/MirSemantics", "trusted/lean/lean-toolchain",
"ci/miri_oracle_pin.json", "docs/alpha.md",
"tools/anneal-corpus-scan/canonical_taxonomy_v1.json",
):
src, dst = REPO_ROOT / rel, root / rel
if src.is_dir():
shutil.copytree(src, dst)
else:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
for p in (root, *root.rglob("*")):
p.chmod(p.stat().st_mode | (0o700 if p.is_dir() else 0o200))
return root, root / "tools/anneal-corpus-scan/canonical_taxonomy_v1.json"
def test_live_and_cli_json_exit_codes(self) -> None:
report = ctl.check_lockstep(REPO_ROOT, TAXONOMY)
self.assertTrue(report["ok"], report)
self.assertEqual((report["enums_found"], report["total_constructs"]), (18, 100))
self.assertEqual((report["unmapped"], report["stale"]), ([], []))
with tempfile.TemporaryDirectory(prefix="anneal-tax-cli-") as td, \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
root, tax = self._stage_copy(Path(td))
self.assertEqual(ctl.main(["--root", str(root), "--taxonomy", str(tax), "--json"]), 0)
(root / "trusted/rustc-capture/src/ir.rs").write_text("", "utf-8")
self.assertEqual(ctl.main(["--root", str(root), "--taxonomy", str(tax), "--json"]), 1)
def test_lexer_and_variant_mutations_fail(self) -> None:
self.assertTrue(ctl._has_symbol_decl("a.rs", "pub unsafe fn u() {}\npub const unsafe fn cu() {}\n", "u"))
self.assertTrue(ctl._has_symbol_decl("a.rs", "pub unsafe fn u() {}\npub const unsafe fn cu() {}\n", "cu"))
with tempfile.TemporaryDirectory(prefix="anneal-tax-vars-") as td:
root, tax = self._stage_copy(Path(td))
ir_path = root / "trusted/rustc-capture/src/ir.rs"
rval_lean = root / "trusted/lean/Trusted/MirAst/Rvalues.lean"
term_lean = root / "trusted/lean/Trusted/MirAst/Terminators.lean"
base_ir, base_rval = ir_path.read_text("utf-8"), rval_lean.read_text("utf-8")
base_term = term_lean.read_text("utf-8")
rval_lean.write_text(base_rval.replace(
"inductive UnOp where\n",
'inductive UnOp where\n-- col0 "\n -- see /-\n | @[match_pattern] attrNew\n | private protNew\n -- -/\n', 1,
), "utf-8")
ir_path.write_text(base_ir.replace(
"pub enum UnOp {\n", 'const _: u8 = b\'"\';\npub enum UnOp {\n #[doc = "a//b/*c*/"] #[doc = c"a\\x22}"] #[doc = cr#"}"#]\n', 1), "utf-8")
rep = ctl.check_lockstep(root, tax)
self.assertFalse(rep["ok"])
self.assertEqual((rep["unmapped"], rep["stale"]), (["lean:UnOp::attrNew", "lean:UnOp::protNew"], []))
self.assertEqual(rep["enum_counts"]["ir:UnOp"], 3)
rval_lean.write_text(base_rval.replace("inductive UnOp where", "inductive UnOp\n where | hdrCtor", 1), "utf-8")
self.assertEqual(ctl.check_lockstep(root, tax)["unmapped"], ["lean:UnOp::hdrCtor"])
rval_lean.write_text(base_rval.replace("inductive UnOp where", "inductive UnOp where | sameHdr", 1), "utf-8")
self.assertEqual(ctl.check_lockstep(root, tax)["unmapped"], ["lean:UnOp::sameHdr"])
rval_lean.write_text(base_rval, "utf-8")
ir_path.write_text(base_ir.replace("PanicAbort,", 'PanicAbort,\n /// quote "\n PanicFmt,', 1), "utf-8")
self.assertIn("ir:CoreCallOp::PanicFmt", ctl.check_lockstep(root, tax)["unmapped"])
ir_path.write_text(base_ir, "utf-8")
term_lean.write_text(base_term.replace("| panicAbort", "| panicAbort\n | panicFmt", 1), "utf-8")
self.assertIn("lean:CoreCallOp::panicFmt", ctl.check_lockstep(root, tax)["unmapped"])
def test_all_fail_closed_taxonomy_and_ref_branches(self) -> None:
with tempfile.TemporaryDirectory(prefix="anneal-tax-cases-") as td:
root, tax = self._stage_copy(Path(td))
base_data = json.loads(tax.read_text(encoding="utf-8"))
ir_path = root / "trusted/rustc-capture/src/ir.rs"
lean_rval = root / "trusted/lean/Trusted/MirAst/Rvalues.lean"
base_ir, base_lean = ir_path.read_text("utf-8"), lean_rval.read_text("utf-8")
ext_ref = "trusted/rustc-capture/src/extract.rs"
eof_line = len((REPO_ROOT / ext_ref).read_text().splitlines()) + 1
vm, er = "variant_to_construct_map", "exempt_variants_rationale"
def c0(k: str, v: object): return lambda d: d["constructs"][0].__setitem__(k, v)
def lk(k: str, v: object): return lambda d: d["lockstep"].__setitem__(k, v)
def has(b: str, s: str): return lambda r: any(s in e for e in r[b])
cnt = "lockstep variant count metadata mismatch"
cases = [
("dangling", lambda d: d[vm].__setitem__("ir:UnOp::Not", "x"), has("dangling_targets", "ir:UnOp::Not")),
("non_str", lambda d: d[vm].__setitem__("ir:UnOp::Not", ["x"]), has("ambiguous", "ir:UnOp::Not")),
("stale_key", lambda d: d[vm].__setitem__("ir:UnOp::Ghost", "unop_not_neg"), has("stale", "ir:UnOp::Ghost")),
("stale_rat", lambda d: d["lockstep"][er].__setitem__("ir:UnOp::Not", "x"), has("stale_exempt_rationale", "ir:UnOp::Not")),
("rat_type", lambda d: d["lockstep"][er].__setitem__("ir:Rvalue::Cast", 1), has("exempt_without_rationale", "ir:Rvalue::Cast")),
("no_rat", lambda d: d["lockstep"][er].pop("ir:Rvalue::Cast"), has("exempt_without_rationale", "ir:Rvalue::Cast")),
("sentinel", lk("exempt_sentinel", "X"), has("errors", "exempt_sentinel")),
("inv_err", c0("source_variants", []), lambda r: bool(r["inverse_errors"])),
("adm_bool", c0("admissible_for_coverage", "true"), has("errors", "admissible_for_coverage disagrees")),
("bad_sec", c0("secondary_categories", ["bogus"]), has("errors", "invalid secondary_categories")),
("bad_cat", c0("primary_category", "bogus"), has("errors", "unknown primary_category")),
("bad_vocab", c0("unsafe_class", "bogus"), has("errors", "invalid unsafe_class")),
("meta_cnt", lk("gated_variant_count", 0), has("errors", cnt)),
("mapped_cnt", lk("mapped_to_construct_count", 0), has("errors", cnt)),
("gated_list", lk("gated_ir_enums", ["UnOp"]), has("errors", cnt)),
("enum_cnt", lambda d: d["lockstep"]["enum_counts"].__setitem__("ir:UnOp", 99), has("errors", cnt)),
("split_note", lambda d: d["lockstep"]["variant_split_notes"].__setitem__("ir:UnOp::Not", ["x"]), has("errors", "variant_split_notes")),
("req_cid", lambda d: d.__setitem__("constructs", [c for c in d["constructs"] if c["id"] != "crate_gate_native_libs"]), has("missing_required_constructs", "crate_gate_native_libs")),
("traversal", c0("rustc_capture_ref", "trusted/../Cargo.toml:1"), has("bad_source_refs", "traversal")),
("bad_root", c0("rustc_capture_ref", "trustd/x.rs:1"), has("bad_source_refs", "disallowed ref root")),
("eof_plus1", c0("rustc_capture_ref", f"{ext_ref}:{eof_line}"), has("bad_source_refs", "out of bounds")),
("docs_oob", c0("rustc_capture_ref", "docs/alpha.md:999999"), has("bad_source_refs", "out of bounds")),
("bad_rng", c0("rustc_capture_ref", f"{ext_ref}:1-2-3"), has("bad_source_refs", "malformed range")),
("uni_dig", c0("rustc_capture_ref", "docs/alpha.md:\u00b2"), has("bad_source_refs", "malformed range")),
("miss_sym", c0("lean_semantics_ref", "trusted/lean/Trusted/MirAst/Rvalues.lean#ConstLit"), has("bad_source_refs", "missing symbol")),
("symlink", lambda d: ((root / "trusted/link.rs").symlink_to("rustc-capture/src/ir.rs"), c0("rustc_capture_ref", "trusted/link.rs:1")(d)), has("bad_source_refs", "missing/symlink")),
("pin_err", lambda d: d.__setitem__("lean_toolchain", "leanprover/lean4:v0.0.0"), has("errors", "lean_toolchain mismatch")),
("miss_ir", lambda d: ir_path.write_text(base_ir.replace("pub enum UnOp", "pub enum RemovedOp"), "utf-8"), has("errors", "missing ir enum UnOp")),
("empty_ir", lambda d: ir_path.write_text(base_ir.replace("Not,\n", "").replace("Neg,\n", "").replace("PtrMetadata,\n", ""), "utf-8"), has("errors", "empty ir enum UnOp")),
("miss_lean", lambda d: lean_rval.write_text(base_lean.replace("inductive UnOp where", "inductive GhostOp where"), "utf-8"), has("errors", "missing lean inductive UnOp")),
("empty_lean", lambda d: lean_rval.write_text(base_lean.replace("inductive UnOp where", "inductive UnOp\ninductive Next where | s", 1), "utf-8"), has("errors", "empty lean inductive UnOp")),
]
for label, mutator, pred in cases:
with self.subTest(case=label):
data = copy.deepcopy(base_data)
mutator(data)
tax.write_text(json.dumps(data), encoding="utf-8")
rep = ctl.check_lockstep(root, tax)
self.assertFalse(rep["ok"], f"{label} passed")
self.assertTrue(pred(rep), f"{label} report={rep}")
ir_path.write_text(base_ir, encoding="utf-8")
lean_rval.write_text(base_lean, encoding="utf-8")
(root / "trusted/link.rs").unlink(missing_ok=True)
def test_duplicate_json_key_and_duplicate_source_variant_fail(self) -> None:
with tempfile.TemporaryDirectory(prefix="anneal-tax-dup-") as td:
root, tax = self._stage_copy(Path(td))
data = json.loads(tax.read_text(encoding="utf-8"))
sv0 = data["constructs"][0]["source_variants"][0]
data["constructs"][0]["source_variants"].append(sv0)
tax.write_text(json.dumps(data), encoding="utf-8")
report = ctl.check_lockstep(root, tax)
self.assertFalse(report["ok"])
self.assertTrue(any("duplicate source_variants" in e for e in report["inverse_errors"]))
tax.write_text('{"a": 1, "a": 2}', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "duplicate JSON key"):
ctl.check_lockstep(root, tax)
data = json.loads(TAXONOMY.read_text(encoding="utf-8"))
data["vocabularies"]["status"]["UNUSED"] = "u"
data["status_counts"]["UNUSED"] = 0
tax.write_text(json.dumps(data), encoding="utf-8")
self.assertTrue(ctl.check_lockstep(root, tax)["ok"])
if __name__ == "__main__":
unittest.main()