| @@ -0,0 +1,254 @@ |
| 1 | + |
| 2 | +"""Reproduce the result of pull request #47 (issue #48). |
| 3 | + |
| 4 | +Run from the project root, on any branch: the script reads what it checks out of the branch under |
| 5 | +test through `git show`, so it needs no checkout of that branch. |
| 6 | + |
| 7 | + python3 routes/p6-reproduce-47/check.py # the branch of pull request #47 |
| 8 | + python3 routes/p6-reproduce-47/check.py <branch> # another branch |
| 9 | + |
| 10 | +It does three things, which are what issue #48 asks for: |
| 11 | + |
| 12 | +1. It finds, for each of the twenty rows of the glossary of `GUIDE.md` (lines 62-81, `a-place` to |
| 13 | + `seesaw`), the declaration the row's `Lean` column names, and compares the place it finds with |
| 14 | + the place the note of the route states. The note's table is the claim under test; the search |
| 15 | + here is written separately, so a disagreement between the two is a disagreement. |
| 16 | +2. It reports the two spot checks of the issue: `New.Data.aPlaces` and `HeightLe`. |
| 17 | +3. It prints the counts and exits 0 only if every name was found where the note says. |
| 18 | + |
| 19 | +The search here is not the note's `check.py`: a name is resolved by its last dotted part and then |
| 20 | +told apart from its namesakes by the prefix it is written under and by the namespaces of the file |
| 21 | +it is declared in, which is enough once the place is compared with the note. |
| 22 | +""" |
| 23 | + |
| 24 | +import re |
| 25 | +import subprocess |
| 26 | +import sys |
| 27 | + |
| 28 | +BRANCH = sys.argv[1] if len(sys.argv) > 1 else "origin/p6-glossary-rows-1-20" |
| 29 | +NOTE = "routes/p6-glossary-rows-1-20/README.md" |
| 30 | +FIRST, LAST = 62, 81 |
| 31 | +SPOT = { |
| 32 | + "New.Data.aPlaces": "src/New/Reduction/Data/AdmissibleData.lean:256", |
| 33 | + "HeightLe": "src/New/Reduction/Lattices/Heights.lean:50", |
| 34 | +} |
| 35 | + |
| 36 | +KEYWORDS = "theorem|lemma|def|abbrev|structure|class|inductive|instance" |
| 37 | + |
| 38 | +ANCHOR = r"^" |
| 39 | + |
| 40 | +DECL = rf"(noncomputable[[:space:]]+)?(protected[[:space:]]+)?({KEYWORDS})[[:space:]]+" |
| 41 | +TAIL = r"([^A-Za-z0-9_']|$)" |
| 42 | + |
| 43 | +DECL_RE = r"(\s*noncomputable\s+)?(\s*protected\s+)?(" + KEYWORDS + r")\s+" |
| 44 | +CELL = re.compile(r"(?<!\\)\|") |
| 45 | + |
| 46 | +_cache = {} |
| 47 | + |
| 48 | + |
| 49 | +def git_show(path): |
| 50 | + if path not in _cache: |
| 51 | + r = subprocess.run(["git", "show", f"{BRANCH}:{path}"], capture_output=True, text=True, |
| 52 | + encoding="utf-8") |
| 53 | + if r.returncode != 0: |
| 54 | + raise SystemExit(f"cannot read {path} of {BRANCH}: {r.stderr.strip()}") |
| 55 | + _cache[path] = r.stdout |
| 56 | + return _cache[path] |
| 57 | + |
| 58 | + |
| 59 | +def cells(line): |
| 60 | + parts = CELL.split(line) |
| 61 | + return [p.strip() for p in parts[1:-1]] if len(parts) >= 3 else [] |
| 62 | + |
| 63 | + |
| 64 | +def names_of(cell): |
| 65 | + return [n.strip() for n in cell.replace("`", "").split(",") if n.strip()] |
| 66 | + |
| 67 | + |
| 68 | +def rows_of_guide(): |
| 69 | + rows = [] |
| 70 | + for line in git_show("GUIDE.md").split("\n")[FIRST - 1:LAST]: |
| 71 | + c = cells(line) |
| 72 | + if len(c) == 3 and c[0] and c[1].startswith("`"): |
| 73 | + rows.append((c[0], c[1])) |
| 74 | + return rows |
| 75 | + |
| 76 | + |
| 77 | +def grep(pattern): |
| 78 | + r = subprocess.run(["git", "grep", "-n", "-E", "--", pattern, "--", "src"], |
| 79 | + capture_output=True, text=True, encoding="utf-8") |
| 80 | + if r.returncode not in (0, 1): |
| 81 | + raise SystemExit(f"git grep failed: {r.stderr.strip()}") |
| 82 | + return [l for l in r.stdout.splitlines() if l.strip()] |
| 83 | + |
| 84 | + |
| 85 | +def place(line): |
| 86 | + return ":".join(line.split(":")[:2]) |
| 87 | + |
| 88 | + |
| 89 | +def declared_name(line): |
| 90 | + """The qualified name a declaration line declares, `_root_.New.Selmer.DenominatorLe` included.""" |
| 91 | + m = re.search(DECL_RE + r"([\w.']+)", line) |
| 92 | + return m.group(4) if m else "" |
| 93 | + |
| 94 | + |
| 95 | +def namespaces(path): |
| 96 | + """The namespaces a file opens, each `namespace …` line read as written.""" |
| 97 | + return re.findall(r"^namespace\s+([A-Za-z0-9_.']+)", git_show(path), re.M) |
| 98 | + |
| 99 | + |
| 100 | +def find(written): |
| 101 | + """The place of the declaration of `written`, or None. |
| 102 | + |
| 103 | + The namesakes are told apart in two ways. A declaration may be written under a fuller prefix |
| 104 | + (`_root_.New.Selmer.DenominatorLe` for `Selmer.DenominatorLe`) or under none |
| 105 | + (`def aPlaces` for `New.Data.aPlaces`), but not under a prefix the name does not start with, |
| 106 | + which is what keeps `GaugeLe.restrictToY` from answering for `D.restrictToY`. And a name whose |
| 107 | + prefix is a namespace must be declared in a file that opens it (`New.Data.aPlaces`), while a |
| 108 | + name written `D.…` is a field of the data `D : Data P` and must come from a file of a `New` |
| 109 | + namespace. |
| 110 | + """ |
| 111 | + leaf = written.split(".")[-1] |
| 112 | + wprefix = written[: -len(leaf)].rstrip(".") |
| 113 | + best = None |
| 114 | + for h in grep(rf"{ANCHOR}{DECL}([A-Za-z0-9_.']*\.)?{re.escape(leaf)}{TAIL}"): |
| 115 | + decl = declared_name(h) |
| 116 | + if not decl: |
| 117 | + continue |
| 118 | + if not decl.endswith(leaf): |
| 119 | + continue |
| 120 | + path = h.split(":")[0] |
| 121 | + dprefix = decl[: -len(leaf)].removeprefix("_root_.").removeprefix("New.") |
| 122 | + score = 0 |
| 123 | + if dprefix: |
| 124 | + if written.startswith(dprefix): |
| 125 | + score = 2 |
| 126 | + elif written.endswith("." + dprefix + leaf): |
| 127 | + score = 1 |
| 128 | + else: |
| 129 | + continue |
| 130 | + elif written.startswith("D."): |
| 131 | + if any(ns == "New" or ns.startswith("New.") for ns in namespaces(path)): |
| 132 | + score = 2 |
| 133 | + elif wprefix: |
| 134 | + if any(ns == wprefix or ns.endswith("." + wprefix) for ns in namespaces(path)): |
| 135 | + score = 3 |
| 136 | + else: |
| 137 | + score = 1 |
| 138 | + if best is None or score > best[0]: |
| 139 | + best = (score, place(h)) |
| 140 | + if best is not None: |
| 141 | + return best[1] |
| 142 | + |
| 143 | + hits = grep(rf"^[[:space:]]+{re.escape(leaf)}[[:space:]]*:") |
| 144 | + if hits: |
| 145 | + return place(hits[0]) |
| 146 | + |
| 147 | + hits = grep(rf"(open|export)[[:space:]]+[A-Za-z0-9_.']+[[:space:]]+\([^)]*{re.escape(leaf)}") |
| 148 | + return place(hits[0]) if hits else None |
| 149 | + |
| 150 | + |
| 151 | +def note_places(): |
| 152 | + """The places the note of the route states, by name. |
| 153 | + |
| 154 | + A row of the note's table is `| word | declarations | what the row says |`, and each |
| 155 | + declaration is a name in backticks followed by its place in backticks, the place sometimes |
| 156 | + shortened to `:391` of the file before it, and sometimes not in `src` at all but opened from a |
| 157 | + library, which the note gives in brackets after the name. |
| 158 | + """ |
| 159 | + places = {} |
| 160 | + for line in git_show(NOTE).split("\n"): |
| 161 | + c = cells(line) |
| 162 | + if len(c) < 3 or not c[1].startswith("`"): |
| 163 | + continue |
| 164 | + cell = c[1] |
| 165 | + tokens = [(m.group(1), m.start()) for m in re.finditer(r"`([^`]+)`", cell)] |
| 166 | + last_file = "" |
| 167 | + for i, (tok, at) in enumerate(tokens): |
| 168 | + if tok.startswith("src/") or tok.startswith(":") or tok in ("src", "not in"): |
| 169 | + continue |
| 170 | + place_ = "" |
| 171 | + for tok2, _at2 in tokens[i + 1:]: |
| 172 | + if tok2.startswith("src/"): |
| 173 | + place_ = tok2 |
| 174 | + last_file = tok2.rsplit(":", 1)[0] |
| 175 | + break |
| 176 | + if tok2.startswith(":"): |
| 177 | + place_ = last_file + tok2 |
| 178 | + break |
| 179 | + if not tok2.startswith("src"): |
| 180 | + break |
| 181 | + if not place_: |
| 182 | + |
| 183 | + after = cell[at:] |
| 184 | + m = re.search(r"opened at `(src/[^`]+)`", after) |
| 185 | + if m: |
| 186 | + place_ = m.group(1) |
| 187 | + places[tok] = place_ |
| 188 | + return places |
| 189 | + |
| 190 | + |
| 191 | +def claimed_places(claimed, written): |
| 192 | + """The places the note states for `written`. |
| 193 | + |
| 194 | + The note writes the names as the source declares them (`New.Data.aPlaces`) where the guide |
| 195 | + writes them as its reader meets them (`D.aPlaces`), so the note's entries are matched by the |
| 196 | + last dotted part of the name, and every place the note gives for that part is accepted: the |
| 197 | + question here is whether the note lands the name where this search does, not which of two |
| 198 | + namesakes it had in mind. |
| 199 | + """ |
| 200 | + leaf = written.split(".")[-1] |
| 201 | + return {v for k, v in claimed.items() |
| 202 | + if k == written or k.endswith("." + written) or k.split(".")[-1] == leaf} |
| 203 | + |
| 204 | + |
| 205 | +def main(): |
| 206 | + rows = rows_of_guide() |
| 207 | + claimed = note_places() |
| 208 | + bad = [] |
| 209 | + total = 0 |
| 210 | + print(f"branch under test: {BRANCH}") |
| 211 | + print(f"GUIDE.md lines {FIRST}-{LAST}: {len(rows)} rows, {rows[0][0]!r} to {rows[-1][0]!r}") |
| 212 | + print() |
| 213 | + print("| row | name | found at | note says | agree |") |
| 214 | + print("|---|---|---|---|---|") |
| 215 | + for word, lean in rows: |
| 216 | + for n in names_of(lean): |
| 217 | + total += 1 |
| 218 | + here = find(n) |
| 219 | + there = claimed_places(claimed, n) |
| 220 | + ok = (here in there) if here else not there |
| 221 | + if not ok: |
| 222 | + bad.append((word, n, here, there)) |
| 223 | + print(f"| {word} | `{n}` | `{here}` | `{'`, `'.join(sorted(there)) or None}` |" |
| 224 | + f" {'yes' if ok else 'no'} |") |
| 225 | + print() |
| 226 | + print(f"rows: {len(rows)}; names: {total}; not found: {sum(1 for w, n, h, t in bad if h is None)};" |
| 227 | + f" disagreeing: {sum(1 for w, n, h, t in bad if h is not None)}") |
| 228 | + for word, n, here, there in bad: |
| 229 | + print(f" {word}: `{n}`: found {here}, note says {sorted(there)}") |
| 230 | + print() |
| 231 | + print("Spot checks:") |
| 232 | + for written, expected in SPOT.items(): |
| 233 | + here = find(written) |
| 234 | + print(f" `{written}`: {here} ({'as expected' if here == expected else 'UNEXPECTED'})") |
| 235 | + for h in grep(rf"{ANCHOR}{DECL}([A-Za-z0-9_.']*\.)?{re.escape(written.split('.')[-1])}{TAIL}"): |
| 236 | + if place(h) == here: |
| 237 | + print(f" {h.split(':', 2)[2].strip()[:96]}") |
| 238 | + break |
| 239 | + ok = not bad and all(find(k) == v for k, v in SPOT.items()) |
| 240 | + print() |
| 241 | + print("ok" if ok else "not reproduced") |
| 242 | + sys.exit(0 if ok else 1) |
| 243 | + |
| 244 | + |
| 245 | +if __name__ == "__main__": |
| 246 | + main() |
| 247 | + |
| 248 | + |
| 249 | + |
| 250 | + |
| 251 | + |
| 252 | + |
| 253 | + |
| 254 | + |