Coverage for scripts/check_axioms.py: 100%
64 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Which axioms do the Lean proofs rest on? (V6.6.4)
3`lake build` accepts a theorem that uses `sorry` as a warning, and a proof can lean on `native_decide` (which trusts the compiler) or an added axiom without saying so. This asks Lean for
4`#print axioms` of every theorem in `formal/AetherFormal/*.lean` and fails on anything beyond Lean's three standard ones. The known exceptions are listed with their reason below.
6 python scripts/check_axioms.py # needs a built formal/ (a Codespace; `aq prove` first)
7 python scripts/check_axioms.py --list # only print the theorems it would check
8"""
10from __future__ import annotations
12import re
13import subprocess
14import sys
15from pathlib import Path
17ROOT = Path(__file__).resolve().parents[1]
18FORMAL = ROOT / "formal"
19STANDARD = {"propext", "Classical.choice", "Quot.sound"}
20# A proof that trusts the compiler is allowed only where it is named here with its reason (a `native_decide` adds `Lean.ofReduceBool` and one axiom of its own, `<theorem>._native.native_decide.ax_n_m`);
21# any other extra axiom, and the same trust in any other theorem, fails.
22ALLOWED_NATIVE = {
23 "AetherFormal.BookNeutrality.counter_net": "the sector-cap counterexample is a computed finding, not a general result (formal/README.md, Findings)",
24 "AetherFormal.BookNeutrality.sector_cap_counterexample": "built on counter_net",
25}
26ALLOWED_EXTRA = {"Lean.ofReduceBool": "native_decide, in the two theorems of ALLOWED_NATIVE only"}
27NATIVE_AXIOM = re.compile(r".*\._native\.native_decide\.ax_\d+_\d+$")
28NAMESPACE = re.compile(r"^namespace\s+(\S+)", re.M)
29THEOREM = re.compile(r"^(?:@\[[^\]]*\]\s*)?(?:protected\s+)?(?:theorem|lemma)\s+([A-Za-z0-9_'.]+)", re.M)
32def theorems(root: Path = FORMAL) -> list[str]:
33 """Fully qualified names of every theorem and lemma, by file namespace. A private one is skipped (it cannot be printed from outside)."""
34 names: list[str] = []
35 for path in sorted((root / "AetherFormal").glob("*.lean")):
36 text = path.read_text(encoding="utf-8")
37 if path.name in ("GenCases.lean", "Axioms.lean"):
38 continue
39 namespaces = NAMESPACE.findall(text)
40 prefix = namespaces[0] if namespaces else ""
41 for match in THEOREM.finditer(text): # THEOREM is anchored at a line start, so a `private theorem` never matches
42 names.append(f"{prefix}.{match.group(1)}" if prefix else match.group(1))
43 return names
46def parse_axioms(output: str) -> dict[str, set[str]]:
47 """{theorem: axioms} from `#print axioms` output: `'name' depends on axioms: [a, b]` or `'name' does not depend on any axioms`."""
48 found: dict[str, set[str]] = {}
49 # Lean wraps a long axiom list over several lines, and a name may itself hold an apostrophe, so this reads the whole text and ends the name at the first `' depends`.
50 for match in re.finditer(r"'([^\n]*?)' depends on axioms: \[(.*?)\]", output, re.S):
51 found[match.group(1)] = {item.strip() for item in match.group(2).replace("\n", " ").split(",") if item.strip()}
52 for match in re.finditer(r"'([^\n]*?)' does not depend on any axioms", output):
53 found[match.group(1)] = set()
54 return found
57def violations(found: dict[str, set[str]], expected: list[str]) -> list[str]:
58 problems = []
59 for name in expected:
60 if name not in found:
61 problems.append(f"{name}: Lean printed nothing for it")
62 continue
63 extra = found[name] - STANDARD
64 if name in ALLOWED_NATIVE:
65 extra = {axiom for axiom in extra if axiom not in ALLOWED_EXTRA and not NATIVE_AXIOM.match(axiom)}
66 if extra:
67 problems.append(f"{name} rests on {sorted(extra)}")
68 if "sorryAx" in found[name]:
69 problems.append(f"{name} uses sorry")
70 return problems
73def main(argv: list[str] | None = None) -> int:
74 args = list(sys.argv[1:] if argv is None else argv)
75 names = theorems()
76 if "--list" in args:
77 print("\n".join(names))
78 return 0
79 probe = FORMAL / "AxiomProbe.lean"
80 probe.write_text("import AetherFormal\n\n" + "\n".join(f"#print axioms {name}" for name in names) + "\n", encoding="utf-8", newline="\n")
81 try:
82 result = subprocess.run(["lake", "env", "lean", str(probe.name)], cwd=FORMAL, capture_output=True, text=True, timeout=3600, check=False)
83 finally:
84 probe.unlink(missing_ok=True)
85 found = parse_axioms(result.stdout)
86 problems = violations(found, names)
87 for line in problems:
88 print(f"axiom check: {line}", file=sys.stderr)
89 print(f"axiom check: {len(names)} theorems, {len(problems)} problem(s); extra axioms seen: {sorted({axiom for value in found.values() for axiom in value} - STANDARD)}")
90 return 1 if problems or result.returncode not in (0,) else 0
93if __name__ == "__main__":
94 raise SystemExit(main())