The Robbins problem with tactics (deep dive: compression).
Code with colored syntax: click a line number to get a link to it; an underlined name leads to its definition.
| 1 | """The Robbins problem with tactics (deep dive: compression). |
| 2 | |
| 3 | A Robbins algebra has a sum and a complement n(x) with three laws: |
| 4 | |
| 5 | A1 x + y = y + x |
| 6 | A2 x + y + z = x + (y + z) |
| 7 | R n(n(x + y) + n(x + n(y))) = x (Robbins, 1933) |
| 8 | |
| 9 | Every proof here is a tree of the five kernel rules. The tactics below |
| 10 | write those trees for us, in the style of Lean's tactic blocks: |
| 11 | |
| 12 | g = Goal(K, "n(n(n(a + b) + n(a) + b) + b) = n(a + b)") |
| 13 | g.nth_rw(2, "← R (n(a + b)) (n(a) + b)") |
| 14 | g.nth_rw(3, "← R b a") |
| 15 | g.ac() |
| 16 | proof = g.qed() |
| 17 | |
| 18 | nth_rw k rewrites the k-th occurrence, rw every occurrence (as in Lean); |
| 19 | "← R x y" uses the law from right to left; ac closes a goal whose sides |
| 20 | differ only by A1 and A2 (module ac); rw_ac, ac_simp and auto rewrite |
| 21 | modulo A1 and A2. Our kernel has no implication, so a lemma with |
| 22 | hypotheses (Hypothetical) and a group of lemmas about constants (Section, |
| 23 | like a section of Lean with `variable`) are proved once with constants and |
| 24 | written down again for every use; the kernel checks every copy. |
| 25 | """ |
| 26 | |
| 27 | from itertools import combinations |
| 28 | |
| 29 | from kernel import Kernel, Refl, Symm, Trans, CongrArg, Inst, subst |
| 30 | from syntax import term, equation, show, show_equation |
| 31 | from tactics import TacticError, match_pattern, variables, trans, symm, fresh |
| 32 | from ac import (brief, order_key, Steps, ac_proof, ac_match, |
| 33 | ac_match_part, at, is_sum, chain, |
| 34 | addends, normal) |
| 35 | |
| 36 | SIGNATURE = {"+": 2, "n": 1} |
| 37 | AXIOMS = [("A1", "x + y = y + x"), |
| 38 | ("A2", "x + y + z = x + (y + z)"), |
| 39 | ("R", "n(n(x + y) + n(x + n(y))) = x")] |
| 40 | |
| 41 | |
| 42 | class Library(Kernel): |
| 43 | """The kernel that also keeps the proofs of its theorems, so that we |
| 44 | can measure them. The checking is the kernel's own, unchanged.""" |
| 45 | |
| 46 | def __init__(self, signature): |
| 47 | super().__init__(signature) |
| 48 | self.proofs = {} # name -> proof |
| 49 | |
| 50 | def theorem(self, name, variables, l, r, proof): |
| 51 | super().theorem(name, variables, l, r, proof) |
| 52 | self.proofs[name] = proof |
| 53 | |
| 54 | |
| 55 | def theory(): |
| 56 | """A kernel with the three laws of a Robbins algebra.""" |
| 57 | K = Library(SIGNATURE) |
| 58 | for name, text in AXIOMS: |
| 59 | l, r = equation(text) |
| 60 | K.axiom(name, variables(r, variables(l)), l, r) |
| 61 | return K |
| 62 | |
| 63 | |
| 64 | def times(k, a="a"): |
| 65 | """k·a = a + a + ... + a (k summands), as text: times(3) = 'a + a + a'.""" |
| 66 | return " + ".join([f"({a})" if "+" in a else a] * k) |
| 67 | |
| 68 | |
| 69 | def _words(text): |
| 70 | """'← R (a + b) c' -> ['←', 'R', '(a + b)', 'c']: split at spaces |
| 71 | outside parentheses.""" |
| 72 | words, depth, now = [], 0, "" |
| 73 | for c in text.replace("←", " ← "): |
| 74 | if c == " " and depth == 0: |
| 75 | if now: |
| 76 | words.append(now) |
| 77 | now = "" |
| 78 | continue |
| 79 | depth += (c == "(") - (c == ")") |
| 80 | now += c |
| 81 | return words + ([now] if now else []) |
| 82 | |
| 83 | |
| 84 | def positions(t, path=()): |
| 85 | """Paths of all subterms in Lean's order: the term, then its |
| 86 | arguments from left to right.""" |
| 87 | yield path |
| 88 | if not isinstance(t, str): |
| 89 | for i, a in enumerate(t[1:], 1): |
| 90 | yield from positions(a, path + (i,)) |
| 91 | |
| 92 | |
| 93 | class Goal: |
| 94 | """The goal l = r of a proof in progress, with the rewrites so far |
| 95 | (a proof l0 = l and a proof r0 = r) and the local hypotheses.""" |
| 96 | |
| 97 | def __init__(self, kernel, statement, hypotheses=None): |
| 98 | l, r = (equation(statement) if isinstance(statement, str) |
| 99 | else statement) |
| 100 | self.kernel = kernel |
| 101 | self.sides = [Steps(kernel, l), Steps(kernel, r)] |
| 102 | self.hypotheses = dict(hypotheses or {}) # name -> proof |
| 103 | self.closing = None |
| 104 | self.tactics = 0 # tactic calls so far |
| 105 | self.equations = {} # id(proof) -> equation |
| 106 | |
| 107 | def goal(self): |
| 108 | return self.sides[0].now, self.sides[1].now |
| 109 | |
| 110 | def __str__(self): |
| 111 | return brief(show_equation(self.goal())) |
| 112 | |
| 113 | # --- reading a rule: a law, a lemma or a hypothesis --------------------- |
| 114 | |
| 115 | def rule(self, text): |
| 116 | """'← R (a + b) c' -> (pattern, result, free, proof of instance). |
| 117 | |
| 118 | Arguments may be left out at the end or written _; they are then |
| 119 | found by matching the pattern against the goal.""" |
| 120 | words = _words(text) |
| 121 | backward = words[0] == "←" |
| 122 | if backward: |
| 123 | words = words[1:] |
| 124 | name, args = words[0], words[1:] |
| 125 | if name in self.hypotheses: |
| 126 | proof = self.hypotheses[name] |
| 127 | l, r = self._known(proof) |
| 128 | if backward: |
| 129 | l, r, proof = r, l, symm(proof) |
| 130 | return l, r, (), lambda s: proof |
| 131 | if name not in self.kernel.facts: |
| 132 | raise TacticError(f"unknown fact or hypothesis {name}") |
| 133 | names, l, r = self.kernel.facts[name] |
| 134 | given = {v: term(a) for v, a in zip(names, args) if a != "_"} |
| 135 | if len(args) > len(names): |
| 136 | raise TacticError(f"{name}: too many arguments") |
| 137 | # the fact's own variables get names unlike those of the goal, so |
| 138 | # that `R y _` does not mix the goal's y with the fact's y |
| 139 | apart = _apart([v for v in names if v not in given], |
| 140 | *(given[v] for v in given), *self.goal()) |
| 141 | both = {**given, **apart} |
| 142 | l, r = subst(l, both), subst(r, both) |
| 143 | if backward: |
| 144 | l, r = r, l |
| 145 | free = tuple(apart[v] for v in apart) |
| 146 | |
| 147 | def proof(s): |
| 148 | p = Inst(name, tuple(given[v] if v in given else |
| 149 | s.get(apart[v], apart[v]) for v in names)) |
| 150 | return Symm(p) if backward else p |
| 151 | return l, r, free, proof |
| 152 | |
| 153 | def _known(self, proof): |
| 154 | """The equation of a proof, computed once per proof.""" |
| 155 | if id(proof) not in self.equations: |
| 156 | self.equations[id(proof)] = (proof, |
| 157 | self.kernel.conclusion(proof)) |
| 158 | return self.equations[id(proof)][1] |
| 159 | |
| 160 | def _instance(self, pattern, free, sides): |
| 161 | """The first match of the pattern in the goal (Lean's order).""" |
| 162 | for i in sides: |
| 163 | t = self.sides[i].now |
| 164 | for path in positions(t): |
| 165 | s = match_pattern(pattern, at(t, path), set(free), {}) |
| 166 | if s is not None: |
| 167 | return s |
| 168 | raise TacticError(f"no {brief(show(pattern))} in {self}") |
| 169 | |
| 170 | # --- tactics ----------------------------------------------------------- |
| 171 | |
| 172 | def rw(self, *rules, side=None): |
| 173 | """rw [r₁, r₂, …]: each rule rewrites every occurrence of its |
| 174 | first match; side='lhs' or 'rhs' rewrites in one side only.""" |
| 175 | for text in rules: |
| 176 | self._rewrite(text, None, side) |
| 177 | return self |
| 178 | |
| 179 | def nth_rw(self, k, *rules, side=None): |
| 180 | """nth_rw k [r₁, …]: only the k-th occurrence (counted in Lean's |
| 181 | order through the left side, then the right side).""" |
| 182 | for text in rules: |
| 183 | self._rewrite(text, k, side) |
| 184 | return self |
| 185 | |
| 186 | def _rewrite(self, text, k, side): |
| 187 | self.tactics += 1 |
| 188 | pattern, result, free, proof = self.rule(text) |
| 189 | sides = {None: (0, 1), "lhs": (0,), "rhs": (1,)}[side] |
| 190 | s = self._instance(pattern, free, sides) |
| 191 | u, p = subst(pattern, s), proof(s) |
| 192 | w = subst(result, s) |
| 193 | found = [] # (side, path) |
| 194 | for i in sides: |
| 195 | t = self.sides[i].now |
| 196 | inside = None |
| 197 | for path in positions(t): |
| 198 | if (k is None and inside is not None |
| 199 | and path[:len(inside)] == inside): |
| 200 | continue # rw: not inside a match |
| 201 | if at(t, path) == u: |
| 202 | found.append((i, path)) |
| 203 | inside = path |
| 204 | if k is not None: |
| 205 | if k > len(found): |
| 206 | raise TacticError(f"nth_rw {k}: only {len(found)} " |
| 207 | f"occurrences of {brief(show(u))}") |
| 208 | found = [found[k - 1]] |
| 209 | for i, path in found: |
| 210 | self.sides[i].step(path, p, (u, w)) |
| 211 | |
| 212 | def rw_ac(self, *rules, side=None): |
| 213 | """rw modulo A1 and A2: the rule's left side may sit in the goal |
| 214 | reordered, or as a part of a longer sum — e.g. b + a inside |
| 215 | c + (a + d + b). Missing arguments are found by matching modulo |
| 216 | A1 and A2. The goal is first brought to the normal form, the |
| 217 | summands are regrouped so that the pattern stands alone, then the |
| 218 | rule rewrites it once (the first match in Lean's order).""" |
| 219 | for text in rules: |
| 220 | self.tactics += 1 |
| 221 | if not self._rewrite_ac(text, side): |
| 222 | raise TacticError(f"rw_ac [{text}]: no match (up to A1, " |
| 223 | f"A2) in {self}") |
| 224 | return self |
| 225 | |
| 226 | def _rewrite_ac(self, text, side): |
| 227 | pattern, result, free, proof = self.rule(text) |
| 228 | free = set(free) |
| 229 | for i in {None: (0, 1), "lhs": (0,), "rhs": (1,)}[side]: |
| 230 | steps = self.sides[i] |
| 231 | t = normal(steps.now) |
| 232 | for path in positions(t): |
| 233 | v = at(t, path) |
| 234 | found = next(ac_match(pattern, v, free, {}), None) |
| 235 | rest = None |
| 236 | if found is None and is_sum(pattern) \ |
| 237 | and _whole_sum(t, path): |
| 238 | for s, left in ac_match_part(pattern, addends(v), |
| 239 | free, {}): |
| 240 | if left: |
| 241 | found, rest = s, left |
| 242 | break |
| 243 | if found is None: |
| 244 | continue |
| 245 | u = subst(pattern, found) |
| 246 | if rest is None: |
| 247 | regrouped, where = _put(t, path, u), path |
| 248 | else: |
| 249 | regrouped = _put(t, path, ("+", chain(rest), u)) |
| 250 | where = path + (2,) |
| 251 | steps.step((), ac_proof(self.kernel, steps.now, regrouped), |
| 252 | (steps.now, regrouped)) |
| 253 | w = subst(result, found) |
| 254 | steps.step(where, proof(found), (u, w)) |
| 255 | return True |
| 256 | return False |
| 257 | |
| 258 | def ac_simp(self, *rules, limit=50): |
| 259 | """simp modulo A1 and A2: rewrite with the rules (in the given |
| 260 | direction) as long as one of them applies, then close the goal |
| 261 | if the sides agree up to A1 and A2.""" |
| 262 | for _ in range(limit): |
| 263 | if not any(self._rewrite_ac(text, None) for text in rules): |
| 264 | break |
| 265 | else: |
| 266 | raise TacticError(f"ac_simp: more than {limit} rewrites") |
| 267 | self.tactics += 1 |
| 268 | l, r = self.goal() |
| 269 | if normal(l) == normal(r): |
| 270 | self.closing = ac_proof(self.kernel, l, r) |
| 271 | return self |
| 272 | |
| 273 | def exact_ac(self, proof): |
| 274 | """Close the goal with a proof of an equation that differs from |
| 275 | the goal only by A1 and A2.""" |
| 276 | self.tactics += 1 |
| 277 | a, b = self._known(proof) |
| 278 | l, r = self.goal() |
| 279 | self.closing = trans(ac_proof(self.kernel, l, a), proof, |
| 280 | ac_proof(self.kernel, b, r)) or proof |
| 281 | return self |
| 282 | |
| 283 | def auto(self, *rules, pool=2, limit=200_000, depth=1): |
| 284 | """Find the creative steps by search: at most `depth` rewrites on |
| 285 | each side (meet in the middle), then ac. Rules: "R" contracts |
| 286 | (finds the pattern modulo A1, A2), "← R" expands a part x of the |
| 287 | goal to n(n(x + y) + n(x + n(y))) with y taken from the terms of |
| 288 | the goal and their sums of up to `pool` summands; other rules are |
| 289 | rewrites modulo A1, A2. Mathlib writes such steps by hand: |
| 290 | nth_rw 2 [← robbins (-(a + b)) (-a + b)].""" |
| 291 | self.tactics += 1 |
| 292 | rules = rules or ("R", "← R") |
| 293 | l, r = self.goal() |
| 294 | nl, nr = normal(l), normal(r) |
| 295 | if nl == nr: |
| 296 | self.closing = ac_proof(self.kernel, l, r) |
| 297 | return self |
| 298 | terms = _pool(nl, nr, pool) |
| 299 | tables = ({nl: None}, {nr: None}) # term -> (previous, move) |
| 300 | layers = [[nl], [nr]] |
| 301 | meet = None |
| 302 | for _ in range(depth): |
| 303 | for side in (0, 1): |
| 304 | table, layer = tables[side], [] |
| 305 | for t in layers[side]: |
| 306 | for u, move in self._moves(t, rules, terms, |
| 307 | limit).items(): |
| 308 | if u not in table: |
| 309 | table[u] = (t, move) |
| 310 | layer.append(u) |
| 311 | if len(table) > limit: |
| 312 | raise TacticError("auto: too many possibilities") |
| 313 | layers[side] = layer |
| 314 | left, right = tables |
| 315 | if nr in left: |
| 316 | meet = nr |
| 317 | elif nl in right: |
| 318 | meet = nl |
| 319 | else: |
| 320 | meet = next((t for t in left if t in right), None) |
| 321 | if meet is not None: |
| 322 | break |
| 323 | if meet is None: |
| 324 | raise TacticError( |
| 325 | f"auto: no proof with {depth} step(s) on " |
| 326 | f"each side for {self}") |
| 327 | for side in (0, 1): |
| 328 | path, t = [], meet |
| 329 | while tables[side].get(t) is not None: |
| 330 | t, move = tables[side][t] |
| 331 | path.append(move) |
| 332 | for regrouped, where, p, equation in reversed(path): |
| 333 | steps = self.sides[side] |
| 334 | steps.step((), ac_proof(self.kernel, steps.now, regrouped), |
| 335 | (steps.now, regrouped)) |
| 336 | steps.step(where, p, equation) |
| 337 | self.closing = ac_proof(self.kernel, *self.goal()) |
| 338 | return self |
| 339 | |
| 340 | def _moves(self, t, rules, terms, limit): |
| 341 | """{normal form after one rewrite: (term before the rewrite, |
| 342 | where, proof of the rewrite, its equation)} for the term t.""" |
| 343 | found = {} |
| 344 | for text in rules: |
| 345 | pattern, result, free, proof = self.rule(text) |
| 346 | for regrouped, where, s in _places(t, pattern, set(free), terms): |
| 347 | u, w = subst(pattern, s), subst(result, s) |
| 348 | new = normal(_put(regrouped, where, w)) |
| 349 | if new not in found: |
| 350 | found[new] = (regrouped, where, proof(s), (u, w)) |
| 351 | if len(found) > limit: |
| 352 | raise TacticError("auto: too many possibilities") |
| 353 | return found |
| 354 | |
| 355 | def ac(self): |
| 356 | """Close the goal: the sides differ only by A1 and A2.""" |
| 357 | self.tactics += 1 |
| 358 | self.closing = ac_proof(self.kernel, *self.goal()) |
| 359 | return self |
| 360 | |
| 361 | def rfl(self): |
| 362 | self.tactics += 1 |
| 363 | l, r = self.goal() |
| 364 | if l != r: |
| 365 | raise TacticError(f"rfl: {self}") |
| 366 | self.closing = None |
| 367 | return self |
| 368 | |
| 369 | def exact(self, proof): |
| 370 | """Close the goal with a proof of exactly this equation.""" |
| 371 | self.tactics += 1 |
| 372 | if self._known(proof) != self.goal(): |
| 373 | raise TacticError(f"exact: the proof does not fit {self}") |
| 374 | self.closing = proof |
| 375 | return self |
| 376 | |
| 377 | def fact(self, text): |
| 378 | """The proof of one instance: fact('mann_44 a (b + c)').""" |
| 379 | pattern, result, free, proof = self.rule(text) |
| 380 | if free: |
| 381 | raise TacticError(f"{text}: give all arguments") |
| 382 | return proof({}) |
| 383 | |
| 384 | def have(self, name, proof): |
| 385 | """A local hypothesis: a proof of an equation, used by rw.""" |
| 386 | self.hypotheses[name] = proof |
| 387 | return self |
| 388 | |
| 389 | def qed(self): |
| 390 | """The proof of the original goal: rewrites, closing, rewrites.""" |
| 391 | l, r = self.goal() |
| 392 | if l != r and self.closing is None: |
| 393 | raise TacticError(f"unfinished: {self}") |
| 394 | left, right = self.sides |
| 395 | return (trans(left.proof, self.closing, symm(right.proof)) |
| 396 | or Refl(left.start)) |
| 397 | |
| 398 | |
| 399 | def _whole_sum(t, path): |
| 400 | """Is the subterm at the path a whole sum (not a part of a longer |
| 401 | one)?""" |
| 402 | if not is_sum(at(t, path)): |
| 403 | return False |
| 404 | return not path or not is_sum(at(t, path[:-1])) |
| 405 | |
| 406 | |
| 407 | def _apart(names, *terms): |
| 408 | """New names x_, y_, ... for the variables `names`, unlike all |
| 409 | variables of the terms.""" |
| 410 | taken = set() |
| 411 | for t in terms: |
| 412 | taken.update(variables(t)) |
| 413 | result = {} |
| 414 | for v in names: |
| 415 | i, candidate = 0, v + "_" |
| 416 | while candidate in taken: |
| 417 | i += 1 |
| 418 | candidate = f"{v}_{i}" |
| 419 | taken.add(candidate) |
| 420 | result[v] = candidate |
| 421 | return result |
| 422 | |
| 423 | |
| 424 | def _parts(ts, most): |
| 425 | """Sums of 2..most summands taken from the list ts (as normal forms).""" |
| 426 | seen = set() |
| 427 | for k in range(2, min(most, len(ts)) + 1): |
| 428 | for bundle in combinations(sorted(ts, key=order_key), k): |
| 429 | if bundle not in seen: |
| 430 | seen.add(bundle) |
| 431 | yield chain(list(bundle)) |
| 432 | |
| 433 | |
| 434 | def _pool(nl, nr, most): |
| 435 | """Candidate terms for a variable that matching does not fix: all |
| 436 | subterms of the goal and sums of up to `most` summands of its sums.""" |
| 437 | terms = set() |
| 438 | for t in (nl, nr): |
| 439 | for path in positions(t): |
| 440 | v = at(t, path) |
| 441 | terms.add(v) |
| 442 | if _whole_sum(t, path): |
| 443 | terms.update(_parts(addends(v), most)) |
| 444 | return sorted(terms, key=order_key) |
| 445 | |
| 446 | |
| 447 | def _places(t, pattern, free, terms): |
| 448 | """Where the pattern fits in the normal form t: (the term with the |
| 449 | match standing alone, path of the match, substitution). A variable |
| 450 | left free by matching takes every value from `terms`.""" |
| 451 | for path in positions(t): |
| 452 | v = at(t, path) |
| 453 | options = [(s, None) for s in ac_match(pattern, v, free, {})] |
| 454 | if _whole_sum(t, path): |
| 455 | ts = addends(v) |
| 456 | if isinstance(pattern, str) and pattern in free: |
| 457 | for bundle in _parts(ts, len(ts) - 1): # a part of the sum |
| 458 | options.append(({pattern: bundle}, |
| 459 | _minus(ts, addends(bundle)))) |
| 460 | elif is_sum(pattern): |
| 461 | options += [(s, left) for s, left in |
| 462 | ac_match_part(pattern, ts, free, {}) if left] |
| 463 | for s, rest in options: |
| 464 | missing = [x for x in sorted(free) if x not in s] |
| 465 | for values in _choices(missing, terms): |
| 466 | s2 = {**s, **values} |
| 467 | u = subst(pattern, s2) |
| 468 | if rest is None: |
| 469 | yield _put(t, path, u), path, s2 |
| 470 | else: |
| 471 | yield (_put(t, path, ("+", chain(rest), u)), |
| 472 | path + (2,), s2) |
| 473 | |
| 474 | |
| 475 | def _choices(missing, terms): |
| 476 | if not missing: |
| 477 | yield {} |
| 478 | return |
| 479 | for value in terms: |
| 480 | for others in _choices(missing[1:], terms): |
| 481 | yield {missing[0]: value, **others} |
| 482 | |
| 483 | |
| 484 | def _minus(whole, part): |
| 485 | """The multiset difference whole − part, or None if part ⊄ whole.""" |
| 486 | rest = list(whole) |
| 487 | for x in part: |
| 488 | if x not in rest: |
| 489 | return None |
| 490 | rest.remove(x) |
| 491 | return rest |
| 492 | |
| 493 | |
| 494 | def _put(t, path, u): |
| 495 | if not path: |
| 496 | return u |
| 497 | i = path[0] |
| 498 | return t[:i] + (_put(t[i], path[1:], u),) + t[i + 1:] |
| 499 | |
| 500 | |
| 501 | def rewrite_at(kernel, proof, *rules, hypotheses=None, ac=False): |
| 502 | """rw [...] at h: the hypothesis u = w becomes u' = w'.""" |
| 503 | g = Goal(kernel, kernel.conclusion(proof), hypotheses) |
| 504 | (g.rw_ac if ac else g.rw)(*rules) |
| 505 | left, right = g.sides |
| 506 | return trans(symm(left.proof), proof, right.proof) or proof |
| 507 | |
| 508 | |
| 509 | def congr_n(proof): |
| 510 | """From a proof of u = w a proof of n(u) = n(w).""" |
| 511 | return CongrArg("z", ("n", "z"), proof) |
| 512 | |
| 513 | |
| 514 | class Hypothetical: |
| 515 | """A lemma with hypotheses, e.g. (Mann's lemma 35): if n(a + n(b)) = c, |
| 516 | then n(n(a + b) + c) = a. Our kernel has no implication, so the lemma |
| 517 | is proved once in a kernel where a, b, c are constants and the |
| 518 | hypotheses are axioms h1, h2, ... To use it for terms and proofs of |
| 519 | the hypotheses we substitute them into that one proof; the kernel |
| 520 | checks the result again wherever it is used.""" |
| 521 | |
| 522 | def __init__(self, base, name, constants, hypotheses, statement, |
| 523 | script): |
| 524 | K = Library({**base.signature, **{c: 0 for c in constants}}) |
| 525 | K.facts, K.assumptions = dict(base.facts), dict(base.assumptions) |
| 526 | for i, text in enumerate(hypotheses, 1): |
| 527 | K.axiom(f"h{i}", (), *equation(text)) |
| 528 | g = Goal(K, statement) |
| 529 | script(g) |
| 530 | self.proof = g.qed() |
| 531 | K.theorem(name, (), *equation(statement), self.proof) |
| 532 | self.kernel, self.name, self.constants = K, name, tuple(constants) |
| 533 | self.hypotheses = [equation(text) for text in hypotheses] |
| 534 | self.tactics = g.tactics |
| 535 | |
| 536 | def __call__(self, values, *proofs): |
| 537 | """The proof for the terms `values` (constant -> term or text) from |
| 538 | proofs of the hypotheses, in the order h1, h2, ...""" |
| 539 | values = {c: term(v) if isinstance(v, str) else v |
| 540 | for c, v in values.items()} |
| 541 | if set(values) != set(self.constants) or \ |
| 542 | len(proofs) != len(self.hypotheses): |
| 543 | raise TacticError(f"{self.name}: wrong arguments") |
| 544 | return transport(self.proof, values, |
| 545 | {f"h{i}": p for i, p in enumerate(proofs, 1)}) |
| 546 | |
| 547 | |
| 548 | class Section: |
| 549 | """Lemmas about constants that satisfy hypotheses — in Lean a section |
| 550 | with `variable (e : α) (h1 : e + e = e)`. Each lemma is proved once, |
| 551 | with the short constant e instead of a long term; `use` writes all of |
| 552 | them down again in another kernel, with terms for the constants and |
| 553 | proofs for the hypotheses (the kernel checks everything again).""" |
| 554 | |
| 555 | def __init__(self, base, constants, hypotheses): |
| 556 | K = Library({**base.signature, **{c: 0 for c in constants}}) |
| 557 | K.facts, K.assumptions = dict(base.facts), dict(base.assumptions) |
| 558 | for i, text in enumerate(hypotheses, 1): |
| 559 | K.axiom(f"h{i}", (), *equation(text)) |
| 560 | self.kernel, self.constants = K, tuple(constants) |
| 561 | self.lemmas = [] # (name, variables, l, r, proof) |
| 562 | self.tactics = {} # name -> tactic calls |
| 563 | |
| 564 | def lemma(self, name, statement, script): |
| 565 | g = Goal(self.kernel, statement) |
| 566 | script(g) |
| 567 | proof = g.qed() |
| 568 | l, r = equation(statement) if isinstance(statement, str) \ |
| 569 | else statement |
| 570 | names = [v for v in variables(r, variables(l)) |
| 571 | if self.kernel.is_var(v)] |
| 572 | self.kernel.theorem(name, names, l, r, proof) |
| 573 | self.lemmas.append((name, tuple(names), l, r, proof)) |
| 574 | self.tactics[name] = g.tactics |
| 575 | return proof |
| 576 | |
| 577 | def include(self, name, names, l, r, proof): |
| 578 | """A lemma proved elsewhere (another section used in this one).""" |
| 579 | self.kernel.theorem(name, names, l, r, proof) |
| 580 | self.lemmas.append((name, tuple(names), l, r, proof)) |
| 581 | |
| 582 | def use(self, place, values, *proofs, prefix=""): |
| 583 | """All lemmas of the section in `place` (a kernel or a section), |
| 584 | as prefix + name. A term put for a constant may bring new |
| 585 | variables (e.g. a in q(a)); they become variables of the lemmas |
| 586 | too, and every use of a lemma passes them on unchanged.""" |
| 587 | kernel = place.kernel if isinstance(place, Section) else place |
| 588 | values = {c: term(v) if isinstance(v, str) else v |
| 589 | for c, v in values.items()} |
| 590 | hypotheses = {f"h{i}": p for i, p in enumerate(proofs, 1)} |
| 591 | renamed = {} |
| 592 | for name, names, l, r, proof in self.lemmas: |
| 593 | l2, r2 = subst(l, values), subst(r, values) |
| 594 | new = [v for v in variables(r2, variables(l2)) |
| 595 | if kernel.is_var(v)] |
| 596 | p = transport(proof, values, hypotheses, renamed) |
| 597 | renamed[name] = (prefix + name, names, tuple(new)) |
| 598 | if isinstance(place, Section): |
| 599 | place.include(prefix + name, new, l2, r2, p) |
| 600 | else: |
| 601 | kernel.theorem(prefix + name, new, l2, r2, p) |
| 602 | |
| 603 | |
| 604 | def transport(proof, values, hypotheses, renamed=None): |
| 605 | """The proof with constants replaced by terms and the axioms h1, ... |
| 606 | by proofs. A CongrArg hole gets a fresh name, so that the variables |
| 607 | of the new terms cannot be caught by it.""" |
| 608 | taken = [values[c] for c in values] |
| 609 | |
| 610 | def tr(d): |
| 611 | match d: |
| 612 | case Refl(t): |
| 613 | return Refl(subst(t, values)) |
| 614 | case Symm(p): |
| 615 | return Symm(tr(p)) |
| 616 | case Trans(p, q): |
| 617 | return Trans(tr(p), tr(q)) |
| 618 | case CongrArg(z, C, p): |
| 619 | z2 = fresh(C, *taken) |
| 620 | return CongrArg(z2, subst(C, {**values, z: z2}), tr(p)) |
| 621 | case Inst(name, args): |
| 622 | if name in hypotheses: |
| 623 | return hypotheses[name] |
| 624 | args = tuple(subst(a, values) for a in args) |
| 625 | if renamed and name in renamed: # a lemma of a section |
| 626 | new_name, earlier, new = renamed[name] |
| 627 | given = dict(zip(earlier, args)) |
| 628 | return Inst(new_name, tuple(given.get(v, v) |
| 629 | for v in new)) |
| 630 | return Inst(name, args) |
| 631 | raise TacticError(f"not a proof: {d!r}") |
| 632 | return tr(proof) |
| 633 | |
| 634 | |
| 635 | def lemma(kernel, name, statement, script): |
| 636 | """A theorem: the script (a function of the goal) proves it, then |
| 637 | the kernel checks the proof and adds the theorem.""" |
| 638 | g = Goal(kernel, statement) |
| 639 | script(g) |
| 640 | proof = g.qed() |
| 641 | l, r = equation(statement) |
| 642 | kernel.theorem(name, variables(r, variables(l)), l, r, proof) |
| 643 | return proof, g.tactics |
| 644 | |
| 645 | |
| 646 | # --- how big is a proof? --------------------------------------------------- |
| 647 | |
| 648 | def nodes(proof): |
| 649 | """Rule applications in a proof tree; a use of a lemma counts once.""" |
| 650 | match proof: |
| 651 | case Refl(_) | Inst(_, _): |
| 652 | return 1 |
| 653 | case Symm(p) | CongrArg(_, _, p): |
| 654 | return 1 + nodes(p) |
| 655 | case Trans(p, q): |
| 656 | return 1 + nodes(p) + nodes(q) |
| 657 | raise TacticError(f"not a proof: {proof!r}") |
| 658 | |
| 659 | |
| 660 | def expanded(kernel, proof, memo=None): |
| 661 | """Rule applications if every lemma were replaced by its own proof, |
| 662 | again and again, down to the axioms: the size of the proof without |
| 663 | lemmas. The number is exact (Python integers have no limit).""" |
| 664 | memo = {} if memo is None else memo |
| 665 | |
| 666 | def size(d): |
| 667 | match d: |
| 668 | case Refl(_): |
| 669 | return 1 |
| 670 | case Inst(name, _): |
| 671 | if name not in kernel.proofs: |
| 672 | return 1 # an axiom |
| 673 | if name not in memo: |
| 674 | memo[name] = size(kernel.proofs[name]) |
| 675 | return memo[name] |
| 676 | case Symm(p) | CongrArg(_, _, p): |
| 677 | return 1 + size(p) |
| 678 | case Trans(p, q): |
| 679 | return 1 + size(p) + size(q) |
| 680 | raise TacticError(f"not a proof: {d!r}") |
| 681 | return size(proof) |
| 682 | |
| 683 | |
| 684 | def lemmas_used(kernel, name, seen=None): |
| 685 | """All theorems that the proof of `name` needs, directly or not.""" |
| 686 | seen = set() if seen is None else seen |
| 687 | for d in _insts(kernel.proofs[name]): |
| 688 | if d in kernel.proofs and d not in seen: |
| 689 | seen.add(d) |
| 690 | lemmas_used(kernel, d, seen) |
| 691 | return seen |
| 692 | |
| 693 | |
| 694 | def _insts(proof): |
| 695 | stack, names = [proof], set() |
| 696 | while stack: |
| 697 | d = stack.pop() |
| 698 | match d: |
| 699 | case Inst(name, _): |
| 700 | names.add(name) |
| 701 | case Symm(p) | CongrArg(_, _, p): |
| 702 | stack.append(p) |
| 703 | case Trans(p, q): |
| 704 | stack += [p, q] |
| 705 | return names |
| 706 | |
| 707 | |
| 708 | __all__ = ["theory", "Library", "Goal", "lemma", "Hypothetical", "Section", |
| 709 | "transport", "rewrite_at", "congr_n", "times", "nodes", |
| 710 | "expanded", "lemmas_used", "SIGNATURE", "AXIOMS"] |