#!/usr/bin/env python3 """Fold small modules into the one file that imports them (issue S-5: fewer modules, as in Lean Pool's copy). python3 -I fold.py plan [--small N] [--cap M] [--skip ] python3 -I fold.py apply # rewrites the tree in place python3 -I fold.py check [rev] # is the working tree what `apply` makes of rev (origin/main)? python3 -I fold.py self-test A module is folded when exactly one file of the repository imports it, that file is in the same folder and the same family (first word of the file name), neither states results, the module has at most --small lines and the file that takes it stands at no more than --cap lines as `apply` writes it. The first limit counts the module's own text. The second counts the written file: the importer's text, the text of the modules it takes, and the lines each fold adds -- a heading that names where the text came from, the `section`, and the `end`s that close the scopes the module left open. `plan` prints both numbers for the largest file. Its text goes into the importer unchanged, in its own `section`, before the importer's own text; the importer takes over its imports. No declaration, statement or proof line changes. `plan` leaves alone the files listed in skip.txt beside this tool, unless --skip names another list: a module folded into one of them builds, and a name or an instance in it resolves to something else (README.md, "Statements"). """ import collections, json, os, re, subprocess, sys LIBS = ("NavierStokes/", "Euler/") # files that state results or must match the challenge: they neither take a module nor are taken PROTECTED = re.compile(r"(Comparator|PaperResult|Results|Theorem|Statement|Solution)") IMPORT = re.compile(r"^import\s+(.+?)\s*(?:--.*)?$") def fam(f): d, n = f.rsplit("/", 1) if f.startswith("NavierStokes/R3/"): return "NavierStokes/R3" w = re.match(r"([A-Z][a-z0-9]+)", n) return d + "/" + (w.group(1) if w else n[:-5]) + "*" def read_tree(tree): src = {} for root, dirs, files in os.walk(tree): dirs[:] = [d for d in dirs if d not in (".lake", ".git")] for n in files: if n.endswith(".lean"): p = os.path.join(root, n) src[os.path.relpath(p, tree)] = open(p, encoding="utf-8").read() return src def split(text): """(what stands before the imports, the imported modules, the rest) of a file's text""" lines = text.split("\n") first = last = None depth = 0 for k, l in enumerate(lines): if depth == 0 and IMPORT.match(l): if first is None: first = k last = k elif depth == 0 and l.strip() and not l.lstrip().startswith("--") and not l.lstrip().startswith("/-") and first is not None: break # the first command after the imports depth = comment_depth(l, depth) if first is None: return lines, [], [] mods = [m for l in lines[first:last + 1] if IMPORT.match(l) for m in IMPORT.match(l).group(1).split()] return lines[:first], mods, lines[last + 1:] def comment_depth(line, depth): """block-comment depth after this line (comments nest; a `--` line comment hides the rest of a line of code)""" k = 0 while k < len(line): two = line[k:k + 2] if two == "/-": depth += 1; k += 2 elif two == "-/" and depth: depth -= 1; k += 2 elif two == "--" and depth == 0: break else: k += 1 return depth OPEN = re.compile(r"^\s*(?:(?:noncomputable|public|private|protected|@\[[^\]]*\])\s+)*(namespace|section|mutual)\b\s*([^\s-]*)") END = re.compile(r"^\s*end\b\s*([^\s-]*)\s*(?:--.*)?$") def unclosed(lines): """the scopes a file's text leaves open at its end (Lean closes them at the end of a file; a section does not)""" stack, depth = [], 0 for l in lines: if depth == 0: m = OPEN.match(l) if m: stack.append((m.group(1), m.group(2) if m.group(1) != "mutual" else "")) elif END.match(l) and stack: stack.pop() depth = comment_depth(l, depth) return stack def module(f): return f[:-5].replace("/", ".") def plan(src, small, cap, skip=(), inplace=True): imports = {f: [m.replace(".", "/") + ".lean" for m in split(t)[1]] for f, t in src.items()} local = {f: [i for i in v if i in src] for f, v in imports.items()} users = collections.defaultdict(set) for f, v in local.items(): for i in v: users[i].add(f) size = {f: t.count("\n") for f, t in src.items()} parts = {f: [f] for f in src} # --cap is on the file `apply` writes, so the heading, the `section` and the `end` each fold adds are counted: # the plain sum of the texts passes the limit and the file it writes overruns it by those lines. gone = {} ok = lambda f: f.startswith(LIBS) and not PROTECTED.search(f.rsplit("/", 1)[1]) and f not in skip changed = True while changed: changed = False for b in sorted(parts, key=lambda f: (size[f], f)): if b not in parts or len(users[b]) != 1: continue a = next(iter(users[b])) if not (ok(a) and ok(b)) or fam(a) != fam(b) or a.rsplit("/", 1)[0] != b.rsplit("/", 1)[0]: continue if size[b] > small: continue cand = parts[b] + parts[a] if folded(src, a, cand, inplace).count("\n") > cap: continue parts[a] = cand; size[a] += size[b] for i in local[b]: users[i].discard(b); users[i].add(a) local[a] = [i for i in local[a] if i != b] + [i for i in local[b] if i not in local[a]] del parts[b], users[b]; gone[b] = a; changed = True return {a: p for a, p in parts.items() if len(p) > 1} def folded(src, host, parts, inplace=False): """the host's new text. `inplace`: a folded module's import line is replaced, where it stood, by that module's own imports, so that every other module is loaded in the order it was loaded before (Lean breaks ties between instances by that order); otherwise the folded modules' imports come after the host's own.""" head, mods, body = split(src[host]) inside = {module(p): p for p in parts[:-1]} if inplace: new = [] def take(ms): for m in ms: if m in inside: take(split(src[inside[m]])[1]) elif m not in new: new.append(m) take(mods) else: new = [m for m in mods if m not in inside] out_parts = [] for p in parts[:-1]: h, pm, pb = split(src[p]) new += [m for m in pm if m not in inside and m not in new] text = h + pb while text and not text[-1].strip(): text.pop() while text and not text[0].strip(): text.pop(0) close = [f"end {name}".rstrip() for kind, name in reversed(unclosed(text))] out_parts.append([f"/-! ## From `{p}`", "", f"The text of `{p}`, folded into this file, which was its only importer. -/", "", "section", ""] + text + close + ["", "end", ""]) # the host's own opening module docstring stays at the top k = 0 while k < len(body) and not body[k].strip(): k += 1 lead = [] if k < len(body) and body[k].startswith("/-!"): depth, j = 0, k while j < len(body): depth = comment_depth(body[j], depth); j += 1 if depth == 0: break lead, body = body[k:j] + [""], body[j:] out = head + [f"import {m}" for m in new] + [""] + lead for part in out_parts: out += part while body and not body[0].strip(): body = body[1:] return "\n".join(out + body) def load(path): """(the folds, whether imports go in place) of a plan file; the first plans were a bare table of folds""" d = json.load(open(path)) return (d["folds"], d.get("imports") == "in place") if "folds" in d else (d, False) def apply(tree, pl, inplace=False): src = read_tree(tree) for host, parts in pl.items(): text = folded(src, host, parts, inplace) # every line of every folded file and of the host is still there (imports aside) want = collections.Counter(l for p in parts for l in (lambda s: s[0] + s[2])(split(src[p])) if l.strip()) have = collections.Counter(l for l in text.split("\n") if l.strip() and not IMPORT.match(l)) assert not (want - have), (host, list((want - have).items())[:3]) open(os.path.join(tree, host), "w", encoding="utf-8").write(text) for p in parts[:-1]: os.remove(os.path.join(tree, p)) def check(repo, pl, rev, inplace=False): """the working tree against what `apply` makes of the revision's text: every changed file, byte for byte""" show = lambda f: subprocess.run(["git", "-C", repo, "show", f"{rev}:{f}"], capture_output=True, text=True, check=True).stdout bad = [] for host, parts in pl.items(): want = folded({p: show(p) for p in parts}, host, parts, inplace) path = os.path.join(repo, host) if not os.path.exists(path) or open(path, encoding="utf-8").read() != want: bad.append(f"{host} is not {rev}'s text folded") bad += [f"{p} is still there" for p in parts[:-1] if os.path.exists(os.path.join(repo, p))] print(f"ok: {len(pl)} files are {rev}'s text with {sum(len(p) - 1 for p in pl.values())} modules folded in, line for line" if not bad else "\n".join(bad)) return 1 if bad else 0 def self_test(): src = {"Euler/FooA.lean": "import Mathlib.X\nimport Euler.FooB\nimport Euler.Bar\n\n/-! # A -/\n\nnoncomputable section\n\ntheorem a : True := trivial\n", "Euler/FooB.lean": "import Mathlib.Y\nimport Euler.FooC\n\n/-! # B\nsection in a comment\n-/\nnoncomputable section\nopen Set\nnamespace Euler.B\ntheorem b : True := trivial\n", "Euler/FooC.lean": "import Mathlib.X\n\ntheorem c : True := trivial\n", "Euler/Bar.lean": "import Mathlib.X\n\ntheorem bar : True := trivial\n", "Euler/FooSolution.lean": "import Euler.FooA\n"} pl = plan(src, 100, 1000) assert pl == {"Euler/FooA.lean": ["Euler/FooC.lean", "Euler/FooB.lean", "Euler/FooA.lean"]}, pl t = folded(src, "Euler/FooA.lean", pl["Euler/FooA.lean"]) assert t.startswith("import Mathlib.X\nimport Euler.Bar\nimport Mathlib.Y\n\n/-! # A -/\n"), t assert "end Euler.B\nend\n\nend\n" in t and t.index("theorem c") < t.index("theorem b") < t.index("theorem a"), t assert unclosed(src["Euler/FooB.lean"].split("\n")) == [("section", ""), ("namespace", "Euler.B")] t2 = folded(src, "Euler/FooA.lean", pl["Euler/FooA.lean"], inplace=True) assert t2.startswith("import Mathlib.X\nimport Mathlib.Y\nimport Euler.Bar\n\n/-! # A -/\n"), t2 assert t2.split("\n\n", 1)[1] == t.split("\n\n", 1)[1] assert plan(src, 100, 1000, skip={"Euler/FooB.lean"}) == {} assert plan(src, 2, 1000) == {}, plan(src, 2, 1000) # the cap is on the file `apply` writes: one line short of it, the last fold is not made stands = t2.count("\n") assert plan(src, 100, stands) == pl and "Euler/FooA.lean" not in plan(src, 100, stands - 1), stands print("ok") if __name__ == "__main__": a = sys.argv[1:] if a[:1] == ["self-test"]: self_test(); sys.exit(0) opt = lambda n, d: (a[a.index(n) + 1] if n in a else d) if a[0] == "plan": src = read_tree(a[1]) beside = os.path.join(os.path.dirname(os.path.abspath(__file__)), "skip.txt") listed = opt("--skip", beside if os.path.exists(beside) else "") skip = {l.strip() for l in open(listed) if l.strip() and not l.startswith("#")} if listed else set() pl = plan(src, int(opt("--small", 200)), int(opt("--cap", 600)), skip) json.dump({"imports": "in place", "folds": pl}, open(a[2], "w"), indent=0) n = sum(len(p) - 1 for p in pl.values()) if pl: stands, h = max((folded(src, h, ps, True).count("\n"), h) for h, ps in pl.items()) text = sum(src[p].count("\n") for p in pl[h]) print(f"folds: {n} modules into {len(pl)} files in {len({fam(h) for h in pl})} families; largest file after: {h} stands at {stands} lines (the cap counts these), {text} of them the text it and its modules had") else: print("folds: 0 modules") elif a[0] == "check": pl, inplace = load(a[2]); sys.exit(check(a[1], pl, a[3] if len(a) > 3 else "origin/main", inplace)) elif a[0] == "apply": pl, inplace = load(a[2]); apply(a[1], pl, inplace); print("applied", sum(len(p) - 1 for p in pl.values()), "folds")