| #!/usr/bin/env python3 | |
| # 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. | |
| """Check gated AST/IR enum lockstep against Anneal's MIR coverage taxonomy. | |
| Validates syntactic completeness between Anneal's 9 gated capture IR enums in | |
| `trusted/rustc-capture/src/ir.rs`, the 9 corresponding Lean AST inductive types | |
| under `trusted/lean/Trusted/MirAst/`, and | |
| `tools/anneal-corpus-scan/canonical_taxonomy_v1.json`. Checks exact variant-set | |
| to map-key parity, inverse `source_variants`, exemption rationales, closed | |
| vocabulary allowlists, toolchain pins, summary/per-enum counts, and file, | |
| declaration (`#sym`), plus bounds checks for refs under `trusted/` and `docs/`. | |
| Not enforced here (deferred to follow-up semantic parity checks): | |
| - Ungated MIR AST families (`Operand`, `PlaceElem`/`ProjectionElem`, `ConstLit`, | |
| `AssertKind`, `UnwindAction`), which remain cataloged at construct granularity. | |
| - Cross-language semantic pairing between individual Rust and Lean variants. | |
| - Code-level semantic equivalence beyond declaration-anchor presence. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sys | |
| REPO_ROOT = Path(__file__).resolve().parent.parent | |
| DEFAULT_TAXONOMY = REPO_ROOT / "tools/anneal-corpus-scan/canonical_taxonomy_v1.json" | |
| IR_ENUMS = ("Statement", "Terminator", "Rvalue", "CastKind", "BinOp", | |
| "UnOp", "Ty", "CoreCallOp", "SysrootNumKind") | |
| LEAN_INDS = ("StatementKind", "TerminatorKind", "Rvalue", "CastKind", "BinOp", | |
| "UnOp", "MirTy", "CoreCallOp", "SysrootNumKind") | |
| EXEMPT_SENTINEL = "INTENTIONALLY_EXEMPT_META" | |
| # Whole-crate/item safety constructs with no AST/IR enum variant that must stay | |
| # present in `constructs[]`. | |
| REQUIRED_CONSTRUCTS = ("item_unsafe_trait_or_impl", "crate_gate_native_libs") | |
| CORE_UNSAFE_CLASSES = frozenset({ | |
| "none", "raw_ptr_deref", "ffi_extern_unsafe_fn", "union_field_access", | |
| "static_mut_thread_local", "inline_asm", "transmute_ptr_int_cast", | |
| "other_unsafe_attr_or_trait", | |
| }) | |
| REF_RE = re.compile( | |
| r"(?<![A-Za-z0-9_.\-/])([A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)+\.(?:rs|lean|md))" | |
| r"(?::([^\s;#()]+))?(?:#([A-Za-z0-9_.'-]+(?:,[A-Za-z0-9_.'-]+)*))?" | |
| ) | |
| RUST_TOK_RE = re.compile( | |
| r'//[^\n]*|/\*|(?<![A-Za-z0-9_])[bc]?r(#*)"|(?<![A-Za-z0-9_])[bc]?"(?:\\.|[^"\\])*"' | |
| r"|(?<![A-Za-z0-9_'])b?'(?:\\.|[^'\\])'" | |
| ) | |
| RUST_BLOCK_RE = re.compile(r"/\*|\*/") | |
| LEAN_TOK_RE = re.compile( | |
| r'--[^\n]*|/-|"(?:\\.|[^"\\])*"|(?<![A-Za-z0-9_\'])' | |
| r"'(?:\\.|[^'\\])'" | |
| ) | |
| LEAN_BLOCK_RE = re.compile(r"/-|-/") | |
| def _read_regular_utf8(path: Path) -> str: | |
| if path.is_symlink() or not path.is_file(): | |
| raise ValueError(f"expected regular file, got {path}") | |
| return path.read_text(encoding="utf-8") | |
| def _strip_comments_and_strings( | |
| src: str, tok_re: re.Pattern[str], block_re: re.Pattern[str], block_open: str | |
| ) -> str: | |
| """Fast single-pass comment and string stripper preserving newlines.""" | |
| out: list[str] = [] | |
| pos, n = 0, len(src) | |
| while pos < n: | |
| m = tok_re.search(src, pos) | |
| if not m: | |
| out.append(src[pos:]) | |
| break | |
| out.append(src[pos:m.start()]) | |
| tok = m.group(0) | |
| if tok == block_open: | |
| depth, cur = 1, m.end() | |
| while depth > 0: | |
| bm = block_re.search(src, cur) | |
| if not bm: | |
| out.append("\n" * src[m.end():].count("\n")) | |
| cur = n | |
| break | |
| out.append("\n" * src[cur:bm.start()].count("\n")) | |
| depth += 1 if bm.group(0) == block_open else -1 | |
| cur = bm.end() | |
| out.append(" ") | |
| pos = cur | |
| elif m.lastindex and m.group(1) is not None: | |
| end_tok = '"' + m.group(1) | |
| j = src.find(end_tok, m.end()) | |
| out.append('""') | |
| if j == -1: | |
| out.append("\n" * src[m.end():].count("\n")) | |
| pos = n | |
| else: | |
| out.append("\n" * src[m.end():j].count("\n")) | |
| pos = j + len(end_tok) | |
| else: | |
| if not tok.startswith(("//", "--")) and tok.endswith(("'", '"')): | |
| out.append(("''" if tok.endswith("'") else '""') + "\n" * tok.count("\n")) | |
| pos = m.end() | |
| return "".join(out) | |
| def _strip_rust_attrs(body: str) -> str: | |
| out: list[str] = [] | |
| i = 0 | |
| while i < len(body): | |
| if body.startswith("#[", i): | |
| depth, j = 0, i + 1 | |
| while j < len(body): | |
| depth += 1 if body[j] == "[" else (-1 if body[j] == "]" else 0) | |
| if depth == 0: | |
| break | |
| j += 1 | |
| i = j + 1 | |
| continue | |
| out.append(body[i]) | |
| i += 1 | |
| return "".join(out) | |
| def rust_enum_variants(src: str, name: str) -> list[str] | None: | |
| """Parse variant identifiers of `pub enum <name>` from Rust source.""" | |
| cleaned = _strip_comments_and_strings(src, RUST_TOK_RE, RUST_BLOCK_RE, "/*") | |
| m = re.search(r"\bpub\s+enum\s+" + re.escape(name) + r"\b[^{;]*\{", cleaned) | |
| if not m: | |
| return None | |
| i, depth, pd, start, chunks = m.end(), 1, 0, m.end(), [] | |
| while i < len(cleaned) and depth > 0: | |
| c = cleaned[i] | |
| if c == "{": | |
| depth += 1 | |
| elif c == "}": | |
| depth -= 1 | |
| if depth == 0: | |
| chunks.append(cleaned[start:i]) | |
| break | |
| elif c in "([": | |
| pd += 1 | |
| elif c in ")]": | |
| pd -= 1 | |
| elif c == "," and depth == 1 and pd == 0: | |
| chunks.append(cleaned[start:i]) | |
| start = i + 1 | |
| i += 1 | |
| return [vm.group(1) for ch in chunks | |
| if (vm := re.match(r"([A-Za-z_][A-Za-z0-9_]*)", _strip_rust_attrs(ch).strip()))] | |
| def lean_inductive_ctors(files: list[Path], name: str) -> list[str] | None: | |
| """Parse constructor identifiers of `inductive <name>` across Lean.""" | |
| ctor_re = re.compile(r"\|\s*(?:@\[[^\]]*\]\s*|(?:private|protected)\s+)*([A-Za-z_][A-Za-z0-9_']*)") | |
| for path in files: | |
| lines = _strip_comments_and_strings( | |
| _read_regular_utf8(path), LEAN_TOK_RE, LEAN_BLOCK_RE, "/-" | |
| ).split("\n") | |
| for idx, line in enumerate(lines): | |
| if re.match(r"^\s*inductive\s+" + re.escape(name) + r"\b", line): | |
| mw0 = re.search(r"\bwhere\b", line) | |
| seen_where = mw0 is not None | |
| ctors = ctor_re.findall(line[mw0.end():]) if mw0 else [] | |
| base = len(line) - len(line.lstrip()) | |
| for nxt in lines[idx + 1:]: | |
| stripped = nxt.lstrip() | |
| if not stripped: | |
| continue | |
| ind = len(nxt) - len(stripped) | |
| if ind <= base and not stripped.startswith("|") and not ( | |
| not seen_where and re.match(r"where\b", stripped) | |
| ): | |
| break | |
| if not seen_where and (mw := re.search(r"\bwhere\b", stripped)): | |
| seen_where = True | |
| ctors.extend(ctor_re.findall(stripped[mw.end():])) | |
| elif stripped.startswith("|"): | |
| ctors.extend(ctor_re.findall(nxt)) | |
| return ctors | |
| return None | |
| def _has_symlink_component(root: Path, rel: str) -> bool: | |
| cur = root | |
| return any((cur := cur / part).is_symlink() for part in Path(rel).parts) | |
| def _has_symbol_decl(rel: str, text: str, sym: str) -> bool: | |
| if rel.endswith(".rs"): | |
| pat = (r"(?m)^\s*(?:pub(?:\([^)]+\))?\s+)?(?:default\s+|const\s+|async\s+)*" | |
| r"(?:unsafe\s+)?(?:extern(?:\s+\"[^\"]*\")?\s+)?" | |
| r"(?:fn|enum|struct|const|static|trait|type|macro_rules!)\s+" | |
| + re.escape(sym) + r"(?![A-Za-z0-9_])") | |
| return bool(re.search(pat, text)) | |
| if rel.endswith(".lean"): | |
| pat = (r"(?m)^(?:(?:noncomputable|private|partial|protected|scoped|local)\s+)*" | |
| r"(?:def|inductive|structure|abbrev|theorem|instance)\s+(?:[A-Za-z0-9_]+\.)*" | |
| + re.escape(sym) + r"(?![A-Za-z0-9_'])") | |
| return bool(re.search(pat, text)) | |
| return sym.lower() in { | |
| re.sub(r"[^a-z0-9]+", "-", h.lower()).strip("-") | |
| for h in re.findall(r"(?m)^#+\s+(.+)$", text) | |
| } | |
| def _check_refs(root: Path, constructs: list[dict]) -> tuple[int, list[str]]: | |
| checked, bad, cache = 0, [], {} | |
| for c in constructs: | |
| for key in ("rustc_capture_ref", "lean_semantics_ref"): | |
| val = c.get(key) | |
| if not isinstance(val, str): | |
| continue | |
| if re.search(r"(?:^|[/:;#\s])\.\.(?:$|[/:;#\s])", val): | |
| bad.append(f"{c['id']}:{key}: traversal in {val}") | |
| for m in REF_RE.finditer(val): | |
| checked += 1 | |
| rel = m.group(1) | |
| if ".." in Path(rel).parts: | |
| bad.append(f"{c['id']}:{key}: traversal in {rel}") | |
| continue | |
| if not rel.startswith(("trusted/", "docs/")): | |
| bad.append(f"{c['id']}:{key}: disallowed ref root {rel}") | |
| continue | |
| target = root / rel | |
| if _has_symlink_component(root, rel) or not target.is_file(): | |
| bad.append(f"{c['id']}:{key}: missing/symlink {rel}") | |
| continue | |
| text = cache.setdefault(rel, target.read_text(encoding="utf-8", errors="replace")) | |
| nlines = len(text.splitlines()) | |
| if nlines < 1: | |
| bad.append(f"{c['id']}:{key}: empty file {rel}") | |
| continue | |
| for sym in (m.group(3) or "").split(","): | |
| if sym and not _has_symbol_decl(rel, text, sym): | |
| bad.append(f"{c['id']}:{key}: missing symbol {rel}#{sym}") | |
| for rng in (m.group(2) or "").split(","): | |
| if not rng: | |
| continue | |
| parts = rng.split("-") | |
| if len(parts) not in (1, 2) or not all(p.isascii() and p.isdigit() for p in parts): | |
| bad.append(f"{c['id']}:{key}: {rel}:{rng} malformed range") | |
| continue | |
| nums = [int(x) for x in parts] | |
| if any(x < 1 or x > nlines for x in nums) or (len(nums) == 2 and nums[0] > nums[1]): | |
| bad.append(f"{c['id']}:{key}: {rel}:{rng} out of bounds (lines={nlines})") | |
| return checked, bad | |
| def _reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict[str, object]: | |
| out: dict[str, object] = {} | |
| for k, v in pairs: | |
| if k in out: | |
| raise ValueError(f"duplicate JSON key {k!r}") | |
| out[k] = v | |
| return out | |
| def _validate_vocabularies(tax: dict[str, object], errors: list[str]) -> dict[str, set[str]]: | |
| raw = tax.get("vocabularies") | |
| fields = ("status", "oracle_coverage", "correspondence_tier", "unsafe_class", "mir_family") | |
| if not isinstance(raw, dict): | |
| errors.append("missing or invalid vocabularies mapping") | |
| return {k: set() for k in fields} | |
| vocab_sets: dict[str, set[str]] = {} | |
| for field in fields: | |
| sub = raw.get(field) | |
| bad = not isinstance(sub, dict) or not sub or any( | |
| not isinstance(k, str) or not isinstance(v, str) or not v.strip() | |
| for k, v in sub.items() | |
| ) | |
| vocab_sets[field] = set() if bad else set(sub) | |
| if bad: | |
| errors.append(f"invalid vocabularies.{field} definition map") | |
| if not CORE_UNSAFE_CLASSES <= vocab_sets["unsafe_class"]: | |
| errors.append("vocabularies.unsafe_class missing core unsafe classes") | |
| return vocab_sets | |
| def _check_pins(root: Path, tax: dict[str, object], errors: list[str]) -> None: | |
| try: | |
| lean_pin = _read_regular_utf8(root / "trusted/lean/lean-toolchain").strip() | |
| if tax.get("lean_toolchain") != lean_pin: | |
| errors.append(f"lean_toolchain mismatch: {tax.get('lean_toolchain')!r} != {lean_pin!r}") | |
| except (OSError, ValueError) as exc: | |
| errors.append(f"unable to read lean-toolchain: {exc}") | |
| try: | |
| miri_pin = json.loads( | |
| _read_regular_utf8(root / "ci/miri_oracle_pin.json"), | |
| object_pairs_hook=_reject_duplicate_keys, | |
| ) | |
| commit = str(miri_pin["rustc_commit"]) | |
| if f"[rustc commit {commit}]" not in str(tax.get("rust_toolchain", "")): | |
| errors.append(f"rust_toolchain missing pinned rustc commit {commit}") | |
| except (OSError, ValueError, KeyError, json.JSONDecodeError) as exc: | |
| errors.append(f"unable to read ci/miri_oracle_pin.json: {exc}") | |
| def _collect_variants( | |
| names: tuple[str, ...], parser, prefix: str, label: str, | |
| errors: list[str], enum_counts: dict[str, int], live: list[str], | |
| ) -> None: | |
| for name in names: | |
| vs = parser(name) | |
| if vs is None: | |
| errors.append(f"missing {label} {name}") | |
| elif not vs: | |
| errors.append(f"empty {label} {name}") | |
| elif len(set(vs)) != len(vs): | |
| errors.append(f"duplicate entry in {prefix}:{name}") | |
| else: | |
| enum_counts[f"{prefix}:{name}"] = len(vs) | |
| live.extend(f"{prefix}:{name}::{v}" for v in vs) | |
| def check_lockstep(root: Path, taxonomy_path: Path) -> dict[str, object]: | |
| """Validate AST/IR enum lockstep and internal taxonomy invariants.""" | |
| tax = json.loads(_read_regular_utf8(taxonomy_path), object_pairs_hook=_reject_duplicate_keys) | |
| constructs, vmap = tax["constructs"], tax["variant_to_construct_map"] | |
| categories = set(tax.get("categories", {})) | |
| cids = [c["id"] for c in constructs] | |
| cid_set, errors = set(cids), [] | |
| if len(cids) != len(cid_set): | |
| errors.append("duplicate construct id in constructs[]") | |
| vocabs = _validate_vocabularies(tax, errors) | |
| _check_pins(root, tax, errors) | |
| ir_src = _read_regular_utf8(root / "trusted/rustc-capture/src/ir.rs") | |
| lean_files = sorted((root / "trusted/lean/Trusted/MirAst").glob("*.lean")) | |
| live, enum_counts = [], {} | |
| _collect_variants(IR_ENUMS, lambda n: rust_enum_variants(ir_src, n), "ir", "ir enum", errors, enum_counts, live) | |
| _collect_variants(LEAN_INDS, lambda n: lean_inductive_ctors(lean_files, n), "lean", "lean inductive", errors, enum_counts, live) | |
| lset, kset = set(live), set(vmap) | |
| unmapped, stale = sorted(lset - kset), sorted(kset - lset) | |
| ambiguous = sorted(k for k, v in vmap.items() if not isinstance(v, str)) | |
| dangling = sorted( | |
| k for k, v in vmap.items() | |
| if isinstance(v, str) and v != EXEMPT_SENTINEL and v not in cid_set | |
| ) | |
| meta = tax.get("lockstep", {}) | |
| if meta.get("exempt_sentinel") != EXEMPT_SENTINEL: | |
| errors.append("lockstep.exempt_sentinel mismatch") | |
| rationale = meta.get("exempt_variants_rationale", {}) | |
| if not isinstance(rationale, dict): | |
| errors.append("invalid lockstep.exempt_variants_rationale") | |
| rationale = {} | |
| exempt = sorted(k for k, v in vmap.items() if v == EXEMPT_SENTINEL) | |
| exempt_no_rat = [ | |
| k for k in exempt if not isinstance(rationale.get(k), str) or not rationale[k].strip() | |
| ] | |
| stale_rat = sorted(set(rationale) - set(exempt)) | |
| inv_err, inv, sub_ids = [], {}, [] | |
| for c in constructs: | |
| cid = c["id"] | |
| if c["primary_category"] not in categories: | |
| errors.append(f"{cid}: unknown primary_category {c['primary_category']}") | |
| secs = c.get("secondary_categories") | |
| if not isinstance(secs, list) or any( | |
| not isinstance(s, str) or s not in categories for s in secs | |
| ): | |
| errors.append(f"{cid}: invalid secondary_categories {secs!r}") | |
| for f in ("status", "oracle_coverage", "correspondence_tier", "unsafe_class", "mir_family"): | |
| if c.get(f) not in vocabs[f]: | |
| errors.append(f"{cid}: invalid {f} {c.get(f)!r}") | |
| adm = c.get("admissible_for_coverage") | |
| if not isinstance(adm, bool) or adm != (c["status"] == "SUPPORTED_END_TO_END"): | |
| errors.append(f"{cid}: admissible_for_coverage disagrees with status") | |
| for sub in c.get("atomic_subcodes") or []: | |
| sub_ids.append(sub["sub_id"]) | |
| if sub["category"] not in categories: | |
| errors.append(f"{cid}/{sub['sub_id']}: unknown category {sub['category']}") | |
| for sf in ("unsafe_class", "oracle_coverage"): | |
| if sub.get(sf) not in vocabs[sf]: | |
| errors.append(f"{cid}/{sub['sub_id']}: invalid {sf} {sub.get(sf)!r}") | |
| svs = c.get("source_variants") or [] | |
| if len(svs) != len(set(svs)): | |
| inv_err.append(f"{cid} has duplicate source_variants") | |
| for sv in svs: | |
| inv.setdefault(sv, set()).add(cid) | |
| if vmap.get(sv) != cid: | |
| inv_err.append(f"{cid} lists {sv} but map has {vmap.get(sv)}") | |
| if len(sub_ids) != len(set(sub_ids)): | |
| errors.append("duplicate atomic sub_id") | |
| for k, v in vmap.items(): | |
| if isinstance(v, str) and v != EXEMPT_SENTINEL and v not in inv.get(k, set()): | |
| inv_err.append(f"map {k}->{v} missing from constructs[{v}].source_variants") | |
| if tax.get("total_constructs") != len(constructs): | |
| errors.append("total_constructs count mismatch") | |
| for field, key in (("status_counts", "status"), ("oracle_coverage_counts", "oracle_coverage"), | |
| ("correspondence_tier_counts", "correspondence_tier")): | |
| cmap, cnt = tax.get(field), Counter(c[key] for c in constructs) | |
| if cmap != {k: cnt.get(k, 0) for k in vocabs[key]}: | |
| errors.append(f"{field} count mismatch") | |
| if isinstance(cmap, dict) and set(cmap) != vocabs[key]: | |
| errors.append(f"{field} keys diverge from vocabularies.{key}") | |
| if (meta.get("gated_variant_count") != len(live) | |
| or meta.get("mapped_to_construct_count") != len(vmap) - len(exempt) | |
| or meta.get("intentionally_exempt_meta_count") != len(exempt) | |
| or meta.get("gated_ir_enums") != list(IR_ENUMS) | |
| or meta.get("gated_lean_inductives") != list(LEAN_INDS) | |
| or meta.get("enum_counts") != enum_counts): | |
| errors.append("lockstep variant count metadata mismatch") | |
| for sv, targets in (meta.get("variant_split_notes") or {}).items(): | |
| if sv not in vmap or not isinstance(targets, list) or not all( | |
| isinstance(t, str) and t in cid_set for t in targets | |
| ): | |
| errors.append(f"invalid variant_split_notes entry for {sv}") | |
| nrefs, bad_refs = _check_refs(root, constructs) | |
| missing_req = [cid for cid in REQUIRED_CONSTRUCTS if cid not in cid_set] | |
| ok = (not errors and not unmapped and not stale and not ambiguous and not dangling | |
| and not exempt_no_rat and not stale_rat and not inv_err and not bad_refs | |
| and not missing_req and len(enum_counts) == len(IR_ENUMS) + len(LEAN_INDS)) | |
| return { | |
| "ok": ok, "enums_found": len(enum_counts), "enum_counts": enum_counts, | |
| "live_variants": len(live), "map_keys": len(vmap), "exempt": len(exempt), | |
| "total_constructs": len(constructs), "source_refs_checked": nrefs, | |
| "unmapped": unmapped, "stale": stale, "ambiguous": ambiguous, | |
| "dangling_targets": dangling, "exempt_without_rationale": exempt_no_rat, | |
| "stale_exempt_rationale": stale_rat, "inverse_errors": inv_err, | |
| "bad_source_refs": bad_refs, "missing_required_constructs": missing_req, | |
| "errors": errors, | |
| } | |
| def main(argv: list[str] | None = None) -> int: | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("--root", type=Path, default=REPO_ROOT) | |
| ap.add_argument("--taxonomy", type=Path, default=DEFAULT_TAXONOMY) | |
| ap.add_argument("--json", action="store_true", help="Emit full JSON report.") | |
| args = ap.parse_args(argv) | |
| report = check_lockstep(args.root, args.taxonomy) | |
| if args.json: | |
| print(json.dumps(report, indent=2, sort_keys=True)) | |
| elif report["ok"]: | |
| print(f"Taxonomy lockstep OK: {report['enums_found']} enums, {report['live_variants']} variants, " | |
| f"{report['total_constructs']} constructs, {report['source_refs_checked']} source refs.") | |
| else: | |
| print("Taxonomy lockstep FAILED:", file=sys.stderr) | |
| for key in ("errors", "unmapped", "stale", "ambiguous", "dangling_targets", | |
| "exempt_without_rationale", "stale_exempt_rationale", | |
| "inverse_errors", "bad_source_refs", "missing_required_constructs"): | |
| if report[key]: | |
| print(f" {key}: {report[key]}", file=sys.stderr) | |
| return 0 if report["ok"] else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) |