Index of theproofnetwork/open-problems@860a535/scripts/import_formal_conjectures.py

qedmarket’s copy of theproofnetwork/open-problems@860a535, 3 Dec 2026original source ↗

203 lines · 9.1 kBraw
#!/usr/bin/env python3"""Copy formal-conjectures' open statements into this repository.     python3 -I scripts/import_formal_conjectures.py <formal-conjectures checkout> \        [--support <open-problems-support checkout>] [--drop FILE ...] What it copies, from the checkout's current commit:- here: every file under `FormalConjectures/` with a `@[category research open …]` declaration, and every  statement file those import (their closure);- into the support repository (theproofnetwork/open-problems-support, by default a checkout next to this one): all  of `FormalConjecturesUtil/` and `FormalConjecturesForMathlib/` and their root files. It is a package of its own so  that the verifier compiles it once into a shared archive, not again for every challenge. After changing it, commit  and push it there, and point `rev` in this repository's lakefile.toml (and lake-manifest.json) at that commit. Module names, and name parts written with `«»` in the statements, are made plain dotted identifiers, as the officialverifier and the platform take them(`[A-Za-z_][A-Za-z0-9_]*` per segment): `ErdosProblems/61.lean` becomes `ErdosProblems/Erdos61.lean`,`Arxiv/2610.08796/` becomes `Arxiv/arXiv_2610_08796/`. Imports are rewritten to match; nothing else in a filechanges, except for the patches (`patches/formal-conjectures/` here, `patches/` in the support repository), appliedin order, which port the files to this Mathlib. Each repository's `upstream.json` records the commit and, per copiedfile, its upstream path. `--drop` leaves out a statement file (its upstream path) and every statement file that imports it, for filesthat don't compile on this repository's Mathlib. Existing copies are replaced: the folders are deleted first."""import jsonimport reimport shutilimport subprocessimport sysfrom pathlib import Path ROOT = Path(__file__).resolve().parent.parentLIBS = ("FormalConjectures", "FormalConjecturesUtil", "FormalConjecturesForMathlib")# The prefix for a segment that starts with a digit, by the folder below FormalConjectures/.PREFIX = {"ErdosProblems": "Erdos", "GreensOpenProblems": "Green", "OEIS": "A", "Arxiv": "arXiv_",          "HilbertProblems": "Hilbert", "Kourovka": "Kourovka", "Mathoverflow": "MO", "LittProblems": "Litt",          "OpenQuantumProblems": "OQP", "OptimizationConstants": "C", "WrittenOnTheWallII": "WOWII"}# A dotted name with at least one «…» segment (`Arxiv.«0805.3777».conjecture`, `FormalConjectures.OEIS.«111291»`).SEG = r"(?:[A-Za-z_][A-Za-z0-9_'!?]*|«[^»\n]+»)"QUOTED = re.compile(rf"(?<![\w.»]){SEG}(?:\.{SEG})*")# The prefix for a namespace segment that starts with a digit, by the segment before it.NS_PREFIX = {"Arxiv": "arXiv_", "Kourovka": "Kourovka", "variants": "v"}IMPORT = re.compile(r"^((?:(?:public|private|meta)\s+)*import\s+)(\S+)(.*)$")OPEN = re.compile(r"@\[[^\]]*category\s+research\s+open")IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")  def segments(name):    """`A.«2610.08796».B` → ['A', '2610.08796', 'B']."""    out, cur, quoted = [], "", False    for ch in name:        if ch == "«":            quoted = True        elif ch == "»":            quoted = False        elif ch == "." and not quoted:            out.append(cur)            cur = ""        else:            cur += ch    return out + [cur]  def plain(segs):    """Segments as the verifier accepts them."""    out = []    for i, s in enumerate(segs):        if not IDENT.match(s):            s = re.sub(r"[^A-Za-z0-9_]", "_", s)            if s[0].isdigit():                folder = segs[1] if segs[0] == "FormalConjectures" and len(segs) > 2 else ""                s = PREFIX.get(folder, "P") + s        out.append(s)    return out  def unquote(text, modules):    """Names with «…» segments as plain identifiers, which the verifier and the platform take: a module reference    as the module is now called, any other name segment by segment (`Arxiv.«0805.3777»` → `Arxiv.arXiv_0805_3777`).    Segments with other characters (a notation's name such as `«term_≤_»`) are left alone."""    def fix(m):        name = m.group(0)        if "«" not in name:            return name        segs = segments(name)        if any(not IDENT.match(s) and not re.fullmatch(r"[A-Za-z0-9.]+", s) for s in segs):            return name        if tuple(segs) in modules:            return ".".join(modules[tuple(segs)])        out = []        for i, s in enumerate(segs):            if not IDENT.match(s):                s = re.sub(r"[^A-Za-z0-9_]", "_", s)                if s[0].isdigit():                    s = NS_PREFIX.get(segs[i - 1] if i else "", "P") + s            out.append(s)        return ".".join(out)    return QUOTED.sub(fix, text)  def module_of(path):    return list(path.with_suffix("").parts)  # a folder may have a dot in its name (`Arxiv/0805.3777/`)  def imports(text):    for line in text.splitlines():        m = IMPORT.match(line)        if m:            yield tuple(segments(m.group(2)))  def main(argv):    src = Path(argv[0]).resolve()    drop = set()    if "--drop" in argv:        drop = {Path(p) for p in argv[argv.index("--drop") + 1:]}        argv = argv[:argv.index("--drop")]    support = (Path(argv[argv.index("--support") + 1]) if "--support" in argv               else ROOT.parent / "open-problems-support").resolve()    if not (support / "lakefile.toml").exists():        sys.exit(f"no support repository at {support}; pass --support")    commit = subprocess.run(["git", "-C", str(src), "rev-parse", "HEAD"], check=True,                            capture_output=True, text=True).stdout.strip()    files = {}  # module segments → upstream path, relative    for lib in LIBS:        for p in sorted(src.glob(f"{lib}/**/*.lean")):            files[tuple(module_of(p.relative_to(src)))] = p.relative_to(src)        if (src / f"{lib}.lean").exists():            files[(lib,)] = Path(f"{lib}.lean")    text = {m: (src / p).read_text() for m, p in files.items()}    statement = {m for m in files if m[0] == "FormalConjectures" and len(m) > 1}     # Leave out the dropped files and whatever imports them.    dropped = {m for m in statement if files[m] in drop}    while True:        more = {m for m in statement - dropped if any(i in dropped for i in imports(text[m]))}        if not more:            break        dropped |= more     wanted = [m for m in statement - dropped if OPEN.search(text[m])]    keep, todo = set(), list(wanted)    while todo:        m = todo.pop()        if m in keep:            continue        keep.add(m)        todo += [i for i in imports(text[m]) if i in statement]    keep |= {m for m in files if m[0] != "FormalConjectures"}     new = {m: tuple(plain(list(m))) for m in files}    if len(set(new.values())) != len(new):        sys.exit("two modules got the same name")    def home(m):        return ROOT if m[0] == "FormalConjectures" else support     for lib in LIBS:        for base in (ROOT, support):            shutil.rmtree(base / lib, ignore_errors=True)            (base / f"{lib}.lean").unlink(missing_ok=True)     def rewrite(line):        m = IMPORT.match(line)        if not m:            return line        segs = tuple(segments(m.group(2)))        if segs not in new:            return line        return m.group(1) + ".".join(new[segs]) + m.group(3)     record, lib_record = {}, {}    for m in sorted(keep):        if any(i in dropped for i in imports(text[m])):            continue  # a library file importing a dropped statement: never happens upstream        out = home(m) / Path(*new[m]).with_suffix(".lean")        out.parent.mkdir(parents=True, exist_ok=True)        body = "\n".join(rewrite(line) for line in text[m].split("\n"))        if home(m) == ROOT:            body = unquote(body, new)        out.write_text(body)        (record if home(m) == ROOT else lib_record)[".".join(new[m])] = str(files[m])    # The fixes that port the files to this Mathlib, made by hand: `git diff > patches/…` after a fix.    for base, folder in ((support, support / "patches"), (ROOT, ROOT / "patches/formal-conjectures")):        for patch in sorted(folder.glob("*.patch")):            subprocess.run(["git", "apply", "--whitespace=nowarn", str(patch)], cwd=base, check=True)            print(f"applied {patch.relative_to(base)} in {base.name}")    (support / "upstream.json").write_text(json.dumps({        "repository": "https://github.com/google-deepmind/formal-conjectures",        "commit": commit,        "modules": lib_record,    }, indent=1, ensure_ascii=False) + "\n")    (ROOT / "upstream.json").write_text(json.dumps({        "repository": "https://github.com/google-deepmind/formal-conjectures",        "commit": commit,        "dropped": sorted(str(files[m]) for m in dropped),        "modules": record,    }, indent=1, ensure_ascii=False) + "\n")    print(f"{len(wanted)} files with open statements, {len(keep)} files copied, {len(dropped)} dropped")  if __name__ == "__main__":    main(sys.argv[1:])

download (.tar)