#!/usr/bin/env python3 """The `challenge` check: a push may change how the theorems are proved, never what is proved or how it is judged. Usage: challenge.py [] This is leanprover-community/riemann-hypothesis's `challenge-files.yml` ("Comparator challenge files and build configuration are unchanged"), made a check of this site. Upstream compares a pull request's head with the commit it branched off; here the approved version of the project is the reference, and `frozen.json`, beside this script in that version, records what it holds: - `files`: the Comparator challenge, its configuration and the statements they import, each by its SHA-256. A commit fails if any of them is missing or differs (Comparator would accept a change there, since both sides would see it). - `lakefile`: `lakefile.toml` as approved, without the keys a pull request may change (FREE: `leanOptions`, `defaultTargets`, `lean_exe`, `[cache]`, and each `require`'s `rev`). The libraries, their sources, Lean's arguments and the dependencies' names and addresses stay as they are, so `Challenge` and the solution keep naming these files. - `manifest`: the settings of `lake-manifest.json` (everything but its packages) and where Mathlib comes from. It also fails a commit that adds `lakefile.lean` (Lake reads it instead of `lakefile.toml`), lists a package that is not a Git repository of leanprover or leanprover-community on GitHub nor one in `trusted`, names a toolchain that is not a release of leanprover/lean4, adds files under `.lake/`, or holds a symbolic link among the frozen files; and, as upstream's build does, one that puts `sorry`, `admit`, an `axiom`, `native_decide`, `implemented_by` or `extern` in its Lean source (comments and strings skipped). A Mathlib or toolchain bump passes: it changes `rev`, the packages' revisions and `lean-toolchain`. The `build` check then needs a Lean image for it. It reads files only and runs nothing from the commit. Standard library only, Python 3.11 or newer (tomllib). Exit 0 passes, 1 fails. """ from __future__ import annotations import hashlib import json import os import re import sys import tomllib from pathlib import Path FREE = {"leanOptions", "defaultTargets", "lean_exe", "cache"} TRUSTED = ("https://github.com/leanprover-community/", "https://github.com/leanprover/") TOOLCHAIN = re.compile(r"leanprover/lean4:v[0-9][0-9A-Za-z.+-]*") FORBIDDEN = [ (re.compile(r"\bsorry\b"), "sorry"), (re.compile(r"\bsorryAx\b"), "sorryAx"), # the axiom behind sorry, which \bsorry\b does not see # the tactic, not a field or projection that happens to be called admit (`admit : P x`, `h.admit`, `admit (x)`) (re.compile(r"(? str: """Lean source without its comments and string literals: `--` to the end of the line, nested `/- … -/`, and "…" with its escapes. What is left is code, so a docstring that mentions `sorry` is not a `sorry`.""" out: list[str] = [] i, n, depth = 0, len(text), 0 while i < n: if depth: if text.startswith("/-", i): depth += 1 i += 2 elif text.startswith("-/", i): depth -= 1 i += 2 else: if text[i] == "\n": out.append("\n") i += 1 continue if text.startswith("/-", i): depth = 1 i += 2 elif text.startswith("--", i): j = text.find("\n", i) i = n if j < 0 else j elif text[i] == '"': i += 1 while i < n and text[i] != '"': i += 2 if text[i] == "\\" else 1 i += 1 elif text[i] == "'" and i + 2 < n and text[i + 2] == "'": i += 3 # a character literal such as '"' else: out.append(text[i]) i += 1 return "".join(out) def sha256(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for block in iter(lambda: f.read(1 << 20), b""): h.update(block) return h.hexdigest() def lakefile_view(text: str) -> dict: """lakefile.toml without what a pull request may change: upstream's `lakefile()`.""" config = tomllib.loads(text) view = {key: value for key, value in config.items() if key not in FREE} view["require"] = [{key: value for key, value in require.items() if key != "rev"} for require in config.get("require", [])] return view def manifest_view(text: str) -> tuple[dict, dict]: """lake-manifest.json's settings, and its packages by name: upstream's `manifest()`.""" data = json.loads(text) return {key: value for key, value in data.items() if key != "packages"}, {p.get("name"): p for p in data.get("packages", [])} def canonical(value) -> str: return json.dumps(value, sort_keys=True, ensure_ascii=False) def frozen_of(root: Path, files: list[str], trusted: list[str]) -> dict: """What frozen.json holds for a tree: run on the approved version to make it (`--freeze`).""" settings, packages = manifest_view((root / "lake-manifest.json").read_text(encoding="utf-8")) return { "files": {path: sha256(root / path) for path in files}, "lakefile": json.loads(canonical(lakefile_view((root / "lakefile.toml").read_text(encoding="utf-8")))), "manifest": {"settings": settings, "mathlib": (packages.get("mathlib") or {}).get("url")}, "trusted": trusted, } def lean_files(root: Path): for here, dirs, names in os.walk(root): dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS) for name in sorted(names): if name.endswith(".lean"): yield Path(here) / name def check(root: Path, frozen: dict) -> tuple[list[str], str]: wrong: list[str] = [] for rel, want in sorted(frozen["files"].items()): p = root / rel if p.is_symlink() or (p.exists() and not p.is_file()): wrong.append(f"{rel} is not a plain file: it is a Comparator challenge file") elif not p.is_file(): wrong.append(f"{rel} is missing: it is a Comparator challenge file") elif sha256(p) != want: wrong.append(f"{rel} differs from the approved version: it is a Comparator challenge file") if (root / "lakefile.lean").exists(): wrong.append("lakefile.lean is added: Lake would read it instead of lakefile.toml") try: lake = root / "lakefile.toml" if not lake.is_file() or canonical(lakefile_view(lake.read_text(encoding="utf-8"))) != canonical(frozen["lakefile"]): wrong.append("lakefile.toml changes other than in a require's rev, leanOptions, defaultTargets, lean_exe or [cache]") settings, packages = manifest_view((root / "lake-manifest.json").read_text(encoding="utf-8")) if canonical(settings) != canonical(frozen["manifest"]["settings"]): wrong.append("lake-manifest.json: its settings change") if (packages.get("mathlib") or {}).get("url") != frozen["manifest"]["mathlib"]: wrong.append("lake-manifest.json: where Mathlib comes from changes") for name, package in packages.items(): url = str(package.get("url")) if package.get("type") != "git" or not (url.startswith(TRUSTED) or url in frozen.get("trusted", [])): wrong.append(f"lake-manifest.json: the package {name} is not a Git repository of leanprover-community or leanprover on GitHub, nor one this project trusts") except (OSError, ValueError, tomllib.TOMLDecodeError, AttributeError) as problem: wrong.append(f"the build configuration could not be read: {problem}") toolchain = (root / "lean-toolchain").read_text(encoding="utf-8").strip() if (root / "lean-toolchain").is_file() else "" if not TOOLCHAIN.fullmatch(toolchain): wrong.append(f"lean-toolchain: {toolchain!r} is not a release of leanprover/lean4") if (root / ".lake").exists(): wrong.append(".lake/ is added: Lake keeps what it builds and fetches there") files = lines = 0 for p in lean_files(root): rel = p.relative_to(root).as_posix() text = p.read_text(encoding="utf-8", errors="replace") files += 1 lines += text.count("\n") if rel in frozen["files"] or not ANY.search(text): continue code = strip(text) for rx, what in FORBIDDEN: m = rx.search(code) if m: wrong.append(f"{rel}:{code.count(chr(10), 0, m.start()) + 1} uses {what}") break return wrong, f"{len(frozen['files'])} challenge files and the build configuration as approved; {files} Lean files, {lines} lines, toolchain {toolchain}" def main(argv: list[str]) -> int: if len(argv) >= 2 and argv[1] == "--freeze": # challenge.py --freeze ... [--trust ]...: print frozen.json for that tree args, trusted = argv[3:], [] while "--trust" in args: i = args.index("--trust") trusted.append(args[i + 1]) del args[i:i + 2] print(json.dumps(frozen_of(Path(argv[2]), args, trusted), indent=2, ensure_ascii=False)) return 0 if len(argv) < 2: print(__doc__.strip().splitlines()[2]) return 2 root = Path(argv[1]) frozen = json.loads((Path(argv[2]) if len(argv) > 2 else Path(__file__).with_name("frozen.json")).read_text(encoding="utf-8")) if not any(lean_files(root)): print("Nothing to check yet: the commit holds no Lean file.") return 0 wrong, said = check(root, frozen) for w in wrong[:50]: print(w) if len(wrong) > 50: print(f"… and {len(wrong) - 50} more") if wrong: print("These files say what the proof is judged against and how it is built, and a pull request may not change them;") print("if one has to, open an issue titled \"Ruling: …\" for a person who maintains the project.") print(f"FAILED: {wrong[0]}") return 1 print(f"ok: {said}") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))