Download scripts/index.py from cfahlgren1/lean-anthropic-3sum-apsp: direct link, hf CLI and curl.
- Browser
- Download file 29.4 kB
-
https://huggingface.co/datasets/cfahlgren1/lean-anthropic-3sum-apsp/resolve/main/scripts/index.py
- Command line
-
hf download hf://datasets/cfahlgren1/lean-anthropic-3sum-apsp/scripts/index.py
-
curl -L -o index.py https://huggingface.co/datasets/cfahlgren1/lean-anthropic-3sum-apsp/resolve/main/scripts/index.py
29.4 kB
| #!/usr/bin/env python3 | |
| # Copyright (c) 2026 Anthropic, PBC. All rights reserved. | |
| # Released under Apache 2.0 license as described in the file LICENSE. | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Write docs/INDEX.md, docs/FILES.md, docs/PROGRAMS.md, and the list of NOTE paragraphs in docs/REMARKS.md. | |
| scripts/index.py [--check] [--names] | |
| docs/INDEX.md says, for each numbered item, table and figure of the paper, which theorems of Challenge/ are about it, in which | |
| file each of them is proved, what they render, and what is not stated. The last two stand in docs/paper-items.json, | |
| which no script writes; the files are found by this script, so that the index follows when a file moves. | |
| docs/FILES.md lists EndStatement.lean, PaperStatements.lean and every Lean file of Challenge/ and the library with the title | |
| of its header, folder by folder. | |
| docs/PROGRAMS.md says, for each running-time item, by which lemmas it follows from facts about programs, of which routines | |
| the programs consist, and which lemma is proved about each routine. docs/programs.json only names the statements of each | |
| item, the lists of procedures, and the lemmas for the few routines whose lemma has another name than the routine. All the | |
| rest is found by this script: the route in the header and in the proofs of the file that proves the statements, the | |
| routines by following the proofs, the words in the docstrings, and the files. So the guide follows when a file moves or a | |
| docstring changes, and a renaming has to be made in docs/programs.json only. | |
| A paragraph of a comment that begins with the word NOTE marks a place where the Lean text departs from the printed text. | |
| The script copies all of them, from the statements, the definitions and the proofs, into docs/REMARKS.md, between two | |
| marker lines. | |
| --check writes nothing and fails if a file on disk differs from what would be written. | |
| --names also fails if README.md or a file of docs/ names, between backticks, a declaration or a file that does not exist. | |
| The script fails in any case if docs/paper-items.json names a theorem that is not in Challenge/, if a theorem of | |
| Challenge/ occurs in no row, if docs/programs.json names a declaration that does not exist or omits a statement about | |
| programs, or if no lemma is found for a routine. | |
| """ | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| SECTIONS = {"Sec1": "Section 1 (introduction)", "Sec2": "Section 2", "Sec3": "Section 3", "Sec4": "Section 4", | |
| "Sec5": "Section 5", "Agreement": "No item of the paper: definitions that are written twice"} | |
| BEGIN, END = "<!-- notes:begin (generated by scripts/index.py) -->", "<!-- notes:end -->" | |
| DECL = re.compile(r"^(?:@\[[^\]]*\]\s*)?(?:(?:private|protected|noncomputable|public)\s+)*" | |
| r"(theorem|lemma|def|abbrev|structure|inductive|instance|class)\s+([^\s:({\[]+)", re.M) | |
| IDENT = re.compile(r"[A-Za-z_][\w'.₀-₉]*") | |
| SPEC_FOLDER = "ThreeSumApsp/Spec/" # the list-level functions | |
| PROGRAM_FOLDERS = ("ThreeSumApsp/Lang/", "ThreeSumApsp/Programs/", "ThreeSumApsp/Machine/") # the programs and the proofs about them | |
| ROUTE_FOLDERS = PROGRAM_FOLDERS + ("ThreeSumApsp/RunningTimes/", "ThreeSumApsp/TimeClaims/", "ThreeSumApsp/Statements/") | |
| BRIDGE = "ThreeSumApsp/Statements/PaperStatements.lean" # here the library's theorems are named once more, in one line each | |
| OUTERMOST = re.compile(r"ThreeSumApsp/RunningTimes/Sec\d/\w+/") # the outermost procedures, item by item | |
| FIELD = re.compile(r"^\s+(?:\|\s+)?([A-Za-z_][\w']*)\s*(?::|$)", re.M) | |
| INTRO = """# Index: the items of the paper and the Lean statements | |
| This file is written by `scripts/index.py` from `docs/paper-items.json`; do not edit it. | |
| For each numbered item, table and figure of the paper, in the order of the pages, a table names the statements and their | |
| files, and the list below the table says what the statements render and what is not stated. | |
| * A **statement** is a proposition that `EndStatement.lean` or `PaperStatements.lean` defines, such as `Lemma_6`. These two | |
| files are what a reader has to read and trust: for the five claims `EndStatement.lean` alone, for a further statement | |
| `PaperStatements.lean` as well. The tables name the theorem which says that the statement holds, such as `lemma_6`; the | |
| tool Comparator can check that the theorem of this name in the library (the folder `ThreeSumApsp/`), which has a proof, | |
| says exactly that (see `README.md`). | |
| * A **lemma** is a theorem of the library that is not one of these. It is proved, and a reader need not read it. | |
| * **About programs** marks a statement whose theorem has the prefix `wordRam_` or `endStatement_`: it says that there is | |
| a program of the word RAM of `EndStatement.lean` that solves a problem within a time bound. | |
| """ | |
| PROGRAMS_INTRO = f"""# The programs, item by item | |
| This file is written by `scripts/index.py` from `docs/programs.json`, from the headers and the proofs of the files that | |
| prove the running-time statements, and from the docstrings of the lemmas; do not edit it. | |
| `docs/MACHINE.md`, Part 3, says in words which programs run and by which route of the paper. This file gives the names. | |
| For each running-time item of the paper, in the order of the pages, it has | |
| * the statements, and the file in which they are proved; | |
| * the header of that file, which tells the route from the programs to the statements; | |
| * the lemmas of the route: those that the header names, those that the proofs in the file use, and, among those that the | |
| proofs of these use in turn, the main results of their files and the deductions between running-time claims; each | |
| with the first sentence of its docstring and with its file; | |
| * the routines of the programs. A routine is a procedure of the light language, a definition whose name ends in | |
| `Body`. The table says what is proved about it, in the words of the docstring of the lemma; which list-level functions | |
| of `{SPEC_FOLDER}` the lemma is stated with; which function bounds the number of steps (where the column is empty, the | |
| bound is written out in the lemma); and where routine and lemma stand. A routine that several items run is listed once, | |
| under the item with the fewest routines among them. | |
| """ | |
| def stop(message): | |
| sys.exit("error: " + message) | |
| def lean_files(): | |
| def skipped(parts): # Solution/ and scripts/, and every file or folder whose name begins with a dot (.lake, .git) | |
| return any(part in ("Solution", "scripts") or part.startswith(".") for part in parts) | |
| return sorted(p for p in ROOT.rglob("*.lean") if not skipped(p.relative_to(ROOT).parts)) | |
| def comments(text): | |
| """The comments of a Lean text, as triples (start, end, text); a nested comment belongs to the outer one.""" | |
| i, depth, start = 0, 0, 0 | |
| while i < len(text) - 1: | |
| two = text[i:i + 2] | |
| if two == "/-": | |
| start, depth, i = (i if depth == 0 else start), depth + 1, i + (3 if depth == 0 else 2) | |
| elif two == "-/" and depth: | |
| depth, i = depth - 1, i + 2 | |
| if depth == 0: | |
| yield start, i, text[start:i] | |
| elif two == "--" and depth == 0: | |
| i = (text.find("\n", i) + 1) or len(text) | |
| else: | |
| i += 1 | |
| def code(text): | |
| """The text with its block comments blanked out. Line comments stay.""" | |
| for start, end, comment in comments(text): | |
| text = text[:start] + re.sub(r"[^\n]", " ", comment) + text[end:] | |
| return text | |
| def subject(text, end, comment): | |
| """What a comment is about: the declaration or the field after a docstring, the heading of a section comment.""" | |
| if comment.startswith("/--"): | |
| rest = text[end:end + 400].lstrip("\n") | |
| m = DECL.match(rest) or FIELD.match(rest) | |
| return m.group(m.lastindex) if m else "?" | |
| m = re.search(r"^/-!\s*#+\s*(.+)$", comment, re.M) | |
| return 'the comment "' + m.group(1).strip().rstrip("-/ ") + '"' if m else "the header" | |
| def notes(): | |
| """All NOTE paragraphs: (file, subject, text), in the order of the files, the trusted ones first; a note on a statement is listed once. | |
| A paragraph may end in a list, one line "* ..." for each departure; the list is kept as a list.""" | |
| found, stated = [], set() | |
| files = sorted(lean_files(), key=lambda p: (p.parts[len(ROOT.parts)] not in ("EndStatement.lean", "PaperStatements.lean", "Challenge"), p)) | |
| for path in files: | |
| text, rel = path.read_text(encoding="utf-8"), path.relative_to(ROOT).as_posix() | |
| for _, end, comment in comments(text): | |
| body = re.sub(r"^/-[-!]?|-/$", "", comment) | |
| for par in re.split(r"\n\s*\n|\n(?=\s*NOTE\b)", body): | |
| if not re.match(r"\s*NOTE\b", par): | |
| continue | |
| who = subject(text, end, comment) | |
| if rel == "PaperStatements.lean": # the library's lemma_6 has the docstring of Lemma_6 | |
| stated.add(who[:1].lower() + who[1:]) | |
| elif who in stated: | |
| continue | |
| found.append((rel, who, "\n * ".join(" ".join(part.split()) for part in re.split(r"\n\s*\* ", par)))) | |
| return found | |
| def notes_block(): | |
| out, last = [BEGIN, ""], None | |
| for rel, who, par in notes(): | |
| if rel != last: | |
| out += [f"**`{rel}`**", ""] | |
| last = rel | |
| out.append(f"* {who if who.startswith('the ') else chr(96) + who + chr(96)}. {par}") | |
| out.append("") | |
| return "\n".join(out + [END]) | |
| def index(): | |
| items = json.loads((ROOT / "docs" / "paper-items.json").read_text(encoding="utf-8")) | |
| stated_in, proved_in = {}, {} | |
| for path in lean_files(): | |
| rel = path.relative_to(ROOT).as_posix() | |
| for m in DECL.finditer(code(path.read_text(encoding="utf-8"))): | |
| if m.group(1) == "theorem": | |
| (stated_in if rel.startswith("Challenge/") else {} if rel == BRIDGE else proved_in).setdefault(m.group(2), rel) | |
| used = {n for it in items for n in it["statements"]} | |
| if used - set(stated_in): | |
| stop("docs/paper-items.json names theorems that are not in Challenge/: " + ", ".join(sorted(used - set(stated_in)))) | |
| if set(stated_in) - used: | |
| stop("theorems of Challenge/ that occur in no row of docs/paper-items.json: " + ", ".join(sorted(set(stated_in) - used))) | |
| if set(stated_in) - set(proved_in): | |
| stop("statements without a theorem of the same name in the library: " + ", ".join(sorted(set(stated_in) - set(proved_in)))) | |
| def files(names, where): | |
| return "<br>".join(f"[`{f}`](../{f})" for f in dict.fromkeys(where[n] for n in names)) | |
| out = [INTRO, f"There are {len(stated_in)} statements, in {len(set(stated_in.values()))} files.", ""] | |
| for sec, title in SECTIONS.items(): | |
| out += [f"## {title}", "", "| Item | Page | Statements | Proved in |", "|---|---|---|---|"] | |
| prose = [] | |
| for it in (x for x in items if x["section"] == sec): | |
| names = it["statements"] | |
| what = f"**{it['item']}**" + (f"<br>{it['title']}" if it["title"] else "") | |
| out.append(f"| {what} | {it['pages']} | {', '.join(f'`{n}`' for n in names) or 'none'} " | |
| f"| {files(names, proved_in)} |") | |
| prose.append(f"* **{it['item']}.** *Stated:* {it['stated']}" | |
| + (f" *Not stated:* {it['not_stated']}" if it["not_stated"] else "")) | |
| out += ["", *prose, ""] | |
| return "\n".join(out) | |
| def files_map(): | |
| """Every Lean file with the title of its header (the first line of a comment that begins with "# ").""" | |
| out = ["# The files", "", "This file is written by `scripts/index.py`; do not edit it.", "", | |
| "`EndStatement.lean`, `PaperStatements.lean` and every Lean file of `Challenge/` and the library, with the title of its", | |
| "header, folder by folder. The header of a file says what the file proves and how. (The files of `Solution/` only", | |
| "import the library, and `scripts/PrintAxioms.lean` is generated; they are not listed.)", ""] | |
| last = None | |
| for path in sorted(lean_files(), key=lambda p: (p.parent.as_posix(), p.name)): | |
| rel = path.relative_to(ROOT) | |
| if rel.parent != last: | |
| last = rel.parent | |
| out += ["", f"## {'the top level' if last.as_posix() == '.' else chr(96) + last.as_posix() + '/' + chr(96)}", "", | |
| "| file | title |", "|---|---|"] | |
| m = re.search(r"^(?:/-!\s*)?#\s+(.+?)\s*(?:-/)?$", path.read_text(encoding="utf-8"), re.M) | |
| title = m.group(1).replace("|", "\\|") if m else "(no title: the file only imports others, or explains itself)" | |
| out.append(f"| `{rel.name}` | {title} |") | |
| return "\n".join(out) + "\n" | |
| def declarations(): | |
| """All declarations outside Challenge/ and the file BRIDGE: the name with its namespaces -> file, kind, docstring, statement, body, and the | |
| namespaces that the file opens.""" | |
| decls = {} | |
| for path in lean_files(): | |
| rel, text = path.relative_to(ROOT).as_posix(), path.read_text(encoding="utf-8") | |
| if rel.startswith("Challenge/") or rel == BRIDGE: # the theorems stand there once more | |
| continue | |
| plain = code(text) | |
| docs = [(end, c) for _, end, c in comments(text) if c.startswith("/--")] | |
| opened = [w for m in re.finditer(r"^open\s+([^\n]*?)(?:\s+in)?\s*$", plain, re.M) for w in m.group(1).split()] | |
| spaces, marks = [], [] | |
| for m in re.finditer(r"^(namespace|end)\s+(\S+)\s*$", plain, re.M): | |
| if m.group(1) == "namespace": | |
| spaces = spaces + [m.group(2)] | |
| elif spaces and spaces[-1] == m.group(2): | |
| spaces = spaces[:-1] | |
| marks.append((m.start(), spaces)) | |
| found = list(DECL.finditer(plain)) | |
| for k, m in enumerate(found): | |
| around = next((sp for at, sp in reversed(marks) if at < m.start()), []) | |
| name = m.group(2) | |
| full = name[7:] if name.startswith("_root_.") else ".".join(around + [name]) | |
| whole = plain[m.start():found[k + 1].start() if k + 1 < len(found) else len(plain)] | |
| cut = re.search(r":=|\bwhere\b", whole) | |
| stmt = whole[:cut.start()] if cut else whole | |
| doc = next((c for end, c in reversed(docs) if end <= m.start() and | |
| re.fullmatch(r"(\s|@\[[^\]]*\]|open [^\n]* in)*", plain[end:m.start()])), "") | |
| decls.setdefault(full, dict(file=rel, kind=m.group(1), doc=doc, stmt=stmt, body=whole[len(stmt):], | |
| opened=opened)) | |
| return decls | |
| def programs(): | |
| items = json.loads((ROOT / "docs" / "programs.json").read_text(encoding="utf-8")) | |
| decls, last, fronts = declarations(), {}, {} | |
| for full in decls: | |
| last.setdefault(full.split(".")[-1], []).append(full) | |
| def resolve(word, inside): | |
| """The declaration that a name means inside a declaration: what is missing in front of the name is a namespace | |
| around that declaration, or one that its file opens. In h.mono the lemma h is followed by a projection.""" | |
| if inside not in fronts: | |
| here = inside.split(".") | |
| around = [".".join(here[:k]) + "." for k in range(len(here), 0, -1)] + [""] | |
| fronts[inside] = around + [a + o + "." for o in (decls[inside]["opened"] if inside in decls else []) | |
| for a in around] | |
| parts = word.split(".") | |
| for k in range(len(parts), 0, -1): | |
| if parts[k - 1] in last: | |
| name = ".".join(parts[:k]) | |
| for front in fronts[inside]: | |
| if front + name in decls: | |
| return front + name | |
| return None | |
| def ending_with(word): | |
| return [c for c in last.get(word.split(".")[-1], []) if c == word or c.endswith("." + word)] | |
| def need(word, inside, who): | |
| """A name of docs/programs.json: as inside the given declaration, or else the one declaration that ends with it.""" | |
| cands = ending_with(word) | |
| if not cands: | |
| stop(f"docs/programs.json, {who}: there is no declaration {word}") | |
| if len(cands) > 1 and not (inside and resolve(word, inside)): | |
| stop(f"docs/programs.json, {who}: {word} can be " + ", ".join(cands)) | |
| return (inside and resolve(word, inside)) or cands[0] | |
| def has_type(full, types): | |
| return decls[full]["kind"] in ("def", "abbrev") and re.search(rf":\s*({types})\s*$", decls[full]["stmt"].strip()) | |
| def uses(full): | |
| """The lemmas that the proof of a lemma names, in the order of the text.""" | |
| found = [] | |
| for word in IDENT.findall(decls[full]["body"]): | |
| c = resolve(word, full) | |
| if c and c != full and c not in found and decls[c]["kind"] == "theorem" and \ | |
| decls[c]["file"].startswith(ROUTE_FOLDERS): | |
| found.append(c) | |
| return found | |
| def routines_of(full, seen=()): | |
| """The routines of a list of procedures, in the order of the list.""" | |
| out = [] | |
| for word in IDENT.findall(decls[full]["body"]): | |
| c = resolve(word, full) | |
| if c and c != full and c not in seen: | |
| if has_type(c, "Stmt"): | |
| out.append(c) | |
| elif has_type(c, "Program|List Stmt"): | |
| out += routines_of(c, seen + (full,)) | |
| return out | |
| def reach(start): | |
| """The routines that the statements and proofs of the given declarations lead to.""" | |
| seen, todo, got = set(start), list(start), [] | |
| while todo: | |
| full = todo.pop() | |
| for word in IDENT.findall(decls[full]["stmt"] + decls[full]["body"]): | |
| c = resolve(word, full) | |
| if c and c not in seen and decls[c]["file"].startswith(ROUTE_FOLDERS): | |
| seen.add(c) | |
| todo.append(c) | |
| if has_type(c, "Stmt") and c.endswith("Body"): | |
| got.append(c) | |
| return sorted(got, key=lambda r: (decls[r]["file"], r)) | |
| def lemmas_of(routine, chosen, who): | |
| short = routine.split(".")[-1] | |
| if short in chosen: | |
| return [need(n, routine, who) for n in chosen[short].split()] | |
| for ending in ("_spec", "_entry", "_solves", "_meets", "_ends", "_ok"): | |
| c = resolve(short[:-4] + ending, routine) | |
| if c and decls[c]["kind"] == "theorem": | |
| return [c] | |
| stop(f"docs/programs.json, {who}: no lemma is found for the routine {routine}; name it under 'lemmas'") | |
| def says(full): | |
| """The first sentence of a docstring.""" | |
| text = " ".join(re.sub(r"^/--|-/$", "", decls[full]["doc"]).split()).replace("**", "").replace("|", "\\|") | |
| m = re.match(r".{40,}?[.](?= [A-Z(]|$)", text) | |
| return m.group(0) if m else text | |
| def proved(lemma, routine): | |
| """What a lemma proves about a routine. Where its docstring only says that the routine meets its entry, the words are | |
| those of the definition of the entry, or else of the routine.""" | |
| if says(lemma) and not re.search(r"meets? (its|this) (entry|specification)|entry of the map|callers of", says(lemma)): | |
| return says(lemma) | |
| conclusion = re.split(r"[)\]}]\s*:\s", decls[lemma]["stmt"])[-1] | |
| entry = next((c for c in (resolve(w, lemma) for w in IDENT.findall(conclusion)) | |
| if c and c.endswith("Spec") and decls[c]["doc"]), routine) | |
| return says(entry) or says(lemma) | |
| def stated_with(full): | |
| """The list-level functions and the time functions in the statement of a lemma, or in the definitions of the | |
| specification, of the assumptions and of the conclusion that the statement names, and in those that these name.""" | |
| parts = [decls[full]["stmt"]] | |
| for part in parts: # the list grows while it is read | |
| for word in IDENT.findall(part): | |
| c = resolve(word, full) | |
| if c and decls[c]["kind"] in ("def", "structure") and re.search(r"(Spec|Pre|Post)$", c): | |
| if decls[c]["stmt"] + decls[c]["body"] not in parts: | |
| parts.append(decls[c]["stmt"] + decls[c]["body"]) | |
| text = "".join(parts) | |
| fields = set(re.findall(r"^\s+([\w']+)\s*:", text, re.M)) # of a structure of assumptions | |
| fns, times = [], [] | |
| for word in IDENT.findall(text): | |
| c = None if word in fields else resolve(word, full) | |
| if c and decls[c]["kind"] == "def": | |
| if decls[c]["file"].startswith(SPEC_FOLDER) and c not in fns: | |
| fns.append(c) | |
| elif re.search(r"^t[A-Z]|(Time|Steps)$", c.split(".")[-1]) and c not in times: | |
| times.append(c) | |
| return fns, times | |
| def tick(name): | |
| return chr(96) + name + chr(96) | |
| def ticks(names, sep=", "): | |
| return sep.join(tick(n) for n in dict.fromkeys(names)) | |
| def short(names): | |
| return [n.split(".")[-1] for n in names] | |
| about_programs = {m.group(2) for f in sorted((ROOT / "Challenge").glob("*.lean")) | |
| for m in DECL.finditer(code(f.read_text(encoding="utf-8"))) | |
| if m.group(2).startswith(("wordRam_", "endStatement_"))} | |
| if about_programs - {n for it in items for n in it["statements"]}: | |
| stop("statements about programs that occur in no record of docs/programs.json: " + | |
| ", ".join(sorted(about_programs - {n for it in items for n in it["statements"]}))) | |
| stated = {it["item"]: [need(n, "", it["item"]) for n in it["statements"]] for it in items} | |
| files = {who: list(dict.fromkeys(decls[s]["file"] for s in names)) for who, names in stated.items()} | |
| runs = {} # item -> its routines, those of the lists of procedures first | |
| for it in items: | |
| who = it["item"] | |
| rs = [r for p in it.get("programs", []) for r in routines_of(need(p, "", who))] | |
| runs[who] = list(dict.fromkeys(rs + reach([c for c, d in decls.items() if d["file"] in files[who]]))) | |
| # A routine is listed under the item that claims it in docs/programs.json, or else under the item with the fewest | |
| # routines among those that run it; of two such items, under the one that names a list of procedures. | |
| home = {need(r, "", it["item"]): it["item"] for it in items for r in it.get("own", [])} | |
| lists = {it["item"] for it in items if it.get("programs")} | |
| for who in sorted(runs, key=lambda w: (len(runs[w]), w not in lists)): | |
| for r in runs[who]: | |
| home.setdefault(r, who) | |
| out = [PROGRAMS_INTRO] | |
| for it in items: | |
| who = it["item"] | |
| pages = f" ({'pages' if ' ' in it['pages'] else 'page'} {it['pages']})" if it["pages"] else "" | |
| out += [f"## {who}{pages}", "", | |
| f"Statements: {ticks(short(stated[who]))}, proved in {ticks(files[who])}.", ""] | |
| route = [] | |
| for f in files[who]: | |
| head = next((c for _, _, c in comments((ROOT / f).read_text(encoding="utf-8")) if c.startswith("/-!")), "") | |
| head = re.sub(r"^/-!\s*#[^\n]*\n|-/$", "", head).strip() | |
| out += [head, ""] | |
| for word in re.findall(chr(96) + r"([A-Za-z][\w.'₀-₉]*)" + chr(96), head): | |
| cands = ending_with(word) | |
| c = resolve(word, stated[who][0]) or (cands[0] if len(cands) == 1 else None) | |
| if c and re.search(r"[_.]|[a-z][A-Z]", word): | |
| route.append(c) | |
| for s in stated[who] + [c for c in route if decls[c]["file"] in files[who]]: | |
| route += uses(s) | |
| for s in [c for c in route if decls[c]["file"].startswith(PROGRAM_FOLDERS) or OUTERMOST.match(decls[c]["file"])]: | |
| route += [c for c in uses(s) if decls[c]["doc"].startswith("/-- **") or # the main results of their files | |
| (decls[c]["file"].startswith(("ThreeSumApsp/TimeClaims/Sec3/", "ThreeSumApsp/TimeClaims/Sec5/")) | |
| and not decls[c]["file"].endswith("Arithmetic.lean"))] # and the deductions between claims | |
| route = [c for c in dict.fromkeys(route) if c not in stated[who] and decls[c]["doc"]] | |
| if route: | |
| out += ["| Lemma or definition | What it says | File |", "|---|---|---|"] | |
| out += [f"| {tick(c)} | {says(c)} | {tick(decls[c]['file'])} |" for c in route] + [""] | |
| if it.get("programs"): | |
| out += ["Lists of procedures: " + ", ".join( | |
| f"{tick(p)} ({tick(decls[p]['file'])})" for p in (need(p, "", who) for p in it["programs"])) + ".", ""] | |
| if any(home[r] == who for r in runs[who]): | |
| out += ["| Routine | What is proved about it | Lemma | Stated with | Time | Files |", "|---|---|---|---|---|---|"] | |
| for r in (r for r in runs[who] if home[r] == who): | |
| lems = lemmas_of(r, it.get("lemmas", {}), who) | |
| fns = [x for lem in lems for x in stated_with(lem)[0]] | |
| times = list(dict.fromkeys(x for lem in lems for x in stated_with(lem)[1])) | |
| stem = r.split(".")[-1][:-4].lower() # the routine's own time function, not those of the routines it calls | |
| own = [x for x in times if x.split(".")[-1].lower() in ("t" + stem, stem + "time", stem + "steps")] | |
| out.append(f"| {tick(r.split('.')[-1])} | {' '.join(dict.fromkeys(proved(x, r) for x in lems))} | {ticks(short(lems))} | " | |
| f"{ticks(short(fns)[:5])} | {ticks(short(own or (times if len(times) == 1 else [])))} | " | |
| f"{ticks([decls[x]['file'] for x in [r] + lems], '<br>')} |") | |
| count = {} | |
| for r in runs[who]: | |
| if home[r] != who: | |
| count[home[r]] = count.get(home[r], 0) + 1 | |
| if count: | |
| out += ["", "The programs also run routines that are listed under other items: " + | |
| ", ".join(f"{n} under {w}" for w, n in count.items()) + "."] | |
| out.append("") | |
| return "\n".join(out) | |
| def check_names(): | |
| declared, full = set(), set() # last components, fields and namespaces; names with the namespaces around them | |
| for path in lean_files(): | |
| text, spaces = code(path.read_text(encoding="utf-8")), [] | |
| for line in text.splitlines(): | |
| m = re.match(r"(namespace|end)\s+(\S+)", line) | |
| if m and m.group(1) == "namespace": | |
| spaces.append(m.group(2)) | |
| elif m and spaces and spaces[-1] == m.group(2): | |
| spaces.pop() | |
| m = DECL.match(line) | |
| if m: | |
| full.add(".".join(spaces + [m.group(2)])) | |
| full.add(".".join(spaces)) | |
| declared |= {m.group(1) for m in FIELD.finditer(text)} | |
| declared |= set(re.findall(r'^macro "(\w+)', text, re.M)) # tactics | |
| declared |= {part for name in full for part in name.split(".")} | |
| tails = {".".join(name.split(".")[i:]) for name in full for i in range(name.count(".") + 1)} | |
| bad = [] | |
| for doc in [ROOT / "README.md", *sorted(p for p in (ROOT / "docs").glob("*.md") if p.name != "FILES.md")]: | |
| copied = False # the NOTE paragraphs are copies of comments, which also name hypotheses and variables | |
| for k, line in enumerate(doc.read_text(encoding="utf-8").splitlines(), 1): | |
| copied = line == BEGIN or (copied and line != END) | |
| for word in [] if copied else re.findall(r"`([A-Za-z][\w.'/₀-₉-]*)`", line): | |
| if re.fullmatch(r"v[\d.]+", word) or word in ("Quot.sound", "Classical.choice"): | |
| ok = True | |
| elif word.endswith("_"): # a prefix of names | |
| ok = any(name.startswith(word) for name in declared) | |
| elif "/" in word or re.search(r"\.(lean|md|json|py|sh|toml)$", word): | |
| ok = (ROOT / word).exists() | |
| elif re.search(r"[_.]|[a-z][A-Z]", word): | |
| ok = word in tails or ("." not in word and word in declared) or \ | |
| ("." in word and word.rsplit(".", 1)[0] in tails and word.rsplit(".", 1)[1] in declared) | |
| else: | |
| ok = True | |
| if not ok: | |
| bad.append(f"{doc.relative_to(ROOT)}:{k}: {word}") | |
| if bad: | |
| stop("names that do not exist:\n " + "\n ".join(bad)) | |
| def main(): | |
| flags = set(sys.argv[1:]) | |
| if flags - {"--check", "--names"}: | |
| stop(__doc__) | |
| remarks = ROOT / "docs" / "REMARKS.md" | |
| old = remarks.read_text(encoding="utf-8") | |
| if old.count(BEGIN) != 1 or old.count(END) != 1: | |
| stop("docs/REMARKS.md must contain the two marker lines once each") | |
| new = old[:old.index(BEGIN)] + notes_block() + old[old.index(END) + len(END):] | |
| for path, text in ((ROOT / "docs" / "INDEX.md", index()), (ROOT / "docs" / "FILES.md", files_map()), | |
| (ROOT / "docs" / "PROGRAMS.md", programs()), (remarks, new)): | |
| if "--check" in flags: | |
| if not path.exists() or path.read_text(encoding="utf-8") != text: | |
| stop(f"{path.relative_to(ROOT)} is not up to date; run scripts/index.py") | |
| else: | |
| path.write_text(text, encoding="utf-8") | |
| if "--names" in flags: | |
| check_names() | |
| print(f"{len(notes())} NOTE paragraphs") | |
| if __name__ == "__main__": | |
| main() | |