"""The dead-code landing on shoal/navier-stokes, from Treant's 12-03 deletions and the declaration graph of the site's main. What goes = what Treant deleted, less what the project's keep rule holds back (the paper's results, what cites the paper, all they refer to in terms, and what their text names). Order = waves; in a wave each family of files deletes what has no user left outside its own pull request. python3 -I planner.py Writes /plan.json (units with their declarations and line ranges) and prints the counts.""" import bisect, collections, json, os, re, subprocess, sys decls, site, fork, out = sys.argv[1:5] def git(repo, *a): return subprocess.run(["git", "-C", repo, *a], capture_output=True, text=True, check=True).stdout BASE, S03 = "origin/treant/baseline", "origin/treant/03-dead_theorems" cons = [json.loads(l) for l in open(decls, encoding="utf-8")] f_of = lambda m: m.replace(".", "/") + ".lean" ranged = collections.defaultdict(list) for c in cons: if c["r"]: ranged[c["m"]].append((c["r"][0], c["r"][1], c["n"])) group, head = {}, {} for m, rs in ranged.items(): rs.sort(key=lambda r: (r[0], -r[1])); idx = [] for a, b, n in rs: if idx and a <= idx[-1][1]: idx[-1] = (idx[-1][0], max(idx[-1][1], b)) else: idx.append((a, b)); head[(m, a)] = n starts = [g[0] for g in idx] for a, b, n in rs: g = idx[bisect.bisect_right(starts, a) - 1]; group[n] = (m, g[0], g[1]) for c in cons: if c["n"] not in group: p = c["n"] while "." in p: p = p.rsplit(".", 1)[0] if p in group and group[p][0] == c["m"]: group[c["n"]] = group[p]; break G = set(group.values()); name_of = {g: head[(g[0], g[1])] for g in G} raw = {c["n"]: c["u"] for c in cons} sys.setrecursionlimit(100000) def through(n, seen): o = set() for u in raw.get(n, ()): g = group.get(u) if g: o.add(g) elif u not in seen: seen.add(u); o |= through(u, seen) return o uses = collections.defaultdict(set) for c in cons: a = group.get(c["n"]) if a: uses[a] |= through(c["n"], set()) - {a} users = collections.defaultdict(set) for a, bs in uses.items(): for b in bs: users[b].add(a) src = {} def text(m): if m not in src: src[m] = open(f"{site}/{f_of(m)}", encoding="utf-8").read().split("\n") return src[m] body = lambda g: "\n".join(text(g[0])[g[1] - 1:g[2]]) lines = lambda s: sum(g[2] - g[1] + 1 for g in s) # Treant's dead set on the site's main: by line where the file is the same, by the declaration's first lines where it is not site_blobs = {l.split("\t")[1]: l.split()[2] for l in git(site, "ls-tree", "-r", "HEAD").splitlines()} base_blobs = {l.split("\t")[1]: l.split()[2] for l in git(fork, "ls-tree", "-r", BASE).splitlines()} s03_files = set(git(fork, "ls-tree", "-r", "--name-only", S03).splitlines()) gone = {f for f in base_blobs if f.endswith(".lean") and f not in s03_files} deleted, added, cur = collections.defaultdict(set), collections.defaultdict(set), None for line in git(fork, "diff", "-U0", "--no-renames", "--diff-filter=M", BASE, S03, "--", "*.lean").splitlines(): if line.startswith("--- a/"): cur = line[6:] elif line.startswith("@@") and cur: m = re.match(r"@@ -(\d+)(?:,(\d+))? ", line); a, n = int(m.group(1)), int(m.group(2) or 1); deleted[cur].update(range(a, a + n)) elif line.startswith("+") and not line.startswith("+++") and cur: added[cur].add(line[1:]) differ = {f for f in site_blobs if f.endswith(".lean") and site_blobs[f] != base_blobs.get(f)} s03_text = {} def kept_by_treant(f): if f not in s03_text: s03_text[f] = git(fork, "show", f"{S03}:{f}") if f in s03_files else "" return s03_text[f] all_s03 = None def first(g): # the declaration's first line with a name on it, as text for l in text(g[0])[g[1] - 1:g[2]]: if re.search(r"\b(theorem|lemma|def|abbrev|structure|instance|inductive|class)\b", l): return l.strip() return None tdead = set() for g in G: f = f_of(g[0]) if f in gone: tdead.add(g) elif f not in differ: if f in deleted and all(l in deleted[f] for l in range(g[1], g[2] + 1)) and (first(g) or "") not in {a.strip() for a in added[f]}: tdead.add(g) else: # moved by #30/#31: dead if Treant's tree has its first line nowhere in the file it came from h = first(g) origin = [x for x in ("NavierStokes/CorrectionStep.lean", f) if x in s03_files or x in base_blobs] if h and all(h not in kept_by_treant(x) for x in origin) and any(h in git(fork, "show", f"{BASE}:{x}") for x in origin if x in base_blobs): tdead.add(g) print(f"source declarations {len(G)}; Treant's deletions found on the site's main: {len(tdead)} ({lines(tdead)} lines), {sum(f_of(g[0]) in gone for g in tdead)} of them in the {sum(f in site_blobs for f in gone)} whole files that go, {sum(f_of(g[0]) in differ for g in tdead)} in files main has changed") # the keep rule doc = {} for c in cons: g = group.get(c["n"]) if g and c["d"] and name_of[g] == c["n"]: doc[g] = c["d"] cites = re.compile(r"\b(Lemma|Theorem|Proposition|Corollary|Section|Equation|Definition)\s+\(?\d|§\s*\d|\(\d+\.\d+\)") paper_mods = {"NavierStokes.PeriodicPaperTheorem", "NavierStokes.LocalAngularGrowth", "NavierStokes.LocalPaperHeat", "NavierStokes.PaperAdditionalResults", "NavierStokes.R3.Theorem", "NavierStokes.LocalPaperTheorem"} roots = {g for g in G if g[0] in paper_mods or cites.search(doc.get(g, ""))} imports = {} def sees(m): """The modules of this project that module m imports, itself included.""" if m not in imports: imports[m] = {m} for l in text(m)[:400]: w = re.match(r"\s*(?:public\s+|private\s+|meta\s+)*import\s+([\w.]+)", l) if w and w.group(1) in outer_mods: imports[m] |= sees(w.group(1)) return imports[m] outer_mods = {g[0] for g in G} plain = lambda n: re.sub(r"^_private\..*?\.0\.", "", n) short = collections.defaultdict(set) # last name component -> Treant-dead declarations that carry it for g in tdead: if f_of(g[0]) not in gone: short[plain(name_of[g]).rsplit(".", 1)[-1]].add(g) # a file nothing imports goes whole, whatever its names tok = re.compile(r"[A-Za-z_][A-Za-z0-9_'!?₀-₉]*(?:\.[A-Za-z_][A-Za-z0-9_'!?₀-₉]*)*") def named_in(g): """Treant-dead declarations that the text of g names: by a name theirs ends with, in a file g's file can see.""" out_, vis = set(), sees(g[0]) for t in set(tok.findall(body(g))): for h in short.get(t.rsplit(".", 1)[-1], ()): if h != g and h[0] in vis and (h[0] != g[0] or h[1] < g[1]) and ("." + plain(name_of[h])).endswith("." + t): out_.add(h) return out_ held, st = set(), [g for g in roots] seen = set(st) while st: g = st.pop() if g in tdead: held.add(g) nxt = set(uses[g]) if g in tdead: nxt |= named_in(g) # a declaration brought back must still read: what its text names comes back too for b in nxt: if b not in seen: seen.add(b); st.append(b) held = {g for g in held if f_of(g[0]) not in gone} go = tdead - held # whatever a declaration that stays refers to stays too (a deletion the diff showed but Treant's tree did not make) back, changed = 0, True while changed: changed = False for g in list(go): if any(u not in go for u in users[g]): go.discard(g); held.add(g); back += 1; changed = True print(f"brought back because a declaration that stays refers to them: {back}") bad = [g for g in G - go if uses[g] & go] loose = 0 for g in go: t, i = text(g[0]), g[1] - 2 while i >= 0 and not t[i].strip(): i -= 1 if i >= 0 and (t[i].rstrip().endswith("-/") or t[i].lstrip().startswith("@[")): loose += 1 print(f"declarations that go whose docstring or attribute line lies above their range: {loose}") print(f"held back by the keep rule: {len(held)} declarations ({lines(held)} lines, {100 * lines(held) / lines(tdead):.1f}% of Treant's deleted lines) in {len({g[0] for g in held})} files; {sum(bool(cites.search(doc.get(g, ''))) for g in held)} of them cite the paper themselves") print(f"what goes: {len(go)} declarations, {lines(go)} lines; a kept declaration that still refers to one of them: {len(bad)} {[name_of[g] for g in bad[:3]]}") # waves: in a wave a family deletes every declaration whose users are gone already or go in the same pull request def fam(m): parts = m.split("."); d = "/".join(parts[:-1]) if m.startswith("NavierStokes.R3."): return "NavierStokes/R3" w = re.match(r"([A-Z][a-z0-9]+)", parts[-1]); return d + "/" + (w.group(1) if w else parts[-1]) + "*" named = 0 for g in go: if f_of(g[0]) in gone: continue for h in named_in(g): if h in go and g not in users[h]: users[h].add(g); named += 1 print(f"order: {named} more pairs where one declaration that goes is only named in the text of another") whole = {g for g in go if f_of(g[0]) in gone} # whole files: the first step of S-1, its own pull requests rest, done, waves = go - whole, set(whole), [] while rest: wave = {} byfam = collections.defaultdict(set) for g in rest: byfam[fam(g[0])].add(g) for F, cand in byfam.items(): s = set(cand); changed = True while changed: changed = False for g in list(s): if any(u in go and u not in done and u not in s for u in users[g]): s.discard(g); changed = True if s: wave[F] = s if not wave: break waves.append(wave) for s in wave.values(): done |= s; rest -= s print(f"whole files: {len({g[0] for g in whole})} files in {len({fam(g[0]) for g in whole})} families; then {len(waves)} waves, pull requests a wave: {[len(w) for w in waves]} = {sum(len(w) for w in waves)}; left over (a cycle across families): {len(rest)}") cum = 0 for i, w in enumerate(waves, 1): n = sum(len(s) for s in w.values()); cum += n if i <= 12: print(f" wave {i}: {len(w)} families, {n} declarations, {lines({g for s in w.values() for g in s})} lines, {100 * cum / max(1, len(go - whole)):.0f}% done") def top(g): """The first line to cut for g: its range, and the docstring or attribute lines that sit right above it.""" t, a = text(g[0]), g[1] while a >= 2: prev = t[a - 2].strip() if prev.startswith("@[") and prev.endswith("]"): a -= 1 elif prev.endswith("-/"): i = a - 2 while i >= 0 and "/-" not in t[i]: i -= 1 if i < 0 or not t[i].lstrip().startswith("/--"): break a = i + 1 elif re.search(r"\bin\s*$", prev): # `omit [...] in`, `include h in`, `open X in`: a command's prefix goes with it i = a - 2 while i >= 0 and a - 2 - i < 8 and not PREFIX.match(t[i]): i -= 1 if i < 0 or not PREFIX.match(t[i]): break a = i + 1 else: break return a PREFIX = re.compile(r"(omit|include|open|set_option|variable|attribute|local|universe|unseal|seal)\b") os.makedirs(out, exist_ok=True) plan = {"whole_files": sorted(f for f in gone if f in site_blobs), "held": sorted([name_of[g], g[0]] for g in held), "waves": [{F: sorted([g[0], top(g), g[2], name_of[g]] for g in s) for F, s in sorted(w.items())} for w in waves], "left": sorted([name_of[g], g[0]] for g in rest)} json.dump(plan, open(f"{out}/plan.json", "w")) print("written", f"{out}/plan.json")